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/>.
42 #include "ucioption.h"
46 //// Local definitions
53 // IterationInfoType stores search results for each iteration
55 // Because we use relatively small (dynamic) aspiration window,
56 // there happens many fail highs and fail lows in root. And
57 // because we don't do researches in those cases, "value" stored
58 // here is not necessarily exact. Instead in case of fail high/low
59 // we guess what the right value might be and store our guess
60 // as a "speculated value" and then move on. Speculated values are
61 // used just to calculate aspiration window width, so also if are
62 // not exact is not big a problem.
64 struct IterationInfoType {
66 IterationInfoType(Value v = Value(0), Value sv = Value(0))
67 : value(v), speculatedValue(sv) {}
69 Value value, speculatedValue;
73 // The BetaCounterType class is used to order moves at ply one.
74 // Apart for the first one that has its score, following moves
75 // normally have score -VALUE_INFINITE, so are ordered according
76 // to the number of beta cutoffs occurred under their subtree during
77 // the last iteration. The counters are per thread variables to avoid
78 // concurrent accessing under SMP case.
80 struct BetaCounterType {
84 void add(Color us, Depth d, int threadID);
85 void read(Color us, int64_t& our, int64_t& their);
89 // The RootMove class is used for moves at the root at the tree. For each
90 // root move, we store a score, a node count, and a PV (really a refutation
91 // in the case of moves which fail low).
96 bool operator<(const RootMove&); // used to sort
100 int64_t nodes, cumulativeNodes;
101 Move pv[PLY_MAX_PLUS_2];
102 int64_t ourBeta, theirBeta;
106 // The RootMoveList class is essentially an array of RootMove objects, with
107 // a handful of methods for accessing the data in the individual moves.
112 RootMoveList(Position& pos, Move searchMoves[]);
113 inline Move get_move(int moveNum) const;
114 inline Value get_move_score(int moveNum) const;
115 inline void set_move_score(int moveNum, Value score);
116 inline void set_move_nodes(int moveNum, int64_t nodes);
117 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
118 void set_move_pv(int moveNum, const Move pv[]);
119 inline Move get_move_pv(int moveNum, int i) const;
120 inline int64_t get_move_cumulative_nodes(int moveNum) const;
121 inline int move_count() const;
122 Move scan_for_easy_move() const;
124 void sort_multipv(int n);
127 static const int MaxRootMoves = 500;
128 RootMove moves[MaxRootMoves];
135 // Search depth at iteration 1
136 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
138 // Depth limit for selective search
139 const Depth SelectiveDepth = 7 * OnePly;
141 // Use internal iterative deepening?
142 const bool UseIIDAtPVNodes = true;
143 const bool UseIIDAtNonPVNodes = false;
145 // Internal iterative deepening margin. At Non-PV moves, when
146 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
147 // search when the static evaluation is at most IIDMargin below beta.
148 const Value IIDMargin = Value(0x100);
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
154 // Problem margin. If the score of the first move at iteration N+1 has
155 // dropped by more than this since iteration N, the boolean variable
156 // "Problem" is set to true, which will make the program spend some extra
157 // time looking for a better move.
158 const Value ProblemMargin = Value(0x28);
160 // No problem margin. If the boolean "Problem" is true, and a new move
161 // is found at the root which is less than NoProblemMargin worse than the
162 // best move from the previous iteration, Problem is set back to false.
163 const Value NoProblemMargin = Value(0x14);
165 // Null move margin. A null move search will not be done if the approximate
166 // evaluation of the position is more than NullMoveMargin below beta.
167 const Value NullMoveMargin = Value(0x300);
169 // Pruning criterions. See the code and comments in ok_to_prune() to
170 // understand their precise meaning.
171 const bool PruneEscapeMoves = false;
172 const bool PruneDefendingMoves = false;
173 const bool PruneBlockingMoves = false;
175 // Margins for futility pruning in the quiescence search, and at frontier
176 // and near frontier nodes.
177 const Value FutilityMarginQS = Value(0x80);
179 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
180 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
181 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
182 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
184 const Depth RazorDepth = 4*OnePly;
186 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
187 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
193 /// Variables initialized by UCI options
195 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
196 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
198 // Depth limit for use of dynamic threat detection
199 Depth ThreatDepth; // heavy SMP read access
201 // Last seconds noise filtering (LSN)
202 const bool UseLSNFiltering = true;
203 const int LSNTime = 4000; // In milliseconds
204 const Value LSNValue = value_from_centipawns(200);
205 bool loseOnTime = false;
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 // There is heavy SMP read access on these arrays
209 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
210 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
212 // Iteration counters
214 BetaCounterType BetaCounter; // has per-thread internal data
216 // Scores and number of times the best move changed for each iteration
217 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
218 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
223 // Time managment variables
225 int MaxNodes, MaxDepth;
226 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
230 bool StopOnPonderhit;
231 bool AbortSearch; // heavy SMP read access
237 // Show current line?
238 bool ShowCurrentLine;
242 std::ofstream LogFile;
244 // MP related variables
245 int ActiveThreads = 1;
246 Depth MinimumSplitDepth;
247 int MaxThreadsPerSplitPoint;
248 Thread Threads[THREAD_MAX];
251 bool AllThreadsShouldExit = false;
252 const int MaxActiveSplitPoints = 8;
253 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
256 #if !defined(_MSC_VER)
257 pthread_cond_t WaitCond;
258 pthread_mutex_t WaitLock;
260 HANDLE SitIdleEvent[THREAD_MAX];
263 // Node counters, used only by thread[0] but try to keep in different
264 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
266 int NodesBetweenPolls = 30000;
274 Value id_loop(const Position& pos, Move searchMoves[]);
275 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
276 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
277 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
278 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
279 void sp_search(SplitPoint* sp, int threadID);
280 void sp_search_pv(SplitPoint* sp, int threadID);
281 void init_node(SearchStack ss[], int ply, int threadID);
282 void update_pv(SearchStack ss[], int ply);
283 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
284 bool connected_moves(const Position& pos, Move m1, Move m2);
285 bool value_is_mate(Value value);
286 bool move_is_killer(Move m, const SearchStack& ss);
287 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
288 bool ok_to_do_nullmove(const Position& pos);
289 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
290 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
291 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
292 void update_killers(Move m, SearchStack& ss);
294 bool fail_high_ply_1();
295 int current_search_time();
299 void print_current_line(SearchStack ss[], int ply, int threadID);
300 void wait_for_stop_or_ponderhit();
301 void init_ss_array(SearchStack ss[]);
303 void idle_loop(int threadID, SplitPoint* waitSp);
304 void init_split_point_stack();
305 void destroy_split_point_stack();
306 bool thread_should_stop(int threadID);
307 bool thread_is_available(int slave, int master);
308 bool idle_thread_exists(int master);
309 bool split(const Position& pos, SearchStack* ss, int ply,
310 Value *alpha, Value *beta, Value *bestValue,
311 const Value futilityValue, const Value approximateValue,
312 Depth depth, int *moves,
313 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
314 void wake_sleeping_threads();
316 #if !defined(_MSC_VER)
317 void *init_thread(void *threadID);
319 DWORD WINAPI init_thread(LPVOID threadID);
330 /// perft() is our utility to verify move generation is bug free. All the
331 /// legal moves up to given depth are generated and counted and the sum returned.
333 int perft(Position& pos, Depth depth)
336 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
339 // If we are at the last ply we don't need to do and undo
340 // the moves, just to count them.
341 if (depth <= OnePly) // Replace with '<' to test also qsearch
343 while ((move = mp.get_next_move()) != MOVE_NONE) sum++;
347 // Loop through all legal moves
349 while ((move = mp.get_next_move()) != MOVE_NONE)
352 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
353 sum += perft(pos, depth - OnePly);
360 /// think() is the external interface to Stockfish's search, and is called when
361 /// the program receives the UCI 'go' command. It initializes various
362 /// search-related global variables, and calls root_search(). It returns false
363 /// when a quit command is received during the search.
365 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
366 int time[], int increment[], int movesToGo, int maxDepth,
367 int maxNodes, int maxTime, Move searchMoves[]) {
369 // Look for a book move
370 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
373 if (get_option_value_string("Book File") != OpeningBook.file_name())
374 OpeningBook.open("book.bin");
376 bookMove = OpeningBook.get_move(pos);
377 if (bookMove != MOVE_NONE)
379 std::cout << "bestmove " << bookMove << std::endl;
384 // Initialize global search variables
386 SearchStartTime = get_system_time();
387 for (int i = 0; i < THREAD_MAX; i++)
389 Threads[i].nodes = 0ULL;
390 Threads[i].failHighPly1 = false;
393 InfiniteSearch = infinite;
394 PonderSearch = ponder;
395 StopOnPonderhit = false;
401 ExactMaxTime = maxTime;
403 // Read UCI option values
404 TT.set_size(get_option_value_int("Hash"));
405 if (button_was_pressed("Clear Hash"))
408 loseOnTime = false; // reset at the beginning of a new game
411 bool PonderingEnabled = get_option_value_bool("Ponder");
412 MultiPV = get_option_value_int("MultiPV");
414 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
415 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
417 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
418 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
420 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
421 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
423 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
424 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
426 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
427 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
429 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
430 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
432 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
433 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
434 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
436 Chess960 = get_option_value_bool("UCI_Chess960");
437 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
438 UseLogFile = get_option_value_bool("Use Search Log");
440 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
442 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
443 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
445 read_weights(pos.side_to_move());
447 // Set the number of active threads
448 int newActiveThreads = get_option_value_int("Threads");
449 if (newActiveThreads != ActiveThreads)
451 ActiveThreads = newActiveThreads;
452 init_eval(ActiveThreads);
455 // Wake up sleeping threads
456 wake_sleeping_threads();
458 for (int i = 1; i < ActiveThreads; i++)
459 assert(thread_is_available(i, 0));
462 int myTime = time[side_to_move];
463 int myIncrement = increment[side_to_move];
465 if (!movesToGo) // Sudden death time control
469 MaxSearchTime = myTime / 30 + myIncrement;
470 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
471 } else { // Blitz game without increment
472 MaxSearchTime = myTime / 30;
473 AbsoluteMaxSearchTime = myTime / 8;
476 else // (x moves) / (y minutes)
480 MaxSearchTime = myTime / 2;
481 AbsoluteMaxSearchTime =
482 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
484 MaxSearchTime = myTime / Min(movesToGo, 20);
485 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
489 if (PonderingEnabled)
491 MaxSearchTime += MaxSearchTime / 4;
492 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
495 // Fixed depth or fixed number of nodes?
498 InfiniteSearch = true; // HACK
503 NodesBetweenPolls = Min(MaxNodes, 30000);
504 InfiniteSearch = true; // HACK
506 else if (myTime && myTime < 1000)
507 NodesBetweenPolls = 1000;
508 else if (myTime && myTime < 5000)
509 NodesBetweenPolls = 5000;
511 NodesBetweenPolls = 30000;
513 // Write information to search log file
515 LogFile << "Searching: " << pos.to_fen() << std::endl
516 << "infinite: " << infinite
517 << " ponder: " << ponder
518 << " time: " << myTime
519 << " increment: " << myIncrement
520 << " moves to go: " << movesToGo << std::endl;
523 // We're ready to start thinking. Call the iterative deepening loop function
525 // FIXME we really need to cleanup all this LSN ugliness
528 Value v = id_loop(pos, searchMoves);
529 loseOnTime = ( UseLSNFiltering
536 loseOnTime = false; // reset for next match
537 while (SearchStartTime + myTime + 1000 > get_system_time())
539 id_loop(pos, searchMoves); // to fail gracefully
550 /// init_threads() is called during startup. It launches all helper threads,
551 /// and initializes the split point stack and the global locks and condition
554 void init_threads() {
558 #if !defined(_MSC_VER)
559 pthread_t pthread[1];
562 for (i = 0; i < THREAD_MAX; i++)
563 Threads[i].activeSplitPoints = 0;
565 // Initialize global locks
566 lock_init(&MPLock, NULL);
567 lock_init(&IOLock, NULL);
569 init_split_point_stack();
571 #if !defined(_MSC_VER)
572 pthread_mutex_init(&WaitLock, NULL);
573 pthread_cond_init(&WaitCond, NULL);
575 for (i = 0; i < THREAD_MAX; i++)
576 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
579 // All threads except the main thread should be initialized to idle state
580 for (i = 1; i < THREAD_MAX; i++)
582 Threads[i].stop = false;
583 Threads[i].workIsWaiting = false;
584 Threads[i].idle = true;
585 Threads[i].running = false;
588 // Launch the helper threads
589 for(i = 1; i < THREAD_MAX; i++)
591 #if !defined(_MSC_VER)
592 pthread_create(pthread, NULL, init_thread, (void*)(&i));
595 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
598 // Wait until the thread has finished launching
599 while (!Threads[i].running);
604 /// stop_threads() is called when the program exits. It makes all the
605 /// helper threads exit cleanly.
607 void stop_threads() {
609 ActiveThreads = THREAD_MAX; // HACK
610 Idle = false; // HACK
611 wake_sleeping_threads();
612 AllThreadsShouldExit = true;
613 for (int i = 1; i < THREAD_MAX; i++)
615 Threads[i].stop = true;
616 while(Threads[i].running);
618 destroy_split_point_stack();
622 /// nodes_searched() returns the total number of nodes searched so far in
623 /// the current search.
625 int64_t nodes_searched() {
627 int64_t result = 0ULL;
628 for (int i = 0; i < ActiveThreads; i++)
629 result += Threads[i].nodes;
634 // SearchStack::init() initializes a search stack. Used at the beginning of a
635 // new search from the root.
636 void SearchStack::init(int ply) {
638 pv[ply] = pv[ply + 1] = MOVE_NONE;
639 currentMove = threatMove = MOVE_NONE;
640 reduction = Depth(0);
643 void SearchStack::initKillers() {
645 mateKiller = MOVE_NONE;
646 for (int i = 0; i < KILLER_MAX; i++)
647 killers[i] = MOVE_NONE;
652 // id_loop() is the main iterative deepening loop. It calls root_search
653 // repeatedly with increasing depth until the allocated thinking time has
654 // been consumed, the user stops the search, or the maximum search depth is
657 Value id_loop(const Position& pos, Move searchMoves[]) {
660 SearchStack ss[PLY_MAX_PLUS_2];
662 // searchMoves are verified, copied, scored and sorted
663 RootMoveList rml(p, searchMoves);
665 // Print RootMoveList c'tor startup scoring to the standard output,
666 // so that we print information also for iteration 1.
667 std::cout << "info depth " << 1 << "\ninfo depth " << 1
668 << " score " << value_to_string(rml.get_move_score(0))
669 << " time " << current_search_time()
670 << " nodes " << nodes_searched()
672 << " pv " << rml.get_move(0) << "\n";
678 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
681 Move EasyMove = rml.scan_for_easy_move();
683 // Iterative deepening loop
684 while (Iteration < PLY_MAX)
686 // Initialize iteration
689 BestMoveChangesByIteration[Iteration] = 0;
693 std::cout << "info depth " << Iteration << std::endl;
695 // Calculate dynamic search window based on previous iterations
698 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
700 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
701 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
703 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
705 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
706 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
710 alpha = - VALUE_INFINITE;
711 beta = VALUE_INFINITE;
714 // Search to the current depth
715 Value value = root_search(p, ss, rml, alpha, beta);
717 // Write PV to transposition table, in case the relevant entries have
718 // been overwritten during the search.
719 TT.insert_pv(p, ss[0].pv);
722 break; // Value cannot be trusted. Break out immediately!
724 //Save info about search result
725 Value speculatedValue;
728 Value delta = value - IterationInfo[Iteration - 1].value;
735 speculatedValue = value + delta;
736 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
738 else if (value <= alpha)
740 assert(value == alpha);
744 speculatedValue = value + delta;
745 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
747 speculatedValue = value;
749 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
750 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
752 // Erase the easy move if it differs from the new best move
753 if (ss[0].pv[0] != EasyMove)
754 EasyMove = MOVE_NONE;
761 bool stopSearch = false;
763 // Stop search early if there is only a single legal move
764 if (Iteration >= 6 && rml.move_count() == 1)
767 // Stop search early when the last two iterations returned a mate score
769 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
770 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
773 // Stop search early if one move seems to be much better than the rest
774 int64_t nodes = nodes_searched();
778 && EasyMove == ss[0].pv[0]
779 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
780 && current_search_time() > MaxSearchTime / 16)
781 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
782 && current_search_time() > MaxSearchTime / 32)))
785 // Add some extra time if the best move has changed during the last two iterations
786 if (Iteration > 5 && Iteration <= 50)
787 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
788 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
790 // Stop search if most of MaxSearchTime is consumed at the end of the
791 // iteration. We probably don't have enough time to search the first
792 // move at the next iteration anyway.
793 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
798 //FIXME: Implement fail-low emergency measures
802 StopOnPonderhit = true;
806 if (MaxDepth && Iteration >= MaxDepth)
812 // If we are pondering, we shouldn't print the best move before we
815 wait_for_stop_or_ponderhit();
817 // Print final search statistics
818 std::cout << "info nodes " << nodes_searched()
820 << " time " << current_search_time()
821 << " hashfull " << TT.full() << std::endl;
823 // Print the best move and the ponder move to the standard output
824 if (ss[0].pv[0] == MOVE_NONE)
826 ss[0].pv[0] = rml.get_move(0);
827 ss[0].pv[1] = MOVE_NONE;
829 std::cout << "bestmove " << ss[0].pv[0];
830 if (ss[0].pv[1] != MOVE_NONE)
831 std::cout << " ponder " << ss[0].pv[1];
833 std::cout << std::endl;
838 dbg_print_mean(LogFile);
840 if (dbg_show_hit_rate)
841 dbg_print_hit_rate(LogFile);
844 LogFile << "Nodes: " << nodes_searched() << std::endl
845 << "Nodes/second: " << nps() << std::endl
846 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
848 p.do_move(ss[0].pv[0], st);
849 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
850 << std::endl << std::endl;
852 return rml.get_move_score(0);
856 // root_search() is the function which searches the root node. It is
857 // similar to search_pv except that it uses a different move ordering
858 // scheme (perhaps we should try to use this at internal PV nodes, too?)
859 // and prints some information to the standard output.
861 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
863 Value oldAlpha = alpha;
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);
883 RootMoveNumber = i + 1;
886 // Remember the node count before the move is searched. The node counts
887 // are used to sort the root moves at the next iteration.
888 nodes = nodes_searched();
890 // Reset beta cut-off counters
893 // Pick the next root move, and print the move and the move number to
894 // the standard output.
895 move = ss[0].currentMove = rml.get_move(i);
896 if (current_search_time() >= 1000)
897 std::cout << "info currmove " << move
898 << " currmovenumber " << i + 1 << std::endl;
900 // Decide search depth for this move
901 bool moveIsCheck = pos.move_is_check(move);
902 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
904 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
905 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
907 // Make the move, and search it
908 pos.do_move(move, st, ci, moveIsCheck);
912 // Aspiration window is disabled in multi-pv case
914 alpha = -VALUE_INFINITE;
916 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
917 // If the value has dropped a lot compared to the last iteration,
918 // set the boolean variable Problem to true. This variable is used
919 // for time managment: When Problem is true, we try to complete the
920 // current iteration before playing a move.
921 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
923 if (Problem && StopOnPonderhit)
924 StopOnPonderhit = false;
928 if ( newDepth >= 3*OnePly
929 && i >= MultiPV + LMRPVMoves
931 && !captureOrPromotion
932 && !move_is_castle(move))
934 ss[0].reduction = OnePly;
935 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
937 value = alpha + 1; // Just to trigger next condition
941 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
944 // Fail high! Set the boolean variable FailHigh to true, and
945 // re-search the move with a big window. The variable FailHigh is
946 // used for time managment: We try to avoid aborting the search
947 // prematurely during a fail high research.
949 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
956 // Finished searching the move. If AbortSearch is true, the search
957 // was aborted because the user interrupted the search or because we
958 // ran out of time. In this case, the return value of the search cannot
959 // be trusted, and we break out of the loop without updating the best
964 // Remember the node count for this move. The node counts are used to
965 // sort the root moves at the next iteration.
966 rml.set_move_nodes(i, nodes_searched() - nodes);
968 // Remember the beta-cutoff statistics
970 BetaCounter.read(pos.side_to_move(), our, their);
971 rml.set_beta_counters(i, our, their);
973 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
975 if (value <= alpha && i >= MultiPV)
976 rml.set_move_score(i, -VALUE_INFINITE);
979 // PV move or new best move!
982 rml.set_move_score(i, value);
984 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
985 rml.set_move_pv(i, ss[0].pv);
989 // We record how often the best move has been changed in each
990 // iteration. This information is used for time managment: When
991 // the best move changes frequently, we allocate some more time.
993 BestMoveChangesByIteration[Iteration]++;
995 // Print search information to the standard output
996 std::cout << "info depth " << Iteration
997 << " score " << value_to_string(value)
999 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
1000 << " time " << current_search_time()
1001 << " nodes " << nodes_searched()
1005 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1006 std::cout << ss[0].pv[j] << " ";
1008 std::cout << std::endl;
1011 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1012 ((value >= beta)? VALUE_TYPE_LOWER
1013 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1020 // Reset the global variable Problem to false if the value isn't too
1021 // far below the final value from the last iteration.
1022 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1027 rml.sort_multipv(i);
1028 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1031 std::cout << "info multipv " << j + 1
1032 << " score " << value_to_string(rml.get_move_score(j))
1033 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1034 << " time " << current_search_time()
1035 << " nodes " << nodes_searched()
1039 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1040 std::cout << rml.get_move_pv(j, k) << " ";
1042 std::cout << std::endl;
1044 alpha = rml.get_move_score(Min(i, MultiPV-1));
1046 } // New best move case
1048 assert(alpha >= oldAlpha);
1050 FailLow = (alpha == oldAlpha);
1056 // search_pv() is the main search function for PV nodes.
1058 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1059 Depth depth, int ply, int threadID) {
1061 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1062 assert(beta > alpha && beta <= VALUE_INFINITE);
1063 assert(ply >= 0 && ply < PLY_MAX);
1064 assert(threadID >= 0 && threadID < ActiveThreads);
1066 Move movesSearched[256];
1071 Depth ext, newDepth;
1072 Value oldAlpha, value;
1073 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1075 Value bestValue = -VALUE_INFINITE;
1078 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1080 // Initialize, and make an early exit in case of an aborted search,
1081 // an instant draw, maximum ply reached, etc.
1082 init_node(ss, ply, threadID);
1084 // After init_node() that calls poll()
1085 if (AbortSearch || thread_should_stop(threadID))
1091 if (ply >= PLY_MAX - 1)
1092 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1094 // Mate distance pruning
1096 alpha = Max(value_mated_in(ply), alpha);
1097 beta = Min(value_mate_in(ply+1), beta);
1101 // Transposition table lookup. At PV nodes, we don't use the TT for
1102 // pruning, but only for move ordering.
1103 tte = TT.retrieve(pos.get_key());
1104 ttMove = (tte ? tte->move() : MOVE_NONE);
1106 // Go with internal iterative deepening if we don't have a TT move
1107 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1109 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1110 ttMove = ss[ply].pv[ply];
1113 // Initialize a MovePicker object for the current position, and prepare
1114 // to search all moves
1115 isCheck = pos.is_check();
1116 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1118 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1120 // Loop through all legal moves until no moves remain or a beta cutoff
1122 while ( alpha < beta
1123 && (move = mp.get_next_move()) != MOVE_NONE
1124 && !thread_should_stop(threadID))
1126 assert(move_is_ok(move));
1128 singleReply = (isCheck && mp.number_of_evasions() == 1);
1129 moveIsCheck = pos.move_is_check(move, ci);
1130 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1132 movesSearched[moveCount++] = ss[ply].currentMove = move;
1134 // Decide the new search depth
1135 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1136 newDepth = depth - OnePly + ext;
1138 // Make and search the move
1139 pos.do_move(move, st, ci, moveIsCheck);
1141 if (moveCount == 1) // The first move in list is the PV
1142 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1145 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1146 // if the move fails high will be re-searched at full depth.
1147 if ( depth >= 3*OnePly
1148 && moveCount >= LMRPVMoves
1150 && !captureOrPromotion
1151 && !move_is_castle(move)
1152 && !move_is_killer(move, ss[ply]))
1154 ss[ply].reduction = OnePly;
1155 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1158 value = alpha + 1; // Just to trigger next condition
1160 if (value > alpha) // Go with full depth non-pv search
1162 ss[ply].reduction = Depth(0);
1163 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1164 if (value > alpha && value < beta)
1166 // When the search fails high at ply 1 while searching the first
1167 // move at the root, set the flag failHighPly1. This is used for
1168 // time managment: We don't want to stop the search early in
1169 // such cases, because resolving the fail high at ply 1 could
1170 // result in a big drop in score at the root.
1171 if (ply == 1 && RootMoveNumber == 1)
1172 Threads[threadID].failHighPly1 = true;
1174 // A fail high occurred. Re-search at full window (pv search)
1175 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1176 Threads[threadID].failHighPly1 = false;
1180 pos.undo_move(move);
1182 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1185 if (value > bestValue)
1192 if (value == value_mate_in(ply + 1))
1193 ss[ply].mateKiller = move;
1195 // If we are at ply 1, and we are searching the first root move at
1196 // ply 0, set the 'Problem' variable if the score has dropped a lot
1197 // (from the computer's point of view) since the previous iteration.
1200 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1205 if ( ActiveThreads > 1
1207 && depth >= MinimumSplitDepth
1209 && idle_thread_exists(threadID)
1211 && !thread_should_stop(threadID)
1212 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE, depth,
1213 &moveCount, &mp, ci.dcCandidates, threadID, true))
1217 // All legal moves have been searched. A special case: If there were
1218 // no legal moves, it must be mate or stalemate.
1220 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1222 // If the search is not aborted, update the transposition table,
1223 // history counters, and killer moves.
1224 if (AbortSearch || thread_should_stop(threadID))
1227 if (bestValue <= oldAlpha)
1228 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1230 else if (bestValue >= beta)
1232 BetaCounter.add(pos.side_to_move(), depth, threadID);
1233 move = ss[ply].pv[ply];
1234 if (!pos.move_is_capture_or_promotion(move))
1236 update_history(pos, move, depth, movesSearched, moveCount);
1237 update_killers(move, ss[ply]);
1239 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1242 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1248 // search() is the search function for zero-width nodes.
1250 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1251 int ply, bool allowNullmove, int threadID) {
1253 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1254 assert(ply >= 0 && ply < PLY_MAX);
1255 assert(threadID >= 0 && threadID < ActiveThreads);
1257 Move movesSearched[256];
1262 Depth ext, newDepth;
1263 Value approximateEval, nullValue, value, futilityValue;
1264 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1265 bool mateThreat = false;
1267 Value bestValue = -VALUE_INFINITE;
1270 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1272 // Initialize, and make an early exit in case of an aborted search,
1273 // an instant draw, maximum ply reached, etc.
1274 init_node(ss, ply, threadID);
1276 // After init_node() that calls poll()
1277 if (AbortSearch || thread_should_stop(threadID))
1283 if (ply >= PLY_MAX - 1)
1284 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1286 // Mate distance pruning
1287 if (value_mated_in(ply) >= beta)
1290 if (value_mate_in(ply + 1) < beta)
1293 // Transposition table lookup
1294 tte = TT.retrieve(pos.get_key());
1295 ttMove = (tte ? tte->move() : MOVE_NONE);
1297 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1299 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1300 return value_from_tt(tte->value(), ply);
1303 approximateEval = quick_evaluate(pos);
1304 isCheck = pos.is_check();
1310 && !value_is_mate(beta)
1311 && ok_to_do_nullmove(pos)
1312 && approximateEval >= beta - NullMoveMargin)
1314 ss[ply].currentMove = MOVE_NULL;
1316 pos.do_null_move(st);
1317 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1319 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1321 pos.undo_null_move();
1323 if (nullValue >= beta)
1325 if (depth < 6 * OnePly)
1328 // Do zugzwang verification search
1329 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1333 // The null move failed low, which means that we may be faced with
1334 // some kind of threat. If the previous move was reduced, check if
1335 // the move that refuted the null move was somehow connected to the
1336 // move which was reduced. If a connection is found, return a fail
1337 // low score (which will cause the reduced move to fail high in the
1338 // parent node, which will trigger a re-search with full depth).
1339 if (nullValue == value_mated_in(ply + 2))
1342 ss[ply].threatMove = ss[ply + 1].currentMove;
1343 if ( depth < ThreatDepth
1344 && ss[ply - 1].reduction
1345 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1349 // Null move search not allowed, try razoring
1350 else if ( !value_is_mate(beta)
1351 && depth < RazorDepth
1352 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1353 && ss[ply - 1].currentMove != MOVE_NULL
1354 && ttMove == MOVE_NONE
1355 && !pos.has_pawn_on_7th(pos.side_to_move()))
1357 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1358 if (v < beta - RazorMargins[int(depth) - 2])
1362 // Go with internal iterative deepening if we don't have a TT move
1363 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1364 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1366 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1367 ttMove = ss[ply].pv[ply];
1370 // Initialize a MovePicker object for the current position, and prepare
1371 // to search all moves.
1372 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1374 futilityValue = VALUE_NONE;
1375 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1377 // Avoid calling evaluate() if we already have the score in TT
1378 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1379 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1381 // Loop through all legal moves until no moves remain or a beta cutoff
1383 while ( bestValue < beta
1384 && (move = mp.get_next_move()) != MOVE_NONE
1385 && !thread_should_stop(threadID))
1387 assert(move_is_ok(move));
1389 singleReply = (isCheck && mp.number_of_evasions() == 1);
1390 moveIsCheck = pos.move_is_check(move, ci);
1391 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1393 movesSearched[moveCount++] = ss[ply].currentMove = move;
1395 // Decide the new search depth
1396 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1397 newDepth = depth - OnePly + ext;
1400 if ( useFutilityPruning
1402 && !captureOrPromotion
1405 // History pruning. See ok_to_prune() definition
1406 if ( moveCount >= 2 + int(depth)
1407 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1408 && bestValue > value_mated_in(PLY_MAX))
1411 // Value based pruning
1412 if (approximateEval < beta)
1414 if (futilityValue == VALUE_NONE)
1415 futilityValue = evaluate(pos, ei, threadID)
1416 + FutilityMargins[int(depth) - 2];
1418 if (futilityValue < beta)
1420 if (futilityValue > bestValue)
1421 bestValue = futilityValue;
1427 // Make and search the move
1428 pos.do_move(move, st, ci, moveIsCheck);
1430 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1431 // if the move fails high will be re-searched at full depth.
1432 if ( depth >= 3*OnePly
1433 && moveCount >= LMRNonPVMoves
1435 && !captureOrPromotion
1436 && !move_is_castle(move)
1437 && !move_is_killer(move, ss[ply]))
1439 ss[ply].reduction = OnePly;
1440 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1443 value = beta; // Just to trigger next condition
1445 if (value >= beta) // Go with full depth non-pv search
1447 ss[ply].reduction = Depth(0);
1448 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1450 pos.undo_move(move);
1452 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1455 if (value > bestValue)
1461 if (value == value_mate_in(ply + 1))
1462 ss[ply].mateKiller = move;
1466 if ( ActiveThreads > 1
1468 && depth >= MinimumSplitDepth
1470 && idle_thread_exists(threadID)
1472 && !thread_should_stop(threadID)
1473 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval, depth, &moveCount,
1474 &mp, ci.dcCandidates, threadID, false))
1478 // All legal moves have been searched. A special case: If there were
1479 // no legal moves, it must be mate or stalemate.
1481 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1483 // If the search is not aborted, update the transposition table,
1484 // history counters, and killer moves.
1485 if (AbortSearch || thread_should_stop(threadID))
1488 if (bestValue < beta)
1489 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1492 BetaCounter.add(pos.side_to_move(), depth, threadID);
1493 move = ss[ply].pv[ply];
1494 if (!pos.move_is_capture_or_promotion(move))
1496 update_history(pos, move, depth, movesSearched, moveCount);
1497 update_killers(move, ss[ply]);
1499 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1502 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1508 // qsearch() is the quiescence search function, which is called by the main
1509 // search function when the remaining depth is zero (or, to be more precise,
1510 // less than OnePly).
1512 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1513 Depth depth, int ply, int threadID) {
1515 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1516 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1518 assert(ply >= 0 && ply < PLY_MAX);
1519 assert(threadID >= 0 && threadID < ActiveThreads);
1524 Value staticValue, bestValue, value, futilityValue;
1525 bool isCheck, enoughMaterial, moveIsCheck;
1526 const TTEntry* tte = NULL;
1528 bool pvNode = (beta - alpha != 1);
1530 // Initialize, and make an early exit in case of an aborted search,
1531 // an instant draw, maximum ply reached, etc.
1532 init_node(ss, ply, threadID);
1534 // After init_node() that calls poll()
1535 if (AbortSearch || thread_should_stop(threadID))
1541 // Transposition table lookup, only when not in PV
1544 tte = TT.retrieve(pos.get_key());
1545 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1547 assert(tte->type() != VALUE_TYPE_EVAL);
1549 return value_from_tt(tte->value(), ply);
1552 ttMove = (tte ? tte->move() : MOVE_NONE);
1554 // Evaluate the position statically
1555 isCheck = pos.is_check();
1556 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1559 staticValue = -VALUE_INFINITE;
1561 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1563 // Use the cached evaluation score if possible
1564 assert(ei.futilityMargin == Value(0));
1566 staticValue = tte->value();
1569 staticValue = evaluate(pos, ei, threadID);
1571 if (ply >= PLY_MAX - 1)
1572 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1574 // Initialize "stand pat score", and return it immediately if it is
1576 bestValue = staticValue;
1578 if (bestValue >= beta)
1580 // Store the score to avoid a future costly evaluation() call
1581 if (!isCheck && !tte && ei.futilityMargin == 0)
1582 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1587 if (bestValue > alpha)
1590 // Initialize a MovePicker object for the current position, and prepare
1591 // to search the moves. Because the depth is <= 0 here, only captures,
1592 // queen promotions and checks (only if depth == 0) will be generated.
1593 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1595 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1597 // Loop through the moves until no moves remain or a beta cutoff
1599 while ( alpha < beta
1600 && (move = mp.get_next_move()) != MOVE_NONE)
1602 assert(move_is_ok(move));
1605 ss[ply].currentMove = move;
1607 moveIsCheck = pos.move_is_check(move, ci);
1615 && !move_is_promotion(move)
1616 && !pos.move_is_passed_pawn_push(move))
1618 futilityValue = staticValue
1619 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1620 pos.endgame_value_of_piece_on(move_to(move)))
1621 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1623 + ei.futilityMargin;
1625 if (futilityValue < alpha)
1627 if (futilityValue > bestValue)
1628 bestValue = futilityValue;
1633 // Don't search captures and checks with negative SEE values
1636 && !move_is_promotion(move)
1637 && pos.see_sign(move) < 0)
1640 // Make and search the move
1641 pos.do_move(move, st, ci, moveIsCheck);
1642 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1643 pos.undo_move(move);
1645 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1648 if (value > bestValue)
1659 // All legal moves have been searched. A special case: If we're in check
1660 // and no legal moves were found, it is checkmate.
1661 if (!moveCount && pos.is_check()) // Mate!
1662 return value_mated_in(ply);
1664 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1666 // Update transposition table
1667 move = ss[ply].pv[ply];
1670 // If bestValue isn't changed it means it is still the static evaluation of
1671 // the node, so keep this info to avoid a future costly evaluation() call.
1672 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1673 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1675 if (bestValue < beta)
1676 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1678 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1681 // Update killers only for good check moves
1682 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1683 update_killers(move, ss[ply]);
1689 // sp_search() is used to search from a split point. This function is called
1690 // by each thread working at the split point. It is similar to the normal
1691 // search() function, but simpler. Because we have already probed the hash
1692 // table, done a null move search, and searched the first move before
1693 // splitting, we don't have to repeat all this work in sp_search(). We
1694 // also don't need to store anything to the hash table here: This is taken
1695 // care of after we return from the split point.
1697 void sp_search(SplitPoint* sp, int threadID) {
1699 assert(threadID >= 0 && threadID < ActiveThreads);
1700 assert(ActiveThreads > 1);
1702 Position pos = Position(sp->pos);
1704 SearchStack* ss = sp->sstack[threadID];
1707 bool isCheck = pos.is_check();
1708 bool useFutilityPruning = sp->depth < SelectiveDepth
1711 while ( sp->bestValue < sp->beta
1712 && !thread_should_stop(threadID)
1713 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1715 assert(move_is_ok(move));
1717 bool moveIsCheck = pos.move_is_check(move, ci);
1718 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1720 lock_grab(&(sp->lock));
1721 int moveCount = ++sp->moves;
1722 lock_release(&(sp->lock));
1724 ss[sp->ply].currentMove = move;
1726 // Decide the new search depth.
1728 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1729 Depth newDepth = sp->depth - OnePly + ext;
1732 if ( useFutilityPruning
1734 && !captureOrPromotion)
1736 // History pruning. See ok_to_prune() definition
1737 if ( moveCount >= 2 + int(sp->depth)
1738 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1739 && sp->bestValue > value_mated_in(PLY_MAX))
1742 // Value based pruning
1743 if (sp->approximateEval < sp->beta)
1745 if (sp->futilityValue == VALUE_NONE)
1748 sp->futilityValue = evaluate(pos, ei, threadID)
1749 + FutilityMargins[int(sp->depth) - 2];
1752 if (sp->futilityValue < sp->beta)
1754 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1756 lock_grab(&(sp->lock));
1757 if (sp->futilityValue > sp->bestValue)
1758 sp->bestValue = sp->futilityValue;
1759 lock_release(&(sp->lock));
1766 // Make and search the move.
1768 pos.do_move(move, st, ci, moveIsCheck);
1770 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1771 // if the move fails high will be re-searched at full depth.
1773 && moveCount >= LMRNonPVMoves
1774 && !captureOrPromotion
1775 && !move_is_castle(move)
1776 && !move_is_killer(move, ss[sp->ply]))
1778 ss[sp->ply].reduction = OnePly;
1779 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1782 value = sp->beta; // Just to trigger next condition
1784 if (value >= sp->beta) // Go with full depth non-pv search
1786 ss[sp->ply].reduction = Depth(0);
1787 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1789 pos.undo_move(move);
1791 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1793 if (thread_should_stop(threadID))
1797 if (value > sp->bestValue) // Less then 2% of cases
1799 lock_grab(&(sp->lock));
1800 if (value > sp->bestValue && !thread_should_stop(threadID))
1802 sp->bestValue = value;
1803 if (sp->bestValue >= sp->beta)
1805 sp_update_pv(sp->parentSstack, ss, sp->ply);
1806 for (int i = 0; i < ActiveThreads; i++)
1807 if (i != threadID && (i == sp->master || sp->slaves[i]))
1808 Threads[i].stop = true;
1810 sp->finished = true;
1813 lock_release(&(sp->lock));
1817 lock_grab(&(sp->lock));
1819 // If this is the master thread and we have been asked to stop because of
1820 // a beta cutoff higher up in the tree, stop all slave threads.
1821 if (sp->master == threadID && thread_should_stop(threadID))
1822 for (int i = 0; i < ActiveThreads; i++)
1824 Threads[i].stop = true;
1827 sp->slaves[threadID] = 0;
1829 lock_release(&(sp->lock));
1833 // sp_search_pv() is used to search from a PV split point. This function
1834 // is called by each thread working at the split point. It is similar to
1835 // the normal search_pv() function, but simpler. Because we have already
1836 // probed the hash table and searched the first move before splitting, we
1837 // don't have to repeat all this work in sp_search_pv(). We also don't
1838 // need to store anything to the hash table here: This is taken care of
1839 // after we return from the split point.
1841 void sp_search_pv(SplitPoint* sp, int threadID) {
1843 assert(threadID >= 0 && threadID < ActiveThreads);
1844 assert(ActiveThreads > 1);
1846 Position pos = Position(sp->pos);
1848 SearchStack* ss = sp->sstack[threadID];
1852 while ( sp->alpha < sp->beta
1853 && !thread_should_stop(threadID)
1854 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1856 bool moveIsCheck = pos.move_is_check(move, ci);
1857 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1859 assert(move_is_ok(move));
1861 lock_grab(&(sp->lock));
1862 int moveCount = ++sp->moves;
1863 lock_release(&(sp->lock));
1865 ss[sp->ply].currentMove = move;
1867 // Decide the new search depth.
1869 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1870 Depth newDepth = sp->depth - OnePly + ext;
1872 // Make and search the move.
1874 pos.do_move(move, st, ci, moveIsCheck);
1876 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1877 // if the move fails high will be re-searched at full depth.
1879 && moveCount >= LMRPVMoves
1880 && !captureOrPromotion
1881 && !move_is_castle(move)
1882 && !move_is_killer(move, ss[sp->ply]))
1884 ss[sp->ply].reduction = OnePly;
1885 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1888 value = sp->alpha + 1; // Just to trigger next condition
1890 if (value > sp->alpha) // Go with full depth non-pv search
1892 ss[sp->ply].reduction = Depth(0);
1893 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1895 if (value > sp->alpha && value < sp->beta)
1897 // When the search fails high at ply 1 while searching the first
1898 // move at the root, set the flag failHighPly1. This is used for
1899 // time managment: We don't want to stop the search early in
1900 // such cases, because resolving the fail high at ply 1 could
1901 // result in a big drop in score at the root.
1902 if (sp->ply == 1 && RootMoveNumber == 1)
1903 Threads[threadID].failHighPly1 = true;
1905 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1906 Threads[threadID].failHighPly1 = false;
1909 pos.undo_move(move);
1911 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1913 if (thread_should_stop(threadID))
1917 lock_grab(&(sp->lock));
1918 if (value > sp->bestValue && !thread_should_stop(threadID))
1920 sp->bestValue = value;
1921 if (value > sp->alpha)
1924 sp_update_pv(sp->parentSstack, ss, sp->ply);
1925 if (value == value_mate_in(sp->ply + 1))
1926 ss[sp->ply].mateKiller = move;
1928 if (value >= sp->beta)
1930 for (int i = 0; i < ActiveThreads; i++)
1931 if (i != threadID && (i == sp->master || sp->slaves[i]))
1932 Threads[i].stop = true;
1934 sp->finished = true;
1937 // If we are at ply 1, and we are searching the first root move at
1938 // ply 0, set the 'Problem' variable if the score has dropped a lot
1939 // (from the computer's point of view) since the previous iteration.
1942 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1945 lock_release(&(sp->lock));
1948 lock_grab(&(sp->lock));
1950 // If this is the master thread and we have been asked to stop because of
1951 // a beta cutoff higher up in the tree, stop all slave threads.
1952 if (sp->master == threadID && thread_should_stop(threadID))
1953 for (int i = 0; i < ActiveThreads; i++)
1955 Threads[i].stop = true;
1958 sp->slaves[threadID] = 0;
1960 lock_release(&(sp->lock));
1963 /// The BetaCounterType class
1965 BetaCounterType::BetaCounterType() { clear(); }
1967 void BetaCounterType::clear() {
1969 for (int i = 0; i < THREAD_MAX; i++)
1970 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1973 void BetaCounterType::add(Color us, Depth d, int threadID) {
1975 // Weighted count based on depth
1976 Threads[threadID].betaCutOffs[us] += unsigned(d);
1979 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1982 for (int i = 0; i < THREAD_MAX; i++)
1984 our += Threads[i].betaCutOffs[us];
1985 their += Threads[i].betaCutOffs[opposite_color(us)];
1990 /// The RootMove class
1994 RootMove::RootMove() {
1995 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1998 // RootMove::operator<() is the comparison function used when
1999 // sorting the moves. A move m1 is considered to be better
2000 // than a move m2 if it has a higher score, or if the moves
2001 // have equal score but m1 has the higher node count.
2003 bool RootMove::operator<(const RootMove& m) {
2005 if (score != m.score)
2006 return (score < m.score);
2008 return theirBeta <= m.theirBeta;
2011 /// The RootMoveList class
2015 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2017 MoveStack mlist[MaxRootMoves];
2018 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2020 // Generate all legal moves
2021 MoveStack* last = generate_moves(pos, mlist);
2023 // Add each move to the moves[] array
2024 for (MoveStack* cur = mlist; cur != last; cur++)
2026 bool includeMove = includeAllMoves;
2028 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2029 includeMove = (searchMoves[k] == cur->move);
2034 // Find a quick score for the move
2036 SearchStack ss[PLY_MAX_PLUS_2];
2039 moves[count].move = cur->move;
2040 pos.do_move(moves[count].move, st);
2041 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2042 pos.undo_move(moves[count].move);
2043 moves[count].pv[0] = moves[count].move;
2044 moves[count].pv[1] = MOVE_NONE; // FIXME
2051 // Simple accessor methods for the RootMoveList class
2053 inline Move RootMoveList::get_move(int moveNum) const {
2054 return moves[moveNum].move;
2057 inline Value RootMoveList::get_move_score(int moveNum) const {
2058 return moves[moveNum].score;
2061 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2062 moves[moveNum].score = score;
2065 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2066 moves[moveNum].nodes = nodes;
2067 moves[moveNum].cumulativeNodes += nodes;
2070 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2071 moves[moveNum].ourBeta = our;
2072 moves[moveNum].theirBeta = their;
2075 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2077 for(j = 0; pv[j] != MOVE_NONE; j++)
2078 moves[moveNum].pv[j] = pv[j];
2079 moves[moveNum].pv[j] = MOVE_NONE;
2082 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2083 return moves[moveNum].pv[i];
2086 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2087 return moves[moveNum].cumulativeNodes;
2090 inline int RootMoveList::move_count() const {
2095 // RootMoveList::scan_for_easy_move() is called at the end of the first
2096 // iteration, and is used to detect an "easy move", i.e. a move which appears
2097 // to be much bester than all the rest. If an easy move is found, the move
2098 // is returned, otherwise the function returns MOVE_NONE. It is very
2099 // important that this function is called at the right moment: The code
2100 // assumes that the first iteration has been completed and the moves have
2101 // been sorted. This is done in RootMoveList c'tor.
2103 Move RootMoveList::scan_for_easy_move() const {
2110 // moves are sorted so just consider the best and the second one
2111 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2117 // RootMoveList::sort() sorts the root move list at the beginning of a new
2120 inline void RootMoveList::sort() {
2122 sort_multipv(count - 1); // all items
2126 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2127 // list by their scores and depths. It is used to order the different PVs
2128 // correctly in MultiPV mode.
2130 void RootMoveList::sort_multipv(int n) {
2132 for (int i = 1; i <= n; i++)
2134 RootMove rm = moves[i];
2136 for (j = i; j > 0 && moves[j-1] < rm; j--)
2137 moves[j] = moves[j-1];
2143 // init_node() is called at the beginning of all the search functions
2144 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2145 // stack object corresponding to the current node. Once every
2146 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2147 // for user input and checks whether it is time to stop the search.
2149 void init_node(SearchStack ss[], int ply, int threadID) {
2151 assert(ply >= 0 && ply < PLY_MAX);
2152 assert(threadID >= 0 && threadID < ActiveThreads);
2154 Threads[threadID].nodes++;
2159 if (NodesSincePoll >= NodesBetweenPolls)
2166 ss[ply+2].initKillers();
2168 if (Threads[threadID].printCurrentLine)
2169 print_current_line(ss, ply, threadID);
2173 // update_pv() is called whenever a search returns a value > alpha. It
2174 // updates the PV in the SearchStack object corresponding to the current
2177 void update_pv(SearchStack ss[], int ply) {
2178 assert(ply >= 0 && ply < PLY_MAX);
2180 ss[ply].pv[ply] = ss[ply].currentMove;
2182 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2183 ss[ply].pv[p] = ss[ply+1].pv[p];
2184 ss[ply].pv[p] = MOVE_NONE;
2188 // sp_update_pv() is a variant of update_pv for use at split points. The
2189 // difference between the two functions is that sp_update_pv also updates
2190 // the PV at the parent node.
2192 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2193 assert(ply >= 0 && ply < PLY_MAX);
2195 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2197 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2198 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2199 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2203 // connected_moves() tests whether two moves are 'connected' in the sense
2204 // that the first move somehow made the second move possible (for instance
2205 // if the moving piece is the same in both moves). The first move is
2206 // assumed to be the move that was made to reach the current position, while
2207 // the second move is assumed to be a move from the current position.
2209 bool connected_moves(const Position& pos, Move m1, Move m2) {
2211 Square f1, t1, f2, t2;
2214 assert(move_is_ok(m1));
2215 assert(move_is_ok(m2));
2217 if (m2 == MOVE_NONE)
2220 // Case 1: The moving piece is the same in both moves
2226 // Case 2: The destination square for m2 was vacated by m1
2232 // Case 3: Moving through the vacated square
2233 if ( piece_is_slider(pos.piece_on(f2))
2234 && bit_is_set(squares_between(f2, t2), f1))
2237 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2238 p = pos.piece_on(t1);
2239 if (bit_is_set(pos.attacks_from(p, t1), t2))
2242 // Case 5: Discovered check, checking piece is the piece moved in m1
2243 if ( piece_is_slider(p)
2244 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2245 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2247 Bitboard occ = pos.occupied_squares();
2248 Color us = pos.side_to_move();
2249 Square ksq = pos.king_square(us);
2250 clear_bit(&occ, f2);
2251 if (type_of_piece(p) == BISHOP)
2253 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2256 else if (type_of_piece(p) == ROOK)
2258 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2263 assert(type_of_piece(p) == QUEEN);
2264 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2272 // value_is_mate() checks if the given value is a mate one
2273 // eventually compensated for the ply.
2275 bool value_is_mate(Value value) {
2277 assert(abs(value) <= VALUE_INFINITE);
2279 return value <= value_mated_in(PLY_MAX)
2280 || value >= value_mate_in(PLY_MAX);
2284 // move_is_killer() checks if the given move is among the
2285 // killer moves of that ply.
2287 bool move_is_killer(Move m, const SearchStack& ss) {
2289 const Move* k = ss.killers;
2290 for (int i = 0; i < KILLER_MAX; i++, k++)
2298 // extension() decides whether a move should be searched with normal depth,
2299 // or with extended depth. Certain classes of moves (checking moves, in
2300 // particular) are searched with bigger depth than ordinary moves and in
2301 // any case are marked as 'dangerous'. Note that also if a move is not
2302 // extended, as example because the corresponding UCI option is set to zero,
2303 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2305 Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion,
2306 bool check, bool singleReply, bool mateThreat, bool* dangerous) {
2308 assert(m != MOVE_NONE);
2310 Depth result = Depth(0);
2311 *dangerous = check | singleReply | mateThreat;
2316 result += CheckExtension[pvNode];
2319 result += SingleReplyExtension[pvNode];
2322 result += MateThreatExtension[pvNode];
2325 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2327 Color c = pos.side_to_move();
2328 if (relative_rank(c, move_to(m)) == RANK_7)
2330 result += PawnPushTo7thExtension[pvNode];
2333 if (pos.pawn_is_passed(c, move_to(m)))
2335 result += PassedPawnExtension[pvNode];
2340 if ( captureOrPromotion
2341 && pos.type_of_piece_on(move_to(m)) != PAWN
2342 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2343 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2344 && !move_is_promotion(m)
2347 result += PawnEndgameExtension[pvNode];
2352 && captureOrPromotion
2353 && pos.type_of_piece_on(move_to(m)) != PAWN
2354 && pos.see_sign(m) >= 0)
2360 return Min(result, OnePly);
2364 // ok_to_do_nullmove() looks at the current position and decides whether
2365 // doing a 'null move' should be allowed. In order to avoid zugzwang
2366 // problems, null moves are not allowed when the side to move has very
2367 // little material left. Currently, the test is a bit too simple: Null
2368 // moves are avoided only when the side to move has only pawns left. It's
2369 // probably a good idea to avoid null moves in at least some more
2370 // complicated endgames, e.g. KQ vs KR. FIXME
2372 bool ok_to_do_nullmove(const Position& pos) {
2374 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2378 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2379 // non-tactical moves late in the move list close to the leaves are
2380 // candidates for pruning.
2382 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2384 assert(move_is_ok(m));
2385 assert(threat == MOVE_NONE || move_is_ok(threat));
2386 assert(!pos.move_is_check(m));
2387 assert(!pos.move_is_capture_or_promotion(m));
2388 assert(!pos.move_is_passed_pawn_push(m));
2389 assert(d >= OnePly);
2391 Square mfrom, mto, tfrom, tto;
2393 mfrom = move_from(m);
2395 tfrom = move_from(threat);
2396 tto = move_to(threat);
2398 // Case 1: Castling moves are never pruned
2399 if (move_is_castle(m))
2402 // Case 2: Don't prune moves which move the threatened piece
2403 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2406 // Case 3: If the threatened piece has value less than or equal to the
2407 // value of the threatening piece, don't prune move which defend it.
2408 if ( !PruneDefendingMoves
2409 && threat != MOVE_NONE
2410 && pos.move_is_capture(threat)
2411 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2412 || pos.type_of_piece_on(tfrom) == KING)
2413 && pos.move_attacks_square(m, tto))
2416 // Case 4: Don't prune moves with good history
2417 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2420 // Case 5: If the moving piece in the threatened move is a slider, don't
2421 // prune safe moves which block its ray.
2422 if ( !PruneBlockingMoves
2423 && threat != MOVE_NONE
2424 && piece_is_slider(pos.piece_on(tfrom))
2425 && bit_is_set(squares_between(tfrom, tto), mto)
2426 && pos.see_sign(m) >= 0)
2433 // ok_to_use_TT() returns true if a transposition table score
2434 // can be used at a given point in search.
2436 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2438 Value v = value_from_tt(tte->value(), ply);
2440 return ( tte->depth() >= depth
2441 || v >= Max(value_mate_in(100), beta)
2442 || v < Min(value_mated_in(100), beta))
2444 && ( (is_lower_bound(tte->type()) && v >= beta)
2445 || (is_upper_bound(tte->type()) && v < beta));
2449 // update_history() registers a good move that produced a beta-cutoff
2450 // in history and marks as failures all the other moves of that ply.
2452 void update_history(const Position& pos, Move m, Depth depth,
2453 Move movesSearched[], int moveCount) {
2455 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2457 for (int i = 0; i < moveCount - 1; i++)
2459 assert(m != movesSearched[i]);
2460 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2461 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2466 // update_killers() add a good move that produced a beta-cutoff
2467 // among the killer moves of that ply.
2469 void update_killers(Move m, SearchStack& ss) {
2471 if (m == ss.killers[0])
2474 for (int i = KILLER_MAX - 1; i > 0; i--)
2475 ss.killers[i] = ss.killers[i - 1];
2481 // fail_high_ply_1() checks if some thread is currently resolving a fail
2482 // high at ply 1 at the node below the first root node. This information
2483 // is used for time managment.
2485 bool fail_high_ply_1() {
2487 for(int i = 0; i < ActiveThreads; i++)
2488 if (Threads[i].failHighPly1)
2495 // current_search_time() returns the number of milliseconds which have passed
2496 // since the beginning of the current search.
2498 int current_search_time() {
2499 return get_system_time() - SearchStartTime;
2503 // nps() computes the current nodes/second count.
2506 int t = current_search_time();
2507 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2511 // poll() performs two different functions: It polls for user input, and it
2512 // looks at the time consumed so far and decides if it's time to abort the
2517 static int lastInfoTime;
2518 int t = current_search_time();
2523 // We are line oriented, don't read single chars
2524 std::string command;
2525 if (!std::getline(std::cin, command))
2528 if (command == "quit")
2531 PonderSearch = false;
2535 else if (command == "stop")
2538 PonderSearch = false;
2540 else if (command == "ponderhit")
2543 // Print search information
2547 else if (lastInfoTime > t)
2548 // HACK: Must be a new search where we searched less than
2549 // NodesBetweenPolls nodes during the first second of search.
2552 else if (t - lastInfoTime >= 1000)
2559 if (dbg_show_hit_rate)
2560 dbg_print_hit_rate();
2562 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2563 << " time " << t << " hashfull " << TT.full() << std::endl;
2564 lock_release(&IOLock);
2565 if (ShowCurrentLine)
2566 Threads[0].printCurrentLine = true;
2568 // Should we stop the search?
2572 bool overTime = t > AbsoluteMaxSearchTime
2573 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2574 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2575 && t > 6*(MaxSearchTime + ExtraSearchTime));
2577 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2578 || (ExactMaxTime && t >= ExactMaxTime)
2579 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2584 // ponderhit() is called when the program is pondering (i.e. thinking while
2585 // it's the opponent's turn to move) in order to let the engine know that
2586 // it correctly predicted the opponent's move.
2590 int t = current_search_time();
2591 PonderSearch = false;
2592 if (Iteration >= 3 &&
2593 (!InfiniteSearch && (StopOnPonderhit ||
2594 t > AbsoluteMaxSearchTime ||
2595 (RootMoveNumber == 1 &&
2596 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2597 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2598 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2603 // print_current_line() prints the current line of search for a given
2604 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2606 void print_current_line(SearchStack ss[], int ply, int threadID) {
2608 assert(ply >= 0 && ply < PLY_MAX);
2609 assert(threadID >= 0 && threadID < ActiveThreads);
2611 if (!Threads[threadID].idle)
2614 std::cout << "info currline " << (threadID + 1);
2615 for (int p = 0; p < ply; p++)
2616 std::cout << " " << ss[p].currentMove;
2618 std::cout << std::endl;
2619 lock_release(&IOLock);
2621 Threads[threadID].printCurrentLine = false;
2622 if (threadID + 1 < ActiveThreads)
2623 Threads[threadID + 1].printCurrentLine = true;
2627 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2629 void init_ss_array(SearchStack ss[]) {
2631 for (int i = 0; i < 3; i++)
2634 ss[i].initKillers();
2639 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2640 // while the program is pondering. The point is to work around a wrinkle in
2641 // the UCI protocol: When pondering, the engine is not allowed to give a
2642 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2643 // We simply wait here until one of these commands is sent, and return,
2644 // after which the bestmove and pondermove will be printed (in id_loop()).
2646 void wait_for_stop_or_ponderhit() {
2648 std::string command;
2652 if (!std::getline(std::cin, command))
2655 if (command == "quit")
2660 else if (command == "ponderhit" || command == "stop")
2666 // idle_loop() is where the threads are parked when they have no work to do.
2667 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2668 // object for which the current thread is the master.
2670 void idle_loop(int threadID, SplitPoint* waitSp) {
2671 assert(threadID >= 0 && threadID < THREAD_MAX);
2673 Threads[threadID].running = true;
2676 if(AllThreadsShouldExit && threadID != 0)
2679 // If we are not thinking, wait for a condition to be signaled instead
2680 // of wasting CPU time polling for work:
2681 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2682 #if !defined(_MSC_VER)
2683 pthread_mutex_lock(&WaitLock);
2684 if(Idle || threadID >= ActiveThreads)
2685 pthread_cond_wait(&WaitCond, &WaitLock);
2686 pthread_mutex_unlock(&WaitLock);
2688 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2692 // If this thread has been assigned work, launch a search
2693 if(Threads[threadID].workIsWaiting) {
2694 Threads[threadID].workIsWaiting = false;
2695 if(Threads[threadID].splitPoint->pvNode)
2696 sp_search_pv(Threads[threadID].splitPoint, threadID);
2698 sp_search(Threads[threadID].splitPoint, threadID);
2699 Threads[threadID].idle = true;
2702 // If this thread is the master of a split point and all threads have
2703 // finished their work at this split point, return from the idle loop.
2704 if(waitSp != NULL && waitSp->cpus == 0)
2708 Threads[threadID].running = false;
2712 // init_split_point_stack() is called during program initialization, and
2713 // initializes all split point objects.
2715 void init_split_point_stack() {
2716 for(int i = 0; i < THREAD_MAX; i++)
2717 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2718 SplitPointStack[i][j].parent = NULL;
2719 lock_init(&(SplitPointStack[i][j].lock), NULL);
2724 // destroy_split_point_stack() is called when the program exits, and
2725 // destroys all locks in the precomputed split point objects.
2727 void destroy_split_point_stack() {
2728 for(int i = 0; i < THREAD_MAX; i++)
2729 for(int j = 0; j < MaxActiveSplitPoints; j++)
2730 lock_destroy(&(SplitPointStack[i][j].lock));
2734 // thread_should_stop() checks whether the thread with a given threadID has
2735 // been asked to stop, directly or indirectly. This can happen if a beta
2736 // cutoff has occured in thre thread's currently active split point, or in
2737 // some ancestor of the current split point.
2739 bool thread_should_stop(int threadID) {
2740 assert(threadID >= 0 && threadID < ActiveThreads);
2744 if(Threads[threadID].stop)
2746 if(ActiveThreads <= 2)
2748 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2750 Threads[threadID].stop = true;
2757 // thread_is_available() checks whether the thread with threadID "slave" is
2758 // available to help the thread with threadID "master" at a split point. An
2759 // obvious requirement is that "slave" must be idle. With more than two
2760 // threads, this is not by itself sufficient: If "slave" is the master of
2761 // some active split point, it is only available as a slave to the other
2762 // threads which are busy searching the split point at the top of "slave"'s
2763 // split point stack (the "helpful master concept" in YBWC terminology).
2765 bool thread_is_available(int slave, int master) {
2766 assert(slave >= 0 && slave < ActiveThreads);
2767 assert(master >= 0 && master < ActiveThreads);
2768 assert(ActiveThreads > 1);
2770 if(!Threads[slave].idle || slave == master)
2773 if(Threads[slave].activeSplitPoints == 0)
2774 // No active split points means that the thread is available as a slave
2775 // for any other thread.
2778 if(ActiveThreads == 2)
2781 // Apply the "helpful master" concept if possible.
2782 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2789 // idle_thread_exists() tries to find an idle thread which is available as
2790 // a slave for the thread with threadID "master".
2792 bool idle_thread_exists(int master) {
2793 assert(master >= 0 && master < ActiveThreads);
2794 assert(ActiveThreads > 1);
2796 for(int i = 0; i < ActiveThreads; i++)
2797 if(thread_is_available(i, master))
2803 // split() does the actual work of distributing the work at a node between
2804 // several threads at PV nodes. If it does not succeed in splitting the
2805 // node (because no idle threads are available, or because we have no unused
2806 // split point objects), the function immediately returns false. If
2807 // splitting is possible, a SplitPoint object is initialized with all the
2808 // data that must be copied to the helper threads (the current position and
2809 // search stack, alpha, beta, the search depth, etc.), and we tell our
2810 // helper threads that they have been assigned work. This will cause them
2811 // to instantly leave their idle loops and call sp_search_pv(). When all
2812 // threads have returned from sp_search_pv (or, equivalently, when
2813 // splitPoint->cpus becomes 0), split() returns true.
2815 bool split(const Position& p, SearchStack* sstck, int ply,
2816 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2817 const Value approximateEval, Depth depth, int* moves,
2818 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2821 assert(sstck != NULL);
2822 assert(ply >= 0 && ply < PLY_MAX);
2823 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2824 assert(!pvNode || *alpha < *beta);
2825 assert(*beta <= VALUE_INFINITE);
2826 assert(depth > Depth(0));
2827 assert(master >= 0 && master < ActiveThreads);
2828 assert(ActiveThreads > 1);
2830 SplitPoint* splitPoint;
2835 // If no other thread is available to help us, or if we have too many
2836 // active split points, don't split.
2837 if(!idle_thread_exists(master) ||
2838 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2839 lock_release(&MPLock);
2843 // Pick the next available split point object from the split point stack
2844 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2845 Threads[master].activeSplitPoints++;
2847 // Initialize the split point object
2848 splitPoint->parent = Threads[master].splitPoint;
2849 splitPoint->finished = false;
2850 splitPoint->ply = ply;
2851 splitPoint->depth = depth;
2852 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2853 splitPoint->beta = *beta;
2854 splitPoint->pvNode = pvNode;
2855 splitPoint->dcCandidates = dcCandidates;
2856 splitPoint->bestValue = *bestValue;
2857 splitPoint->futilityValue = futilityValue;
2858 splitPoint->approximateEval = approximateEval;
2859 splitPoint->master = master;
2860 splitPoint->mp = mp;
2861 splitPoint->moves = *moves;
2862 splitPoint->cpus = 1;
2863 splitPoint->pos.copy(p);
2864 splitPoint->parentSstack = sstck;
2865 for(i = 0; i < ActiveThreads; i++)
2866 splitPoint->slaves[i] = 0;
2868 // Copy the current position and the search stack to the master thread
2869 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2870 Threads[master].splitPoint = splitPoint;
2872 // Make copies of the current position and search stack for each thread
2873 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2875 if(thread_is_available(i, master)) {
2876 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2877 Threads[i].splitPoint = splitPoint;
2878 splitPoint->slaves[i] = 1;
2882 // Tell the threads that they have work to do. This will make them leave
2884 for(i = 0; i < ActiveThreads; i++)
2885 if(i == master || splitPoint->slaves[i]) {
2886 Threads[i].workIsWaiting = true;
2887 Threads[i].idle = false;
2888 Threads[i].stop = false;
2891 lock_release(&MPLock);
2893 // Everything is set up. The master thread enters the idle loop, from
2894 // which it will instantly launch a search, because its workIsWaiting
2895 // slot is 'true'. We send the split point as a second parameter to the
2896 // idle loop, which means that the main thread will return from the idle
2897 // loop when all threads have finished their work at this split point
2898 // (i.e. when // splitPoint->cpus == 0).
2899 idle_loop(master, splitPoint);
2901 // We have returned from the idle loop, which means that all threads are
2902 // finished. Update alpha, beta and bestvalue, and return.
2904 if(pvNode) *alpha = splitPoint->alpha;
2905 *beta = splitPoint->beta;
2906 *bestValue = splitPoint->bestValue;
2907 Threads[master].stop = false;
2908 Threads[master].idle = false;
2909 Threads[master].activeSplitPoints--;
2910 Threads[master].splitPoint = splitPoint->parent;
2911 lock_release(&MPLock);
2917 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2918 // to start a new search from the root.
2920 void wake_sleeping_threads() {
2921 if(ActiveThreads > 1) {
2922 for(int i = 1; i < ActiveThreads; i++) {
2923 Threads[i].idle = true;
2924 Threads[i].workIsWaiting = false;
2926 #if !defined(_MSC_VER)
2927 pthread_mutex_lock(&WaitLock);
2928 pthread_cond_broadcast(&WaitCond);
2929 pthread_mutex_unlock(&WaitLock);
2931 for(int i = 1; i < THREAD_MAX; i++)
2932 SetEvent(SitIdleEvent[i]);
2938 // init_thread() is the function which is called when a new thread is
2939 // launched. It simply calls the idle_loop() function with the supplied
2940 // threadID. There are two versions of this function; one for POSIX threads
2941 // and one for Windows threads.
2943 #if !defined(_MSC_VER)
2945 void *init_thread(void *threadID) {
2946 idle_loop(*(int *)threadID, NULL);
2952 DWORD WINAPI init_thread(LPVOID threadID) {
2953 idle_loop(*(int *)threadID, NULL);