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 /// Variables initialized by UCI options
155 // Depth limit for use of dynamic threat detection
158 // Last seconds noise filtering (LSN)
159 const bool UseLSNFiltering = true;
160 const int LSNTime = 4000; // In milliseconds
161 const Value LSNValue = value_from_centipawns(200);
162 bool loseOnTime = false;
164 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
165 Depth CheckExtension[2], SingleEvasionExtension[2], PawnPushTo7thExtension[2];
166 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
168 // Iteration counters
170 BetaCounterType BetaCounter;
172 // Scores and number of times the best move changed for each iteration
173 Value ValueByIteration[PLY_MAX_PLUS_2];
174 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
176 // Search window management
182 // Time managment variables
185 int MaxNodes, MaxDepth;
186 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
187 bool UseTimeManagement, InfiniteSearch, PonderSearch, StopOnPonderhit;
188 bool AbortSearch, Quit;
189 bool AspirationFailLow;
191 // Show current line?
192 bool ShowCurrentLine;
196 std::ofstream LogFile;
198 // Futility lookup tables and their getter functions
199 const Value FutilityMarginQS = Value(0x80);
200 int32_t FutilityMarginsMatrix[14][64]; // [depth][moveNumber]
202 inline Value futility_margin(Depth d, int mn) { return (Value) (d < 14? FutilityMarginsMatrix[Max(d, 0)][Min(mn, 63)] : 2*VALUE_INFINITE); }
204 // Reduction lookup tables and their getter functions
205 // Initialized at startup
206 int8_t PVReductionMatrix[64][64]; // [depth][moveNumber]
207 int8_t NonPVReductionMatrix[64][64]; // [depth][moveNumber]
209 inline Depth pv_reduction(Depth d, int mn) { return (Depth) PVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
210 inline Depth nonpv_reduction(Depth d, int mn) { return (Depth) NonPVReductionMatrix[Min(d / 2, 63)][Min(mn, 63)]; }
212 // MP related variables
213 int ActiveThreads = 1;
214 Depth MinimumSplitDepth;
215 int MaxThreadsPerSplitPoint;
216 Thread Threads[THREAD_MAX];
219 bool AllThreadsShouldExit = false;
220 SplitPoint SplitPointStack[THREAD_MAX][ACTIVE_SPLIT_POINTS_MAX];
223 #if !defined(_MSC_VER)
224 pthread_cond_t WaitCond;
225 pthread_mutex_t WaitLock;
227 HANDLE SitIdleEvent[THREAD_MAX];
230 // Node counters, used only by thread[0] but try to keep in different
231 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
233 int NodesBetweenPolls = 30000;
240 Value id_loop(const Position& pos, Move searchMoves[]);
241 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta);
242 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
243 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move excludedMove = MOVE_NONE);
244 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
245 void sp_search(SplitPoint* sp, int threadID);
246 void sp_search_pv(SplitPoint* sp, int threadID);
247 void init_node(SearchStack ss[], int ply, int threadID);
248 void update_pv(SearchStack ss[], int ply);
249 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
250 bool connected_moves(const Position& pos, Move m1, Move m2);
251 bool value_is_mate(Value value);
252 bool move_is_killer(Move m, const SearchStack& ss);
253 Depth extension(const Position&, Move, bool, bool, bool, bool, bool, bool*);
254 bool ok_to_do_nullmove(const Position& pos);
255 bool ok_to_prune(const Position& pos, Move m, Move threat);
256 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
257 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
258 void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
259 void update_killers(Move m, SearchStack& ss);
260 void update_gains(const Position& pos, Move move, Value before, Value after);
262 int current_search_time();
266 void print_current_line(SearchStack ss[], int ply, int threadID);
267 void wait_for_stop_or_ponderhit();
268 void init_ss_array(SearchStack ss[]);
270 void idle_loop(int threadID, SplitPoint* waitSp);
271 void init_split_point_stack();
272 void destroy_split_point_stack();
273 bool thread_should_stop(int threadID);
274 bool thread_is_available(int slave, int master);
275 bool idle_thread_exists(int master);
276 bool split(const Position& pos, SearchStack* ss, int ply,
277 Value *alpha, Value *beta, Value *bestValue,
278 const Value futilityValue, Depth depth, int *moves,
279 MovePicker *mp, int master, bool pvNode);
280 void wake_sleeping_threads();
282 #if !defined(_MSC_VER)
283 void *init_thread(void *threadID);
285 DWORD WINAPI init_thread(LPVOID threadID);
296 /// perft() is our utility to verify move generation is bug free. All the legal
297 /// moves up to given depth are generated and counted and the sum returned.
299 int perft(Position& pos, Depth depth)
303 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
305 // If we are at the last ply we don't need to do and undo
306 // the moves, just to count them.
307 if (depth <= OnePly) // Replace with '<' to test also qsearch
309 while (mp.get_next_move()) sum++;
313 // Loop through all legal moves
315 while ((move = mp.get_next_move()) != MOVE_NONE)
318 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
319 sum += perft(pos, depth - OnePly);
326 /// think() is the external interface to Stockfish's search, and is called when
327 /// the program receives the UCI 'go' command. It initializes various
328 /// search-related global variables, and calls root_search(). It returns false
329 /// when a quit command is received during the search.
331 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
332 int time[], int increment[], int movesToGo, int maxDepth,
333 int maxNodes, int maxTime, Move searchMoves[]) {
335 // Initialize global search variables
336 Idle = StopOnPonderhit = AbortSearch = Quit = false;
337 AspirationFailLow = false;
339 SearchStartTime = get_system_time();
340 ExactMaxTime = maxTime;
343 InfiniteSearch = infinite;
344 PonderSearch = ponder;
345 UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
347 // Look for a book move, only during games, not tests
348 if (UseTimeManagement && get_option_value_bool("OwnBook"))
351 if (get_option_value_string("Book File") != OpeningBook.file_name())
352 OpeningBook.open(get_option_value_string("Book File"));
354 bookMove = OpeningBook.get_move(pos);
355 if (bookMove != MOVE_NONE)
358 wait_for_stop_or_ponderhit();
360 cout << "bestmove " << bookMove << endl;
365 for (int i = 0; i < THREAD_MAX; i++)
367 Threads[i].nodes = 0ULL;
370 if (button_was_pressed("New Game"))
371 loseOnTime = false; // Reset at the beginning of a new game
373 // Read UCI option values
374 TT.set_size(get_option_value_int("Hash"));
375 if (button_was_pressed("Clear Hash"))
378 bool PonderingEnabled = get_option_value_bool("Ponder");
379 MultiPV = get_option_value_int("MultiPV");
381 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
382 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
384 SingleEvasionExtension[1] = Depth(get_option_value_int("Single Evasion Extension (PV nodes)"));
385 SingleEvasionExtension[0] = Depth(get_option_value_int("Single Evasion Extension (non-PV nodes)"));
387 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
388 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
390 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
391 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
393 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
394 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
396 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
397 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
399 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
401 Chess960 = get_option_value_bool("UCI_Chess960");
402 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
403 UseLogFile = get_option_value_bool("Use Search Log");
405 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
407 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
408 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
410 read_weights(pos.side_to_move());
412 // Set the number of active threads
413 int newActiveThreads = get_option_value_int("Threads");
414 if (newActiveThreads != ActiveThreads)
416 ActiveThreads = newActiveThreads;
417 init_eval(ActiveThreads);
418 // HACK: init_eval() destroys the static castleRightsMask[] array in the
419 // Position class. The below line repairs the damage.
420 Position p(pos.to_fen());
424 // Wake up sleeping threads
425 wake_sleeping_threads();
427 for (int i = 1; i < ActiveThreads; i++)
428 assert(thread_is_available(i, 0));
431 int myTime = time[side_to_move];
432 int myIncrement = increment[side_to_move];
433 if (UseTimeManagement)
435 if (!movesToGo) // Sudden death time control
439 MaxSearchTime = myTime / 30 + myIncrement;
440 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
442 else // Blitz game without increment
444 MaxSearchTime = myTime / 30;
445 AbsoluteMaxSearchTime = myTime / 8;
448 else // (x moves) / (y minutes)
452 MaxSearchTime = myTime / 2;
453 AbsoluteMaxSearchTime = (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
457 MaxSearchTime = myTime / Min(movesToGo, 20);
458 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
462 if (PonderingEnabled)
464 MaxSearchTime += MaxSearchTime / 4;
465 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
469 // Set best NodesBetweenPolls interval
471 NodesBetweenPolls = Min(MaxNodes, 30000);
472 else if (myTime && myTime < 1000)
473 NodesBetweenPolls = 1000;
474 else if (myTime && myTime < 5000)
475 NodesBetweenPolls = 5000;
477 NodesBetweenPolls = 30000;
479 // Write information to search log file
481 LogFile << "Searching: " << pos.to_fen() << endl
482 << "infinite: " << infinite
483 << " ponder: " << ponder
484 << " time: " << myTime
485 << " increment: " << myIncrement
486 << " moves to go: " << movesToGo << endl;
488 // LSN filtering. Used only for developing purpose. Disabled by default.
492 // Step 2. If after last move we decided to lose on time, do it now!
493 while (SearchStartTime + myTime + 1000 > get_system_time())
497 // We're ready to start thinking. Call the iterative deepening loop function
498 Value v = id_loop(pos, searchMoves);
502 // Step 1. If this is sudden death game and our position is hopeless,
503 // decide to lose on time.
504 if ( !loseOnTime // If we already lost on time, go to step 3.
514 // Step 3. Now after stepping over the time limit, reset flag for next match.
527 /// init_threads() is called during startup. It launches all helper threads,
528 /// and initializes the split point stack and the global locks and condition
531 void init_threads() {
536 #if !defined(_MSC_VER)
537 pthread_t pthread[1];
540 // Init our reduction lookup tables
541 for (i = 1; i < 64; i++) // i == depth
542 for (int j = 1; j < 64; j++) // j == moveNumber
544 double pvRed = 0.5 + log(double(i)) * log(double(j)) / 6.0;
545 double nonPVRed = 0.5 + log(double(i)) * log(double(j)) / 3.0;
546 PVReductionMatrix[i][j] = (int8_t) ( pvRed >= 1.0 ? floor( pvRed * int(OnePly)) : 0);
547 NonPVReductionMatrix[i][j] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(OnePly)) : 0);
550 // Init futility margins array
551 for (i = 0; i < 14; i++) // i == depth (OnePly = 2)
552 for (int j = 0; j < 64; j++) // j == moveNumber
554 FutilityMarginsMatrix[i][j] = (i < 2 ? 0 : 112 * bitScanReverse32(i * i / 2)) - 8 * j; // FIXME: test using log instead of BSR
557 for (i = 0; i < THREAD_MAX; i++)
558 Threads[i].activeSplitPoints = 0;
560 // Initialize global locks
561 lock_init(&MPLock, NULL);
562 lock_init(&IOLock, NULL);
564 init_split_point_stack();
566 #if !defined(_MSC_VER)
567 pthread_mutex_init(&WaitLock, NULL);
568 pthread_cond_init(&WaitCond, NULL);
570 for (i = 0; i < THREAD_MAX; i++)
571 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
574 // All threads except the main thread should be initialized to idle state
575 for (i = 1; i < THREAD_MAX; i++)
577 Threads[i].stop = false;
578 Threads[i].workIsWaiting = false;
579 Threads[i].idle = true;
580 Threads[i].running = false;
583 // Launch the helper threads
584 for (i = 1; i < THREAD_MAX; i++)
586 #if !defined(_MSC_VER)
587 ok = (pthread_create(pthread, NULL, init_thread, (void*)(&i)) == 0);
590 ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID) != NULL);
595 cout << "Failed to create thread number " << i << endl;
596 Application::exit_with_failure();
599 // Wait until the thread has finished launching
600 while (!Threads[i].running);
605 /// stop_threads() is called when the program exits. It makes all the
606 /// helper threads exit cleanly.
608 void stop_threads() {
610 ActiveThreads = THREAD_MAX; // HACK
611 Idle = false; // HACK
612 wake_sleeping_threads();
613 AllThreadsShouldExit = true;
614 for (int i = 1; i < THREAD_MAX; i++)
616 Threads[i].stop = true;
617 while (Threads[i].running);
619 destroy_split_point_stack();
623 /// nodes_searched() returns the total number of nodes searched so far in
624 /// the current search.
626 int64_t nodes_searched() {
628 int64_t result = 0ULL;
629 for (int i = 0; i < ActiveThreads; i++)
630 result += Threads[i].nodes;
635 // SearchStack::init() initializes a search stack. Used at the beginning of a
636 // new search from the root.
637 void SearchStack::init(int ply) {
639 pv[ply] = pv[ply + 1] = MOVE_NONE;
640 currentMove = threatMove = MOVE_NONE;
641 reduction = Depth(0);
646 void SearchStack::initKillers() {
648 mateKiller = MOVE_NONE;
649 for (int i = 0; i < KILLER_MAX; i++)
650 killers[i] = MOVE_NONE;
655 // id_loop() is the main iterative deepening loop. It calls root_search
656 // repeatedly with increasing depth until the allocated thinking time has
657 // been consumed, the user stops the search, or the maximum search depth is
660 Value id_loop(const Position& pos, Move searchMoves[]) {
663 SearchStack ss[PLY_MAX_PLUS_2];
665 // searchMoves are verified, copied, scored and sorted
666 RootMoveList rml(p, searchMoves);
668 // Handle special case of searching on a mate/stale position
669 if (rml.move_count() == 0)
672 wait_for_stop_or_ponderhit();
674 return pos.is_check()? -VALUE_MATE : VALUE_DRAW;
677 // Print RootMoveList c'tor startup scoring to the standard output,
678 // so that we print information also for iteration 1.
679 cout << "info depth " << 1 << "\ninfo depth " << 1
680 << " score " << value_to_string(rml.get_move_score(0))
681 << " time " << current_search_time()
682 << " nodes " << nodes_searched()
684 << " pv " << rml.get_move(0) << "\n";
690 ValueByIteration[1] = rml.get_move_score(0);
693 // Is one move significantly better than others after initial scoring ?
694 Move EasyMove = MOVE_NONE;
695 if ( rml.move_count() == 1
696 || rml.get_move_score(0) > rml.get_move_score(1) + EasyMoveMargin)
697 EasyMove = rml.get_move(0);
699 // Iterative deepening loop
700 while (Iteration < PLY_MAX)
702 // Initialize iteration
705 BestMoveChangesByIteration[Iteration] = 0;
709 cout << "info depth " << Iteration << endl;
711 // Calculate dynamic search window based on previous iterations
714 if (MultiPV == 1 && Iteration >= 6 && abs(ValueByIteration[Iteration - 1]) < VALUE_KNOWN_WIN)
716 int prevDelta1 = ValueByIteration[Iteration - 1] - ValueByIteration[Iteration - 2];
717 int prevDelta2 = ValueByIteration[Iteration - 2] - ValueByIteration[Iteration - 3];
719 AspirationDelta = Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16);
720 AspirationDelta = (AspirationDelta + 7) / 8 * 8; // Round to match grainSize
722 alpha = Max(ValueByIteration[Iteration - 1] - AspirationDelta, -VALUE_INFINITE);
723 beta = Min(ValueByIteration[Iteration - 1] + AspirationDelta, VALUE_INFINITE);
727 alpha = - VALUE_INFINITE;
728 beta = VALUE_INFINITE;
731 // Search to the current depth
732 Value value = root_search(p, ss, rml, alpha, beta);
734 // Write PV to transposition table, in case the relevant entries have
735 // been overwritten during the search.
736 TT.insert_pv(p, ss[0].pv);
739 break; // Value cannot be trusted. Break out immediately!
741 //Save info about search result
742 ValueByIteration[Iteration] = value;
744 // Drop the easy move if it differs from the new best move
745 if (ss[0].pv[0] != EasyMove)
746 EasyMove = MOVE_NONE;
748 if (UseTimeManagement)
751 bool stopSearch = false;
753 // Stop search early if there is only a single legal move,
754 // we search up to Iteration 6 anyway to get a proper score.
755 if (Iteration >= 6 && rml.move_count() == 1)
758 // Stop search early when the last two iterations returned a mate score
760 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
761 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
764 // Stop search early if one move seems to be much better than the rest
765 int64_t nodes = nodes_searched();
767 && EasyMove == ss[0].pv[0]
768 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
769 && current_search_time() > MaxSearchTime / 16)
770 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
771 && current_search_time() > MaxSearchTime / 32)))
774 // Add some extra time if the best move has changed during the last two iterations
775 if (Iteration > 5 && Iteration <= 50)
776 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
777 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
779 // Stop search if most of MaxSearchTime is consumed at the end of the
780 // iteration. We probably don't have enough time to search the first
781 // move at the next iteration anyway.
782 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime) * 80) / 128)
790 StopOnPonderhit = true;
794 if (MaxDepth && Iteration >= MaxDepth)
800 // If we are pondering or in infinite search, we shouldn't print the
801 // best move before we are told to do so.
802 if (!AbortSearch && (PonderSearch || InfiniteSearch))
803 wait_for_stop_or_ponderhit();
805 // Print final search statistics
806 cout << "info nodes " << nodes_searched()
808 << " time " << current_search_time()
809 << " hashfull " << TT.full() << endl;
811 // Print the best move and the ponder move to the standard output
812 if (ss[0].pv[0] == MOVE_NONE)
814 ss[0].pv[0] = rml.get_move(0);
815 ss[0].pv[1] = MOVE_NONE;
817 cout << "bestmove " << ss[0].pv[0];
818 if (ss[0].pv[1] != MOVE_NONE)
819 cout << " ponder " << ss[0].pv[1];
826 dbg_print_mean(LogFile);
828 if (dbg_show_hit_rate)
829 dbg_print_hit_rate(LogFile);
831 LogFile << "\nNodes: " << nodes_searched()
832 << "\nNodes/second: " << nps()
833 << "\nBest move: " << move_to_san(p, ss[0].pv[0]);
836 p.do_move(ss[0].pv[0], st);
837 LogFile << "\nPonder move: " << move_to_san(p, ss[0].pv[1]) << endl;
839 return rml.get_move_score(0);
843 // root_search() is the function which searches the root node. It is
844 // similar to search_pv except that it uses a different move ordering
845 // scheme and prints some information to the standard output.
847 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value& oldAlpha, Value& beta) {
852 Depth depth, ext, newDepth;
855 int researchCount = 0;
856 bool moveIsCheck, captureOrPromotion, dangerous;
857 Value alpha = oldAlpha;
858 bool isCheck = pos.is_check();
860 // Evaluate the position statically
862 ss[0].eval = !isCheck ? evaluate(pos, ei, 0) : VALUE_NONE;
864 while (1) // Fail low loop
867 // Loop through all the moves in the root move list
868 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
872 // We failed high, invalidate and skip next moves, leave node-counters
873 // and beta-counters as they are and quickly return, we will try to do
874 // a research at the next iteration with a bigger aspiration window.
875 rml.set_move_score(i, -VALUE_INFINITE);
879 RootMoveNumber = i + 1;
881 // Save the current node count before the move is searched
882 nodes = nodes_searched();
884 // Reset beta cut-off counters
887 // Pick the next root move, and print the move and the move number to
888 // the standard output.
889 move = ss[0].currentMove = rml.get_move(i);
891 if (current_search_time() >= 1000)
892 cout << "info currmove " << move
893 << " currmovenumber " << RootMoveNumber << endl;
895 // Decide search depth for this move
896 moveIsCheck = pos.move_is_check(move);
897 captureOrPromotion = pos.move_is_capture_or_promotion(move);
898 depth = (Iteration - 2) * OnePly + InitialDepth;
899 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
900 newDepth = depth + ext;
902 value = - VALUE_INFINITE;
904 while (1) // Fail high loop
907 // Make the move, and search it
908 pos.do_move(move, st, ci, moveIsCheck);
910 if (i < MultiPV || value > alpha)
912 // Aspiration window is disabled in multi-pv case
914 alpha = -VALUE_INFINITE;
916 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
920 // Try to reduce non-pv search depth by one ply if move seems not problematic,
921 // if the move fails high will be re-searched at full depth.
922 bool doFullDepthSearch = true;
924 if ( depth >= 3*OnePly // FIXME was newDepth
926 && !captureOrPromotion
927 && !move_is_castle(move))
929 ss[0].reduction = pv_reduction(depth, RootMoveNumber - MultiPV + 1);
932 value = -search(pos, ss, -alpha, newDepth-ss[0].reduction, 1, true, 0);
933 doFullDepthSearch = (value > alpha);
937 if (doFullDepthSearch)
939 ss[0].reduction = Depth(0);
940 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
943 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
949 // Can we exit fail high loop ?
950 if (AbortSearch || value < beta)
953 // We are failing high and going to do a research. It's important to update score
954 // before research in case we run out of time while researching.
955 rml.set_move_score(i, value);
957 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
958 rml.set_move_pv(i, ss[0].pv);
960 // Print search information to the standard output
961 cout << "info depth " << Iteration
962 << " score " << value_to_string(value)
963 << ((value >= beta) ? " lowerbound" :
964 ((value <= alpha)? " upperbound" : ""))
965 << " time " << current_search_time()
966 << " nodes " << nodes_searched()
970 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
971 cout << ss[0].pv[j] << " ";
977 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
978 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
980 LogFile << pretty_pv(pos, current_search_time(), Iteration,
981 nodes_searched(), value, type, ss[0].pv) << endl;
984 // Prepare for a research after a fail high, each time with a wider window
986 beta = Min(beta + AspirationDelta * (1 << researchCount), VALUE_INFINITE);
988 } // End of fail high loop
990 // Finished searching the move. If AbortSearch is true, the search
991 // was aborted because the user interrupted the search or because we
992 // ran out of time. In this case, the return value of the search cannot
993 // be trusted, and we break out of the loop without updating the best
998 // Remember beta-cutoff and searched nodes counts for this move. The
999 // info is used to sort the root moves at the next iteration.
1001 BetaCounter.read(pos.side_to_move(), our, their);
1002 rml.set_beta_counters(i, our, their);
1003 rml.set_move_nodes(i, nodes_searched() - nodes);
1005 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
1007 if (value <= alpha && i >= MultiPV)
1008 rml.set_move_score(i, -VALUE_INFINITE);
1011 // PV move or new best move!
1014 rml.set_move_score(i, value);
1016 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
1017 rml.set_move_pv(i, ss[0].pv);
1021 // We record how often the best move has been changed in each
1022 // iteration. This information is used for time managment: When
1023 // the best move changes frequently, we allocate some more time.
1025 BestMoveChangesByIteration[Iteration]++;
1027 // Print search information to the standard output
1028 cout << "info depth " << Iteration
1029 << " score " << value_to_string(value)
1030 << ((value >= beta) ? " lowerbound" :
1031 ((value <= alpha)? " upperbound" : ""))
1032 << " time " << current_search_time()
1033 << " nodes " << nodes_searched()
1037 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1038 cout << ss[0].pv[j] << " ";
1044 ValueType type = (value >= beta ? VALUE_TYPE_LOWER
1045 : (value <= alpha ? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT));
1047 LogFile << pretty_pv(pos, current_search_time(), Iteration,
1048 nodes_searched(), value, type, ss[0].pv) << endl;
1055 rml.sort_multipv(i);
1056 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1058 cout << "info multipv " << j + 1
1059 << " score " << value_to_string(rml.get_move_score(j))
1060 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1061 << " time " << current_search_time()
1062 << " nodes " << nodes_searched()
1066 for (int k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1067 cout << rml.get_move_pv(j, k) << " ";
1071 alpha = rml.get_move_score(Min(i, MultiPV-1));
1073 } // PV move or new best move
1075 assert(alpha >= oldAlpha);
1077 AspirationFailLow = (alpha == oldAlpha);
1079 if (AspirationFailLow && StopOnPonderhit)
1080 StopOnPonderhit = false;
1083 // Can we exit fail low loop ?
1084 if (AbortSearch || alpha > oldAlpha)
1087 // Prepare for a research after a fail low, each time with a wider window
1089 alpha = Max(alpha - AspirationDelta * (1 << researchCount), -VALUE_INFINITE);
1098 // search_pv() is the main search function for PV nodes.
1100 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1101 Depth depth, int ply, int threadID) {
1103 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1104 assert(beta > alpha && beta <= VALUE_INFINITE);
1105 assert(ply >= 0 && ply < PLY_MAX);
1106 assert(threadID >= 0 && threadID < ActiveThreads);
1108 Move movesSearched[256];
1112 Depth ext, newDepth;
1113 Value oldAlpha, value;
1114 bool isCheck, mateThreat, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1116 Value bestValue = value = -VALUE_INFINITE;
1119 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1121 // Initialize, and make an early exit in case of an aborted search,
1122 // an instant draw, maximum ply reached, etc.
1123 init_node(ss, ply, threadID);
1125 // After init_node() that calls poll()
1126 if (AbortSearch || thread_should_stop(threadID))
1129 if (pos.is_draw() || ply >= PLY_MAX - 1)
1132 // Mate distance pruning
1134 alpha = Max(value_mated_in(ply), alpha);
1135 beta = Min(value_mate_in(ply+1), beta);
1139 // Transposition table lookup. At PV nodes, we don't use the TT for
1140 // pruning, but only for move ordering. This is to avoid problems in
1141 // the following areas:
1143 // * Repetition draw detection
1144 // * Fifty move rule detection
1145 // * Searching for a mate
1146 // * Printing of full PV line
1148 tte = TT.retrieve(pos.get_key());
1149 ttMove = (tte ? tte->move() : MOVE_NONE);
1151 // Go with internal iterative deepening if we don't have a TT move
1152 if ( UseIIDAtPVNodes
1153 && depth >= 5*OnePly
1154 && ttMove == MOVE_NONE)
1156 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1157 ttMove = ss[ply].pv[ply];
1158 tte = TT.retrieve(pos.get_key());
1161 isCheck = pos.is_check();
1164 // Update gain statistics of the previous move that lead
1165 // us in this position.
1167 ss[ply].eval = evaluate(pos, ei, threadID);
1168 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1171 // Initialize a MovePicker object for the current position, and prepare
1172 // to search all moves
1173 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1175 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1177 // Loop through all legal moves until no moves remain or a beta cutoff
1179 while ( alpha < beta
1180 && (move = mp.get_next_move()) != MOVE_NONE
1181 && !thread_should_stop(threadID))
1183 assert(move_is_ok(move));
1185 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1186 moveIsCheck = pos.move_is_check(move, ci);
1187 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1189 // Decide the new search depth
1190 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1192 // Singular extension search. We extend the TT move if its value is much better than
1193 // its siblings. To verify this we do a reduced search on all the other moves but the
1194 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1195 if ( depth >= 6 * OnePly
1197 && move == tte->move()
1199 && is_lower_bound(tte->type())
1200 && tte->depth() >= depth - 3 * OnePly)
1202 Value ttValue = value_from_tt(tte->value(), ply);
1204 if (abs(ttValue) < VALUE_KNOWN_WIN)
1206 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1208 if (excValue < ttValue - SingleReplyMargin)
1213 newDepth = depth - OnePly + ext;
1215 // Update current move
1216 movesSearched[moveCount++] = ss[ply].currentMove = move;
1218 // Make and search the move
1219 pos.do_move(move, st, ci, moveIsCheck);
1221 if (moveCount == 1) // The first move in list is the PV
1222 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1225 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1226 // if the move fails high will be re-searched at full depth.
1227 bool doFullDepthSearch = true;
1229 if ( depth >= 3*OnePly
1231 && !captureOrPromotion
1232 && !move_is_castle(move)
1233 && !move_is_killer(move, ss[ply]))
1235 ss[ply].reduction = pv_reduction(depth, moveCount);
1236 if (ss[ply].reduction)
1238 value = -search(pos, ss, -alpha, newDepth-ss[ply].reduction, ply+1, true, threadID);
1239 doFullDepthSearch = (value > alpha);
1243 if (doFullDepthSearch) // Go with full depth non-pv search
1245 ss[ply].reduction = Depth(0);
1246 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1247 if (value > alpha && value < beta)
1248 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1251 pos.undo_move(move);
1253 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1256 if (value > bestValue)
1263 if (value == value_mate_in(ply + 1))
1264 ss[ply].mateKiller = move;
1269 if ( ActiveThreads > 1
1271 && depth >= MinimumSplitDepth
1273 && idle_thread_exists(threadID)
1275 && !thread_should_stop(threadID)
1276 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE,
1277 depth, &moveCount, &mp, threadID, true))
1281 // All legal moves have been searched. A special case: If there were
1282 // no legal moves, it must be mate or stalemate.
1284 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1286 // If the search is not aborted, update the transposition table,
1287 // history counters, and killer moves.
1288 if (AbortSearch || thread_should_stop(threadID))
1291 if (bestValue <= oldAlpha)
1292 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1294 else if (bestValue >= beta)
1296 BetaCounter.add(pos.side_to_move(), depth, threadID);
1297 move = ss[ply].pv[ply];
1298 if (!pos.move_is_capture_or_promotion(move))
1300 update_history(pos, move, depth, movesSearched, moveCount);
1301 update_killers(move, ss[ply]);
1303 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1306 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1312 // search() is the search function for zero-width nodes.
1314 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1315 int ply, bool allowNullmove, int threadID, Move excludedMove) {
1317 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1318 assert(ply >= 0 && ply < PLY_MAX);
1319 assert(threadID >= 0 && threadID < ActiveThreads);
1321 Move movesSearched[256];
1326 Depth ext, newDepth;
1327 Value bestValue, staticValue, nullValue, value, futilityValue, futilityValueScaled;
1328 bool isCheck, singleEvasion, moveIsCheck, captureOrPromotion, dangerous;
1329 bool mateThreat = false;
1331 futilityValue = staticValue = bestValue = value = -VALUE_INFINITE;
1334 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1336 // Initialize, and make an early exit in case of an aborted search,
1337 // an instant draw, maximum ply reached, etc.
1338 init_node(ss, ply, threadID);
1340 // After init_node() that calls poll()
1341 if (AbortSearch || thread_should_stop(threadID))
1344 if (pos.is_draw() || ply >= PLY_MAX - 1)
1347 // Mate distance pruning
1348 if (value_mated_in(ply) >= beta)
1351 if (value_mate_in(ply + 1) < beta)
1354 // We don't want the score of a partial search to overwrite a previous full search
1355 // TT value, so we use a different position key in case of an excluded move exsists.
1356 Key posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
1358 // Transposition table lookup
1359 tte = TT.retrieve(posKey);
1360 ttMove = (tte ? tte->move() : MOVE_NONE);
1362 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1364 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1365 return value_from_tt(tte->value(), ply);
1368 isCheck = pos.is_check();
1370 // Calculate depth dependant futility pruning parameters
1371 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(depth) / 8));
1373 // Evaluate the position statically
1376 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1377 staticValue = value_from_tt(tte->value(), ply);
1380 staticValue = evaluate(pos, ei, threadID);
1381 ss[ply].evalInfo = &ei;
1384 ss[ply].eval = staticValue;
1385 futilityValue = staticValue + futility_margin(depth, 0); //FIXME: Remove me, only for split
1386 staticValue = refine_eval(tte, staticValue, ply); // Enhance accuracy with TT value if possible
1387 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1390 // Static null move pruning. We're betting that the opponent doesn't have
1391 // a move that will reduce the score by more than FutilityMargins[int(depth)]
1392 // if we do a null move.
1395 && depth < RazorDepth
1396 && staticValue - futility_margin(depth, 0) >= beta)
1397 return staticValue - futility_margin(depth, 0);
1403 && !value_is_mate(beta)
1404 && ok_to_do_nullmove(pos)
1405 && staticValue >= beta - NullMoveMargin)
1407 ss[ply].currentMove = MOVE_NULL;
1409 pos.do_null_move(st);
1411 // Null move dynamic reduction based on depth
1412 int R = 3 + (depth >= 5 * OnePly ? depth / 8 : 0);
1414 // Null move dynamic reduction based on value
1415 if (staticValue - beta > PawnValueMidgame)
1418 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1420 pos.undo_null_move();
1422 if (nullValue >= beta)
1424 if (depth < 6 * OnePly)
1427 // Do zugzwang verification search
1428 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1432 // The null move failed low, which means that we may be faced with
1433 // some kind of threat. If the previous move was reduced, check if
1434 // the move that refuted the null move was somehow connected to the
1435 // move which was reduced. If a connection is found, return a fail
1436 // low score (which will cause the reduced move to fail high in the
1437 // parent node, which will trigger a re-search with full depth).
1438 if (nullValue == value_mated_in(ply + 2))
1441 ss[ply].threatMove = ss[ply + 1].currentMove;
1442 if ( depth < ThreatDepth
1443 && ss[ply - 1].reduction
1444 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1448 // Null move search not allowed, try razoring
1449 else if ( !value_is_mate(beta)
1451 && depth < RazorDepth
1452 && staticValue < beta - (NullMoveMargin + 16 * depth)
1453 && ss[ply - 1].currentMove != MOVE_NULL
1454 && ttMove == MOVE_NONE
1455 && !pos.has_pawn_on_7th(pos.side_to_move()))
1457 Value rbeta = beta - (NullMoveMargin + 16 * depth);
1458 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1463 // Go with internal iterative deepening if we don't have a TT move
1464 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1465 !isCheck && ss[ply].eval >= beta - IIDMargin)
1467 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1468 ttMove = ss[ply].pv[ply];
1469 tte = TT.retrieve(posKey);
1472 // Initialize a MovePicker object for the current position, and prepare
1473 // to search all moves.
1474 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1477 // Loop through all legal moves until no moves remain or a beta cutoff occurs
1478 while ( bestValue < beta
1479 && (move = mp.get_next_move()) != MOVE_NONE
1480 && !thread_should_stop(threadID))
1482 assert(move_is_ok(move));
1484 if (move == excludedMove)
1487 moveIsCheck = pos.move_is_check(move, ci);
1488 singleEvasion = (isCheck && mp.number_of_evasions() == 1);
1489 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1491 // Decide the new search depth
1492 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleEvasion, mateThreat, &dangerous);
1494 // Singular extension search. We extend the TT move if its value is much better than
1495 // its siblings. To verify this we do a reduced search on all the other moves but the
1496 // ttMove, if result is lower then ttValue minus a margin then we extend ttMove.
1497 if ( depth >= 8 * OnePly
1499 && move == tte->move()
1500 && !excludedMove // Do not allow recursive single-reply search
1502 && is_lower_bound(tte->type())
1503 && tte->depth() >= depth - 3 * OnePly)
1505 Value ttValue = value_from_tt(tte->value(), ply);
1507 if (abs(ttValue) < VALUE_KNOWN_WIN)
1509 Value excValue = search(pos, ss, ttValue - SingleReplyMargin, depth / 2, ply, false, threadID, move);
1511 if (excValue < ttValue - SingleReplyMargin)
1516 newDepth = depth - OnePly + ext;
1518 // Update current move
1519 movesSearched[moveCount++] = ss[ply].currentMove = move;
1524 && !captureOrPromotion
1525 && !move_is_castle(move)
1528 // Move count based pruning
1529 if ( moveCount >= FutilityMoveCountMargin
1530 && ok_to_prune(pos, move, ss[ply].threatMove)
1531 && bestValue > value_mated_in(PLY_MAX))
1534 // Value based pruning
1535 Depth predictedDepth = newDepth - nonpv_reduction(depth, moveCount); //FIXME: We are ignoring condition: depth >= 3*OnePly, BUG??
1536 futilityValueScaled = ss[ply].eval + futility_margin(predictedDepth, moveCount) + H.gain(pos.piece_on(move_from(move)), move_to(move)) + 45;
1538 if (futilityValueScaled < beta)
1540 if (futilityValueScaled > bestValue)
1541 bestValue = futilityValueScaled;
1546 // Make and search the move
1547 pos.do_move(move, st, ci, moveIsCheck);
1549 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1550 // if the move fails high will be re-searched at full depth.
1551 bool doFullDepthSearch = true;
1553 if ( depth >= 3*OnePly
1555 && !captureOrPromotion
1556 && !move_is_castle(move)
1557 && !move_is_killer(move, ss[ply]))
1559 ss[ply].reduction = nonpv_reduction(depth, moveCount);
1560 if (ss[ply].reduction)
1562 value = -search(pos, ss, -(beta-1), newDepth-ss[ply].reduction, ply+1, true, threadID);
1563 doFullDepthSearch = (value >= beta);
1567 if (doFullDepthSearch) // Go with full depth non-pv search
1569 ss[ply].reduction = Depth(0);
1570 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1572 pos.undo_move(move);
1574 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1577 if (value > bestValue)
1583 if (value == value_mate_in(ply + 1))
1584 ss[ply].mateKiller = move;
1588 if ( ActiveThreads > 1
1590 && depth >= MinimumSplitDepth
1592 && idle_thread_exists(threadID)
1594 && !thread_should_stop(threadID)
1595 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, //FIXME: SMP & futilityValue
1596 depth, &moveCount, &mp, threadID, false))
1600 // All legal moves have been searched. A special case: If there were
1601 // no legal moves, it must be mate or stalemate.
1603 return excludedMove ? beta - 1 : (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1605 // If the search is not aborted, update the transposition table,
1606 // history counters, and killer moves.
1607 if (AbortSearch || thread_should_stop(threadID))
1610 if (bestValue < beta)
1611 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1614 BetaCounter.add(pos.side_to_move(), depth, threadID);
1615 move = ss[ply].pv[ply];
1616 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1617 if (!pos.move_is_capture_or_promotion(move))
1619 update_history(pos, move, depth, movesSearched, moveCount);
1620 update_killers(move, ss[ply]);
1625 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1631 // qsearch() is the quiescence search function, which is called by the main
1632 // search function when the remaining depth is zero (or, to be more precise,
1633 // less than OnePly).
1635 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1636 Depth depth, int ply, int threadID) {
1638 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1639 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1641 assert(ply >= 0 && ply < PLY_MAX);
1642 assert(threadID >= 0 && threadID < ActiveThreads);
1647 Value staticValue, bestValue, value, futilityBase, futilityValue;
1648 bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1649 const TTEntry* tte = NULL;
1651 bool pvNode = (beta - alpha != 1);
1652 Value oldAlpha = alpha;
1654 // Initialize, and make an early exit in case of an aborted search,
1655 // an instant draw, maximum ply reached, etc.
1656 init_node(ss, ply, threadID);
1658 // After init_node() that calls poll()
1659 if (AbortSearch || thread_should_stop(threadID))
1662 if (pos.is_draw() || ply >= PLY_MAX - 1)
1665 // Transposition table lookup. At PV nodes, we don't use the TT for
1666 // pruning, but only for move ordering.
1667 tte = TT.retrieve(pos.get_key());
1668 ttMove = (tte ? tte->move() : MOVE_NONE);
1670 if (!pvNode && tte && ok_to_use_TT(tte, depth, beta, ply))
1672 assert(tte->type() != VALUE_TYPE_EVAL);
1674 ss[ply].currentMove = ttMove; // Can be MOVE_NONE
1675 return value_from_tt(tte->value(), ply);
1678 isCheck = pos.is_check();
1680 // Evaluate the position statically
1682 staticValue = -VALUE_INFINITE;
1683 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1684 staticValue = value_from_tt(tte->value(), ply);
1686 staticValue = evaluate(pos, ei, threadID);
1690 ss[ply].eval = staticValue;
1691 update_gains(pos, ss[ply - 1].currentMove, ss[ply - 1].eval, ss[ply].eval);
1694 // Initialize "stand pat score", and return it immediately if it is
1696 bestValue = staticValue;
1698 if (bestValue >= beta)
1700 // Store the score to avoid a future costly evaluation() call
1701 if (!isCheck && !tte && ei.futilityMargin[pos.side_to_move()] == 0)
1702 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1707 if (bestValue > alpha)
1710 // If we are near beta then try to get a cutoff pushing checks a bit further
1711 bool deepChecks = depth == -OnePly && staticValue >= beta - PawnValueMidgame / 8;
1713 // Initialize a MovePicker object for the current position, and prepare
1714 // to search the moves. Because the depth is <= 0 here, only captures,
1715 // queen promotions and checks (only if depth == 0 or depth == -OnePly
1716 // and we are near beta) will be generated.
1717 MovePicker mp = MovePicker(pos, ttMove, deepChecks ? Depth(0) : depth, H);
1719 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1720 futilityBase = staticValue + FutilityMarginQS + ei.futilityMargin[pos.side_to_move()];
1722 // Loop through the moves until no moves remain or a beta cutoff
1724 while ( alpha < beta
1725 && (move = mp.get_next_move()) != MOVE_NONE)
1727 assert(move_is_ok(move));
1729 moveIsCheck = pos.move_is_check(move, ci);
1731 // Update current move
1733 ss[ply].currentMove = move;
1741 && !move_is_promotion(move)
1742 && !pos.move_is_passed_pawn_push(move))
1744 futilityValue = futilityBase
1745 + pos.endgame_value_of_piece_on(move_to(move))
1746 + (move_is_ep(move) ? PawnValueEndgame : Value(0));
1748 if (futilityValue < alpha)
1750 if (futilityValue > bestValue)
1751 bestValue = futilityValue;
1756 // Detect blocking evasions that are candidate to be pruned
1757 evasionPrunable = isCheck
1758 && bestValue != -VALUE_INFINITE
1759 && !pos.move_is_capture(move)
1760 && pos.type_of_piece_on(move_from(move)) != KING
1761 && !pos.can_castle(pos.side_to_move());
1763 // Don't search moves with negative SEE values
1764 if ( (!isCheck || evasionPrunable)
1766 && !move_is_promotion(move)
1767 && pos.see_sign(move) < 0)
1770 // Make and search the move
1771 pos.do_move(move, st, ci, moveIsCheck);
1772 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1773 pos.undo_move(move);
1775 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1778 if (value > bestValue)
1789 // All legal moves have been searched. A special case: If we're in check
1790 // and no legal moves were found, it is checkmate.
1791 if (!moveCount && pos.is_check()) // Mate!
1792 return value_mated_in(ply);
1794 // Update transposition table
1795 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1796 if (bestValue <= oldAlpha)
1798 // If bestValue isn't changed it means it is still the static evaluation
1799 // of the node, so keep this info to avoid a future evaluation() call.
1800 ValueType type = (bestValue == staticValue && !ei.futilityMargin[pos.side_to_move()] ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1801 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1803 else if (bestValue >= beta)
1805 move = ss[ply].pv[ply];
1806 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1808 // Update killers only for good checking moves
1809 if (!pos.move_is_capture_or_promotion(move))
1810 update_killers(move, ss[ply]);
1813 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, d, ss[ply].pv[ply]);
1815 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1821 // sp_search() is used to search from a split point. This function is called
1822 // by each thread working at the split point. It is similar to the normal
1823 // search() function, but simpler. Because we have already probed the hash
1824 // table, done a null move search, and searched the first move before
1825 // splitting, we don't have to repeat all this work in sp_search(). We
1826 // also don't need to store anything to the hash table here: This is taken
1827 // care of after we return from the split point.
1829 void sp_search(SplitPoint* sp, int threadID) {
1831 assert(threadID >= 0 && threadID < ActiveThreads);
1832 assert(ActiveThreads > 1);
1834 Position pos(*sp->pos);
1836 SearchStack* ss = sp->sstack[threadID];
1837 Value value = -VALUE_INFINITE;
1840 bool isCheck = pos.is_check();
1841 bool useFutilityPruning = sp->depth < 7 * OnePly //FIXME: sync with search
1844 const int FutilityMoveCountMargin = 3 + (1 << (3 * int(sp->depth) / 8));
1846 while ( lock_grab_bool(&(sp->lock))
1847 && sp->bestValue < sp->beta
1848 && !thread_should_stop(threadID)
1849 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1851 moveCount = ++sp->moves;
1852 lock_release(&(sp->lock));
1854 assert(move_is_ok(move));
1856 bool moveIsCheck = pos.move_is_check(move, ci);
1857 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1859 ss[sp->ply].currentMove = move;
1861 // Decide the new search depth
1863 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1864 Depth newDepth = sp->depth - OnePly + ext;
1867 if ( useFutilityPruning
1869 && !captureOrPromotion)
1871 // Move count based pruning
1872 if ( moveCount >= FutilityMoveCountMargin
1873 && ok_to_prune(pos, move, ss[sp->ply].threatMove)
1874 && sp->bestValue > value_mated_in(PLY_MAX))
1877 // Value based pruning
1878 Value futilityValueScaled = sp->futilityValue - moveCount * 8; //FIXME: sync with search
1880 if (futilityValueScaled < sp->beta)
1882 if (futilityValueScaled > sp->bestValue) // Less then 1% of cases
1884 lock_grab(&(sp->lock));
1885 if (futilityValueScaled > sp->bestValue)
1886 sp->bestValue = futilityValueScaled;
1887 lock_release(&(sp->lock));
1893 // Make and search the move.
1895 pos.do_move(move, st, ci, moveIsCheck);
1897 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1898 // if the move fails high will be re-searched at full depth.
1899 bool doFullDepthSearch = true;
1902 && !captureOrPromotion
1903 && !move_is_castle(move)
1904 && !move_is_killer(move, ss[sp->ply]))
1906 ss[sp->ply].reduction = nonpv_reduction(sp->depth, moveCount);
1907 if (ss[sp->ply].reduction)
1909 value = -search(pos, ss, -(sp->beta-1), newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
1910 doFullDepthSearch = (value >= sp->beta);
1914 if (doFullDepthSearch) // Go with full depth non-pv search
1916 ss[sp->ply].reduction = Depth(0);
1917 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1919 pos.undo_move(move);
1921 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1923 if (thread_should_stop(threadID))
1925 lock_grab(&(sp->lock));
1930 if (value > sp->bestValue) // Less then 2% of cases
1932 lock_grab(&(sp->lock));
1933 if (value > sp->bestValue && !thread_should_stop(threadID))
1935 sp->bestValue = value;
1936 if (sp->bestValue >= sp->beta)
1938 sp_update_pv(sp->parentSstack, ss, sp->ply);
1939 for (int i = 0; i < ActiveThreads; i++)
1940 if (i != threadID && (i == sp->master || sp->slaves[i]))
1941 Threads[i].stop = true;
1943 sp->finished = true;
1946 lock_release(&(sp->lock));
1950 /* Here we have the lock still grabbed */
1952 // If this is the master thread and we have been asked to stop because of
1953 // a beta cutoff higher up in the tree, stop all slave threads.
1954 if (sp->master == threadID && thread_should_stop(threadID))
1955 for (int i = 0; i < ActiveThreads; i++)
1957 Threads[i].stop = true;
1960 sp->slaves[threadID] = 0;
1962 lock_release(&(sp->lock));
1966 // sp_search_pv() is used to search from a PV split point. This function
1967 // is called by each thread working at the split point. It is similar to
1968 // the normal search_pv() function, but simpler. Because we have already
1969 // probed the hash table and searched the first move before splitting, we
1970 // don't have to repeat all this work in sp_search_pv(). We also don't
1971 // need to store anything to the hash table here: This is taken care of
1972 // after we return from the split point.
1974 void sp_search_pv(SplitPoint* sp, int threadID) {
1976 assert(threadID >= 0 && threadID < ActiveThreads);
1977 assert(ActiveThreads > 1);
1979 Position pos(*sp->pos);
1981 SearchStack* ss = sp->sstack[threadID];
1982 Value value = -VALUE_INFINITE;
1986 while ( lock_grab_bool(&(sp->lock))
1987 && sp->alpha < sp->beta
1988 && !thread_should_stop(threadID)
1989 && (move = sp->mp->get_next_move()) != MOVE_NONE)
1991 moveCount = ++sp->moves;
1992 lock_release(&(sp->lock));
1994 assert(move_is_ok(move));
1996 bool moveIsCheck = pos.move_is_check(move, ci);
1997 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1999 ss[sp->ply].currentMove = move;
2001 // Decide the new search depth
2003 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
2004 Depth newDepth = sp->depth - OnePly + ext;
2006 // Make and search the move.
2008 pos.do_move(move, st, ci, moveIsCheck);
2010 // Try to reduce non-pv search depth by one ply if move seems not problematic,
2011 // if the move fails high will be re-searched at full depth.
2012 bool doFullDepthSearch = true;
2015 && !captureOrPromotion
2016 && !move_is_castle(move)
2017 && !move_is_killer(move, ss[sp->ply]))
2019 ss[sp->ply].reduction = pv_reduction(sp->depth, moveCount);
2020 if (ss[sp->ply].reduction)
2022 Value localAlpha = sp->alpha;
2023 value = -search(pos, ss, -localAlpha, newDepth-ss[sp->ply].reduction, sp->ply+1, true, threadID);
2024 doFullDepthSearch = (value > localAlpha);
2028 if (doFullDepthSearch) // Go with full depth non-pv search
2030 Value localAlpha = sp->alpha;
2031 ss[sp->ply].reduction = Depth(0);
2032 value = -search(pos, ss, -localAlpha, newDepth, sp->ply+1, true, threadID);
2034 if (value > localAlpha && value < sp->beta)
2036 // If another thread has failed high then sp->alpha has been increased
2037 // to be higher or equal then beta, if so, avoid to start a PV search.
2038 localAlpha = sp->alpha;
2039 if (localAlpha < sp->beta)
2040 value = -search_pv(pos, ss, -sp->beta, -localAlpha, newDepth, sp->ply+1, threadID);
2042 assert(thread_should_stop(threadID));
2045 pos.undo_move(move);
2047 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
2049 if (thread_should_stop(threadID))
2051 lock_grab(&(sp->lock));
2056 if (value > sp->bestValue) // Less then 2% of cases
2058 lock_grab(&(sp->lock));
2059 if (value > sp->bestValue && !thread_should_stop(threadID))
2061 sp->bestValue = value;
2062 if (value > sp->alpha)
2064 // Ask threads to stop before to modify sp->alpha
2065 if (value >= sp->beta)
2067 for (int i = 0; i < ActiveThreads; i++)
2068 if (i != threadID && (i == sp->master || sp->slaves[i]))
2069 Threads[i].stop = true;
2071 sp->finished = true;
2076 sp_update_pv(sp->parentSstack, ss, sp->ply);
2077 if (value == value_mate_in(sp->ply + 1))
2078 ss[sp->ply].mateKiller = move;
2081 lock_release(&(sp->lock));
2085 /* Here we have the lock still grabbed */
2087 // If this is the master thread and we have been asked to stop because of
2088 // a beta cutoff higher up in the tree, stop all slave threads.
2089 if (sp->master == threadID && thread_should_stop(threadID))
2090 for (int i = 0; i < ActiveThreads; i++)
2092 Threads[i].stop = true;
2095 sp->slaves[threadID] = 0;
2097 lock_release(&(sp->lock));
2100 /// The BetaCounterType class
2102 BetaCounterType::BetaCounterType() { clear(); }
2104 void BetaCounterType::clear() {
2106 for (int i = 0; i < THREAD_MAX; i++)
2107 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2110 void BetaCounterType::add(Color us, Depth d, int threadID) {
2112 // Weighted count based on depth
2113 Threads[threadID].betaCutOffs[us] += unsigned(d);
2116 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2119 for (int i = 0; i < THREAD_MAX; i++)
2121 our += Threads[i].betaCutOffs[us];
2122 their += Threads[i].betaCutOffs[opposite_color(us)];
2127 /// The RootMoveList class
2129 // RootMoveList c'tor
2131 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2133 SearchStack ss[PLY_MAX_PLUS_2];
2134 MoveStack mlist[MaxRootMoves];
2136 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2138 // Generate all legal moves
2139 MoveStack* last = generate_moves(pos, mlist);
2141 // Add each move to the moves[] array
2142 for (MoveStack* cur = mlist; cur != last; cur++)
2144 bool includeMove = includeAllMoves;
2146 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2147 includeMove = (searchMoves[k] == cur->move);
2152 // Find a quick score for the move
2154 pos.do_move(cur->move, st);
2155 moves[count].move = cur->move;
2156 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2157 moves[count].pv[0] = cur->move;
2158 moves[count].pv[1] = MOVE_NONE;
2159 pos.undo_move(cur->move);
2166 // RootMoveList simple methods definitions
2168 void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2170 moves[moveNum].nodes = nodes;
2171 moves[moveNum].cumulativeNodes += nodes;
2174 void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2176 moves[moveNum].ourBeta = our;
2177 moves[moveNum].theirBeta = their;
2180 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2184 for (j = 0; pv[j] != MOVE_NONE; j++)
2185 moves[moveNum].pv[j] = pv[j];
2187 moves[moveNum].pv[j] = MOVE_NONE;
2191 // RootMoveList::sort() sorts the root move list at the beginning of a new
2194 void RootMoveList::sort() {
2196 sort_multipv(count - 1); // Sort all items
2200 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2201 // list by their scores and depths. It is used to order the different PVs
2202 // correctly in MultiPV mode.
2204 void RootMoveList::sort_multipv(int n) {
2208 for (i = 1; i <= n; i++)
2210 RootMove rm = moves[i];
2211 for (j = i; j > 0 && moves[j - 1] < rm; j--)
2212 moves[j] = moves[j - 1];
2219 // init_node() is called at the beginning of all the search functions
2220 // (search(), search_pv(), qsearch(), and so on) and initializes the
2221 // search stack object corresponding to the current node. Once every
2222 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2223 // for user input and checks whether it is time to stop the search.
2225 void init_node(SearchStack ss[], int ply, int threadID) {
2227 assert(ply >= 0 && ply < PLY_MAX);
2228 assert(threadID >= 0 && threadID < ActiveThreads);
2230 Threads[threadID].nodes++;
2235 if (NodesSincePoll >= NodesBetweenPolls)
2242 ss[ply + 2].initKillers();
2244 if (Threads[threadID].printCurrentLine)
2245 print_current_line(ss, ply, threadID);
2249 // update_pv() is called whenever a search returns a value > alpha.
2250 // It updates the PV in the SearchStack object corresponding to the
2253 void update_pv(SearchStack ss[], int ply) {
2255 assert(ply >= 0 && ply < PLY_MAX);
2259 ss[ply].pv[ply] = ss[ply].currentMove;
2261 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2262 ss[ply].pv[p] = ss[ply + 1].pv[p];
2264 ss[ply].pv[p] = MOVE_NONE;
2268 // sp_update_pv() is a variant of update_pv for use at split points. The
2269 // difference between the two functions is that sp_update_pv also updates
2270 // the PV at the parent node.
2272 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2274 assert(ply >= 0 && ply < PLY_MAX);
2278 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2280 for (p = ply + 1; ss[ply + 1].pv[p] != MOVE_NONE; p++)
2281 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply + 1].pv[p];
2283 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2287 // connected_moves() tests whether two moves are 'connected' in the sense
2288 // that the first move somehow made the second move possible (for instance
2289 // if the moving piece is the same in both moves). The first move is assumed
2290 // to be the move that was made to reach the current position, while the
2291 // second move is assumed to be a move from the current position.
2293 bool connected_moves(const Position& pos, Move m1, Move m2) {
2295 Square f1, t1, f2, t2;
2298 assert(move_is_ok(m1));
2299 assert(move_is_ok(m2));
2301 if (m2 == MOVE_NONE)
2304 // Case 1: The moving piece is the same in both moves
2310 // Case 2: The destination square for m2 was vacated by m1
2316 // Case 3: Moving through the vacated square
2317 if ( piece_is_slider(pos.piece_on(f2))
2318 && bit_is_set(squares_between(f2, t2), f1))
2321 // Case 4: The destination square for m2 is defended by the moving piece in m1
2322 p = pos.piece_on(t1);
2323 if (bit_is_set(pos.attacks_from(p, t1), t2))
2326 // Case 5: Discovered check, checking piece is the piece moved in m1
2327 if ( piece_is_slider(p)
2328 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2329 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2331 // discovered_check_candidates() works also if the Position's side to
2332 // move is the opposite of the checking piece.
2333 Color them = opposite_color(pos.side_to_move());
2334 Bitboard dcCandidates = pos.discovered_check_candidates(them);
2336 if (bit_is_set(dcCandidates, f2))
2343 // value_is_mate() checks if the given value is a mate one
2344 // eventually compensated for the ply.
2346 bool value_is_mate(Value value) {
2348 assert(abs(value) <= VALUE_INFINITE);
2350 return value <= value_mated_in(PLY_MAX)
2351 || value >= value_mate_in(PLY_MAX);
2355 // move_is_killer() checks if the given move is among the
2356 // killer moves of that ply.
2358 bool move_is_killer(Move m, const SearchStack& ss) {
2360 const Move* k = ss.killers;
2361 for (int i = 0; i < KILLER_MAX; i++, k++)
2369 // extension() decides whether a move should be searched with normal depth,
2370 // or with extended depth. Certain classes of moves (checking moves, in
2371 // particular) are searched with bigger depth than ordinary moves and in
2372 // any case are marked as 'dangerous'. Note that also if a move is not
2373 // extended, as example because the corresponding UCI option is set to zero,
2374 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2376 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2377 bool moveIsCheck, bool singleEvasion, bool mateThreat, bool* dangerous) {
2379 assert(m != MOVE_NONE);
2381 Depth result = Depth(0);
2382 *dangerous = moveIsCheck | singleEvasion | mateThreat;
2387 result += CheckExtension[pvNode];
2390 result += SingleEvasionExtension[pvNode];
2393 result += MateThreatExtension[pvNode];
2396 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2398 Color c = pos.side_to_move();
2399 if (relative_rank(c, move_to(m)) == RANK_7)
2401 result += PawnPushTo7thExtension[pvNode];
2404 if (pos.pawn_is_passed(c, move_to(m)))
2406 result += PassedPawnExtension[pvNode];
2411 if ( captureOrPromotion
2412 && pos.type_of_piece_on(move_to(m)) != PAWN
2413 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2414 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2415 && !move_is_promotion(m)
2418 result += PawnEndgameExtension[pvNode];
2423 && captureOrPromotion
2424 && pos.type_of_piece_on(move_to(m)) != PAWN
2425 && pos.see_sign(m) >= 0)
2431 return Min(result, OnePly);
2435 // ok_to_do_nullmove() looks at the current position and decides whether
2436 // doing a 'null move' should be allowed. In order to avoid zugzwang
2437 // problems, null moves are not allowed when the side to move has very
2438 // little material left. Currently, the test is a bit too simple: Null
2439 // moves are avoided only when the side to move has only pawns left.
2440 // It's probably a good idea to avoid null moves in at least some more
2441 // complicated endgames, e.g. KQ vs KR. FIXME
2443 bool ok_to_do_nullmove(const Position& pos) {
2445 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2449 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2450 // non-tactical moves late in the move list close to the leaves are
2451 // candidates for pruning.
2453 bool ok_to_prune(const Position& pos, Move m, Move threat) {
2455 assert(move_is_ok(m));
2456 assert(threat == MOVE_NONE || move_is_ok(threat));
2457 assert(!pos.move_is_check(m));
2458 assert(!pos.move_is_capture_or_promotion(m));
2459 assert(!pos.move_is_passed_pawn_push(m));
2461 Square mfrom, mto, tfrom, tto;
2463 // Prune if there isn't any threat move
2464 if (threat == MOVE_NONE)
2467 mfrom = move_from(m);
2469 tfrom = move_from(threat);
2470 tto = move_to(threat);
2472 // Case 1: Don't prune moves which move the threatened piece
2476 // Case 2: If the threatened piece has value less than or equal to the
2477 // value of the threatening piece, don't prune move which defend it.
2478 if ( pos.move_is_capture(threat)
2479 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2480 || pos.type_of_piece_on(tfrom) == KING)
2481 && pos.move_attacks_square(m, tto))
2484 // Case 3: If the moving piece in the threatened move is a slider, don't
2485 // prune safe moves which block its ray.
2486 if ( piece_is_slider(pos.piece_on(tfrom))
2487 && bit_is_set(squares_between(tfrom, tto), mto)
2488 && pos.see_sign(m) >= 0)
2495 // ok_to_use_TT() returns true if a transposition table score
2496 // can be used at a given point in search.
2498 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2500 Value v = value_from_tt(tte->value(), ply);
2502 return ( tte->depth() >= depth
2503 || v >= Max(value_mate_in(PLY_MAX), beta)
2504 || v < Min(value_mated_in(PLY_MAX), beta))
2506 && ( (is_lower_bound(tte->type()) && v >= beta)
2507 || (is_upper_bound(tte->type()) && v < beta));
2511 // refine_eval() returns the transposition table score if
2512 // possible otherwise falls back on static position evaluation.
2514 Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
2519 Value v = value_from_tt(tte->value(), ply);
2521 if ( (is_lower_bound(tte->type()) && v >= defaultEval)
2522 || (is_upper_bound(tte->type()) && v < defaultEval))
2529 // update_history() registers a good move that produced a beta-cutoff
2530 // in history and marks as failures all the other moves of that ply.
2532 void update_history(const Position& pos, Move move, Depth depth,
2533 Move movesSearched[], int moveCount) {
2537 H.success(pos.piece_on(move_from(move)), move_to(move), depth);
2539 for (int i = 0; i < moveCount - 1; i++)
2541 m = movesSearched[i];
2545 if (!pos.move_is_capture_or_promotion(m))
2546 H.failure(pos.piece_on(move_from(m)), move_to(m), depth);
2551 // update_killers() add a good move that produced a beta-cutoff
2552 // among the killer moves of that ply.
2554 void update_killers(Move m, SearchStack& ss) {
2556 if (m == ss.killers[0])
2559 for (int i = KILLER_MAX - 1; i > 0; i--)
2560 ss.killers[i] = ss.killers[i - 1];
2566 // update_gains() updates the gains table of a non-capture move given
2567 // the static position evaluation before and after the move.
2569 void update_gains(const Position& pos, Move m, Value before, Value after) {
2572 && before != VALUE_NONE
2573 && after != VALUE_NONE
2574 && pos.captured_piece() == NO_PIECE_TYPE
2575 && !move_is_castle(m)
2576 && !move_is_promotion(m))
2577 H.set_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
2581 // current_search_time() returns the number of milliseconds which have passed
2582 // since the beginning of the current search.
2584 int current_search_time() {
2586 return get_system_time() - SearchStartTime;
2590 // nps() computes the current nodes/second count.
2594 int t = current_search_time();
2595 return (t > 0 ? int((nodes_searched() * 1000) / t) : 0);
2599 // poll() performs two different functions: It polls for user input, and it
2600 // looks at the time consumed so far and decides if it's time to abort the
2605 static int lastInfoTime;
2606 int t = current_search_time();
2611 // We are line oriented, don't read single chars
2612 std::string command;
2614 if (!std::getline(std::cin, command))
2617 if (command == "quit")
2620 PonderSearch = false;
2624 else if (command == "stop")
2627 PonderSearch = false;
2629 else if (command == "ponderhit")
2633 // Print search information
2637 else if (lastInfoTime > t)
2638 // HACK: Must be a new search where we searched less than
2639 // NodesBetweenPolls nodes during the first second of search.
2642 else if (t - lastInfoTime >= 1000)
2650 if (dbg_show_hit_rate)
2651 dbg_print_hit_rate();
2653 cout << "info nodes " << nodes_searched() << " nps " << nps()
2654 << " time " << t << " hashfull " << TT.full() << endl;
2656 lock_release(&IOLock);
2658 if (ShowCurrentLine)
2659 Threads[0].printCurrentLine = true;
2662 // Should we stop the search?
2666 bool stillAtFirstMove = RootMoveNumber == 1
2667 && !AspirationFailLow
2668 && t > MaxSearchTime + ExtraSearchTime;
2670 bool noMoreTime = t > AbsoluteMaxSearchTime
2671 || stillAtFirstMove;
2673 if ( (Iteration >= 3 && UseTimeManagement && noMoreTime)
2674 || (ExactMaxTime && t >= ExactMaxTime)
2675 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2680 // ponderhit() is called when the program is pondering (i.e. thinking while
2681 // it's the opponent's turn to move) in order to let the engine know that
2682 // it correctly predicted the opponent's move.
2686 int t = current_search_time();
2687 PonderSearch = false;
2689 bool stillAtFirstMove = RootMoveNumber == 1
2690 && !AspirationFailLow
2691 && t > MaxSearchTime + ExtraSearchTime;
2693 bool noMoreTime = t > AbsoluteMaxSearchTime
2694 || stillAtFirstMove;
2696 if (Iteration >= 3 && UseTimeManagement && (noMoreTime || StopOnPonderhit))
2701 // print_current_line() prints the current line of search for a given
2702 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2704 void print_current_line(SearchStack ss[], int ply, int threadID) {
2706 assert(ply >= 0 && ply < PLY_MAX);
2707 assert(threadID >= 0 && threadID < ActiveThreads);
2709 if (!Threads[threadID].idle)
2712 cout << "info currline " << (threadID + 1);
2713 for (int p = 0; p < ply; p++)
2714 cout << " " << ss[p].currentMove;
2717 lock_release(&IOLock);
2719 Threads[threadID].printCurrentLine = false;
2720 if (threadID + 1 < ActiveThreads)
2721 Threads[threadID + 1].printCurrentLine = true;
2725 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2727 void init_ss_array(SearchStack ss[]) {
2729 for (int i = 0; i < 3; i++)
2732 ss[i].initKillers();
2737 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2738 // while the program is pondering. The point is to work around a wrinkle in
2739 // the UCI protocol: When pondering, the engine is not allowed to give a
2740 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2741 // We simply wait here until one of these commands is sent, and return,
2742 // after which the bestmove and pondermove will be printed (in id_loop()).
2744 void wait_for_stop_or_ponderhit() {
2746 std::string command;
2750 if (!std::getline(std::cin, command))
2753 if (command == "quit")
2758 else if (command == "ponderhit" || command == "stop")
2764 // idle_loop() is where the threads are parked when they have no work to do.
2765 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2766 // object for which the current thread is the master.
2768 void idle_loop(int threadID, SplitPoint* waitSp) {
2770 assert(threadID >= 0 && threadID < THREAD_MAX);
2772 Threads[threadID].running = true;
2776 if (AllThreadsShouldExit && threadID != 0)
2779 // If we are not thinking, wait for a condition to be signaled
2780 // instead of wasting CPU time polling for work.
2781 while (threadID != 0 && (Idle || threadID >= ActiveThreads))
2784 #if !defined(_MSC_VER)
2785 pthread_mutex_lock(&WaitLock);
2786 if (Idle || threadID >= ActiveThreads)
2787 pthread_cond_wait(&WaitCond, &WaitLock);
2789 pthread_mutex_unlock(&WaitLock);
2791 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2795 // If this thread has been assigned work, launch a search
2796 if (Threads[threadID].workIsWaiting)
2798 assert(!Threads[threadID].idle);
2800 Threads[threadID].workIsWaiting = false;
2801 if (Threads[threadID].splitPoint->pvNode)
2802 sp_search_pv(Threads[threadID].splitPoint, threadID);
2804 sp_search(Threads[threadID].splitPoint, threadID);
2806 Threads[threadID].idle = true;
2809 // If this thread is the master of a split point and all threads have
2810 // finished their work at this split point, return from the idle loop.
2811 if (waitSp != NULL && waitSp->cpus == 0)
2815 Threads[threadID].running = false;
2819 // init_split_point_stack() is called during program initialization, and
2820 // initializes all split point objects.
2822 void init_split_point_stack() {
2824 for (int i = 0; i < THREAD_MAX; i++)
2825 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2827 SplitPointStack[i][j].parent = NULL;
2828 lock_init(&(SplitPointStack[i][j].lock), NULL);
2833 // destroy_split_point_stack() is called when the program exits, and
2834 // destroys all locks in the precomputed split point objects.
2836 void destroy_split_point_stack() {
2838 for (int i = 0; i < THREAD_MAX; i++)
2839 for (int j = 0; j < ACTIVE_SPLIT_POINTS_MAX; j++)
2840 lock_destroy(&(SplitPointStack[i][j].lock));
2844 // thread_should_stop() checks whether the thread with a given threadID has
2845 // been asked to stop, directly or indirectly. This can happen if a beta
2846 // cutoff has occurred in the thread's currently active split point, or in
2847 // some ancestor of the current split point.
2849 bool thread_should_stop(int threadID) {
2851 assert(threadID >= 0 && threadID < ActiveThreads);
2855 if (Threads[threadID].stop)
2857 if (ActiveThreads <= 2)
2859 for (sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2862 Threads[threadID].stop = true;
2869 // thread_is_available() checks whether the thread with threadID "slave" is
2870 // available to help the thread with threadID "master" at a split point. An
2871 // obvious requirement is that "slave" must be idle. With more than two
2872 // threads, this is not by itself sufficient: If "slave" is the master of
2873 // some active split point, it is only available as a slave to the other
2874 // threads which are busy searching the split point at the top of "slave"'s
2875 // split point stack (the "helpful master concept" in YBWC terminology).
2877 bool thread_is_available(int slave, int master) {
2879 assert(slave >= 0 && slave < ActiveThreads);
2880 assert(master >= 0 && master < ActiveThreads);
2881 assert(ActiveThreads > 1);
2883 if (!Threads[slave].idle || slave == master)
2886 // Make a local copy to be sure doesn't change under our feet
2887 int localActiveSplitPoints = Threads[slave].activeSplitPoints;
2889 if (localActiveSplitPoints == 0)
2890 // No active split points means that the thread is available as
2891 // a slave for any other thread.
2894 if (ActiveThreads == 2)
2897 // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2898 // that is known to be > 0, instead of Threads[slave].activeSplitPoints that
2899 // could have been set to 0 by another thread leading to an out of bound access.
2900 if (SplitPointStack[slave][localActiveSplitPoints - 1].slaves[master])
2907 // idle_thread_exists() tries to find an idle thread which is available as
2908 // a slave for the thread with threadID "master".
2910 bool idle_thread_exists(int master) {
2912 assert(master >= 0 && master < ActiveThreads);
2913 assert(ActiveThreads > 1);
2915 for (int i = 0; i < ActiveThreads; i++)
2916 if (thread_is_available(i, master))
2923 // split() does the actual work of distributing the work at a node between
2924 // several threads at PV nodes. If it does not succeed in splitting the
2925 // node (because no idle threads are available, or because we have no unused
2926 // split point objects), the function immediately returns false. If
2927 // splitting is possible, a SplitPoint object is initialized with all the
2928 // data that must be copied to the helper threads (the current position and
2929 // search stack, alpha, beta, the search depth, etc.), and we tell our
2930 // helper threads that they have been assigned work. This will cause them
2931 // to instantly leave their idle loops and call sp_search_pv(). When all
2932 // threads have returned from sp_search_pv (or, equivalently, when
2933 // splitPoint->cpus becomes 0), split() returns true.
2935 bool split(const Position& p, SearchStack* sstck, int ply,
2936 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2937 Depth depth, int* moves, MovePicker* mp, int master, bool pvNode) {
2940 assert(sstck != NULL);
2941 assert(ply >= 0 && ply < PLY_MAX);
2942 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2943 assert(!pvNode || *alpha < *beta);
2944 assert(*beta <= VALUE_INFINITE);
2945 assert(depth > Depth(0));
2946 assert(master >= 0 && master < ActiveThreads);
2947 assert(ActiveThreads > 1);
2949 SplitPoint* splitPoint;
2953 // If no other thread is available to help us, or if we have too many
2954 // active split points, don't split.
2955 if ( !idle_thread_exists(master)
2956 || Threads[master].activeSplitPoints >= ACTIVE_SPLIT_POINTS_MAX)
2958 lock_release(&MPLock);
2962 // Pick the next available split point object from the split point stack
2963 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2964 Threads[master].activeSplitPoints++;
2966 // Initialize the split point object
2967 splitPoint->parent = Threads[master].splitPoint;
2968 splitPoint->finished = false;
2969 splitPoint->ply = ply;
2970 splitPoint->depth = depth;
2971 splitPoint->alpha = pvNode ? *alpha : (*beta - 1);
2972 splitPoint->beta = *beta;
2973 splitPoint->pvNode = pvNode;
2974 splitPoint->bestValue = *bestValue;
2975 splitPoint->futilityValue = futilityValue;
2976 splitPoint->master = master;
2977 splitPoint->mp = mp;
2978 splitPoint->moves = *moves;
2979 splitPoint->cpus = 1;
2980 splitPoint->pos = &p;
2981 splitPoint->parentSstack = sstck;
2982 for (int i = 0; i < ActiveThreads; i++)
2983 splitPoint->slaves[i] = 0;
2985 Threads[master].idle = false;
2986 Threads[master].stop = false;
2987 Threads[master].splitPoint = splitPoint;
2989 // Allocate available threads setting idle flag to false
2990 for (int i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint; i++)
2991 if (thread_is_available(i, master))
2993 Threads[i].idle = false;
2994 Threads[i].stop = false;
2995 Threads[i].splitPoint = splitPoint;
2996 splitPoint->slaves[i] = 1;
3000 assert(splitPoint->cpus > 1);
3002 // We can release the lock because master and slave threads are already booked
3003 lock_release(&MPLock);
3005 // Tell the threads that they have work to do. This will make them leave
3006 // their idle loop. But before copy search stack tail for each thread.
3007 for (int i = 0; i < ActiveThreads; i++)
3008 if (i == master || splitPoint->slaves[i])
3010 memcpy(splitPoint->sstack[i] + ply - 1, sstck + ply - 1, 4 * sizeof(SearchStack));
3011 Threads[i].workIsWaiting = true; // This makes the slave to exit from idle_loop()
3014 // Everything is set up. The master thread enters the idle loop, from
3015 // which it will instantly launch a search, because its workIsWaiting
3016 // slot is 'true'. We send the split point as a second parameter to the
3017 // idle loop, which means that the main thread will return from the idle
3018 // loop when all threads have finished their work at this split point
3019 // (i.e. when splitPoint->cpus == 0).
3020 idle_loop(master, splitPoint);
3022 // We have returned from the idle loop, which means that all threads are
3023 // finished. Update alpha, beta and bestValue, and return.
3027 *alpha = splitPoint->alpha;
3029 *beta = splitPoint->beta;
3030 *bestValue = splitPoint->bestValue;
3031 Threads[master].stop = false;
3032 Threads[master].idle = false;
3033 Threads[master].activeSplitPoints--;
3034 Threads[master].splitPoint = splitPoint->parent;
3036 lock_release(&MPLock);
3041 // wake_sleeping_threads() wakes up all sleeping threads when it is time
3042 // to start a new search from the root.
3044 void wake_sleeping_threads() {
3046 if (ActiveThreads > 1)
3048 for (int i = 1; i < ActiveThreads; i++)
3050 Threads[i].idle = true;
3051 Threads[i].workIsWaiting = false;
3054 #if !defined(_MSC_VER)
3055 pthread_mutex_lock(&WaitLock);
3056 pthread_cond_broadcast(&WaitCond);
3057 pthread_mutex_unlock(&WaitLock);
3059 for (int i = 1; i < THREAD_MAX; i++)
3060 SetEvent(SitIdleEvent[i]);
3066 // init_thread() is the function which is called when a new thread is
3067 // launched. It simply calls the idle_loop() function with the supplied
3068 // threadID. There are two versions of this function; one for POSIX
3069 // threads and one for Windows threads.
3071 #if !defined(_MSC_VER)
3073 void* init_thread(void *threadID) {
3075 idle_loop(*(int*)threadID, NULL);
3081 DWORD WINAPI init_thread(LPVOID threadID) {
3083 idle_loop(*(int*)threadID, NULL);