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 // Each move futility margin is decreased
180 const Value IncrementalFutilityMargin = Value(0x8);
182 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
183 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
184 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
185 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
187 const Depth RazorDepth = 4*OnePly;
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
192 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
193 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
196 /// Variables initialized by UCI options
198 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
199 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
201 // Depth limit for use of dynamic threat detection
202 Depth ThreatDepth; // heavy SMP read access
204 // Last seconds noise filtering (LSN)
205 const bool UseLSNFiltering = true;
206 const int LSNTime = 4000; // In milliseconds
207 const Value LSNValue = value_from_centipawns(200);
208 bool loseOnTime = false;
210 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
211 // There is heavy SMP read access on these arrays
212 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
213 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
215 // Iteration counters
217 BetaCounterType BetaCounter; // has per-thread internal data
219 // Scores and number of times the best move changed for each iteration
220 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
221 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
226 // Time managment variables
228 int MaxNodes, MaxDepth;
229 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
233 bool StopOnPonderhit;
234 bool AbortSearch; // heavy SMP read access
240 // Show current line?
241 bool ShowCurrentLine;
245 std::ofstream LogFile;
247 // MP related variables
248 int ActiveThreads = 1;
249 Depth MinimumSplitDepth;
250 int MaxThreadsPerSplitPoint;
251 Thread Threads[THREAD_MAX];
254 bool AllThreadsShouldExit = false;
255 const int MaxActiveSplitPoints = 8;
256 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
259 #if !defined(_MSC_VER)
260 pthread_cond_t WaitCond;
261 pthread_mutex_t WaitLock;
263 HANDLE SitIdleEvent[THREAD_MAX];
266 // Node counters, used only by thread[0] but try to keep in different
267 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
269 int NodesBetweenPolls = 30000;
277 Value id_loop(const Position& pos, Move searchMoves[]);
278 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
279 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
280 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move forbiddenMove = MOVE_NONE);
281 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
282 void sp_search(SplitPoint* sp, int threadID);
283 void sp_search_pv(SplitPoint* sp, int threadID);
284 void init_node(SearchStack ss[], int ply, int threadID);
285 void update_pv(SearchStack ss[], int ply);
286 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
287 bool connected_moves(const Position& pos, Move m1, Move m2);
288 bool value_is_mate(Value value);
289 bool move_is_killer(Move m, const SearchStack& ss);
290 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
291 bool ok_to_do_nullmove(const Position& pos);
292 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
293 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
294 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
295 void update_killers(Move m, SearchStack& ss);
297 bool fail_high_ply_1();
298 int current_search_time();
302 void print_current_line(SearchStack ss[], int ply, int threadID);
303 void wait_for_stop_or_ponderhit();
304 void init_ss_array(SearchStack ss[]);
306 void idle_loop(int threadID, SplitPoint* waitSp);
307 void init_split_point_stack();
308 void destroy_split_point_stack();
309 bool thread_should_stop(int threadID);
310 bool thread_is_available(int slave, int master);
311 bool idle_thread_exists(int master);
312 bool split(const Position& pos, SearchStack* ss, int ply,
313 Value *alpha, Value *beta, Value *bestValue,
314 const Value futilityValue, const Value approximateValue,
315 Depth depth, int *moves,
316 MovePicker *mp, int master, bool pvNode);
317 void wake_sleeping_threads();
319 #if !defined(_MSC_VER)
320 void *init_thread(void *threadID);
322 DWORD WINAPI init_thread(LPVOID threadID);
333 /// perft() is our utility to verify move generation is bug free. All the
334 /// legal moves up to given depth are generated and counted and the sum returned.
336 int perft(Position& pos, Depth depth)
340 MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H);
342 // If we are at the last ply we don't need to do and undo
343 // the moves, just to count them.
344 if (depth <= OnePly) // Replace with '<' to test also qsearch
346 while (mp.get_next_move()) sum++;
350 // Loop through all legal moves
352 while ((move = mp.get_next_move()) != MOVE_NONE)
355 pos.do_move(move, st, ci, pos.move_is_check(move, ci));
356 sum += perft(pos, depth - OnePly);
363 /// think() is the external interface to Stockfish's search, and is called when
364 /// the program receives the UCI 'go' command. It initializes various
365 /// search-related global variables, and calls root_search(). It returns false
366 /// when a quit command is received during the search.
368 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
369 int time[], int increment[], int movesToGo, int maxDepth,
370 int maxNodes, int maxTime, Move searchMoves[]) {
372 // Look for a book move
373 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
376 if (get_option_value_string("Book File") != OpeningBook.file_name())
377 OpeningBook.open("book.bin");
379 bookMove = OpeningBook.get_move(pos);
380 if (bookMove != MOVE_NONE)
382 std::cout << "bestmove " << bookMove << std::endl;
387 // Initialize global search variables
389 SearchStartTime = get_system_time();
390 for (int i = 0; i < THREAD_MAX; i++)
392 Threads[i].nodes = 0ULL;
393 Threads[i].failHighPly1 = false;
396 InfiniteSearch = infinite;
397 PonderSearch = ponder;
398 StopOnPonderhit = false;
404 ExactMaxTime = maxTime;
406 // Read UCI option values
407 TT.set_size(get_option_value_int("Hash"));
408 if (button_was_pressed("Clear Hash"))
411 loseOnTime = false; // reset at the beginning of a new game
414 bool PonderingEnabled = get_option_value_bool("Ponder");
415 MultiPV = get_option_value_int("MultiPV");
417 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
418 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
420 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
421 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
423 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
424 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
426 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
427 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
429 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
430 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
432 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
433 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
435 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
436 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
437 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
439 Chess960 = get_option_value_bool("UCI_Chess960");
440 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
441 UseLogFile = get_option_value_bool("Use Search Log");
443 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
445 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
446 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
448 read_weights(pos.side_to_move());
450 // Set the number of active threads
451 int newActiveThreads = get_option_value_int("Threads");
452 if (newActiveThreads != ActiveThreads)
454 ActiveThreads = newActiveThreads;
455 init_eval(ActiveThreads);
458 // Wake up sleeping threads
459 wake_sleeping_threads();
461 for (int i = 1; i < ActiveThreads; i++)
462 assert(thread_is_available(i, 0));
465 int myTime = time[side_to_move];
466 int myIncrement = increment[side_to_move];
468 if (!movesToGo) // Sudden death time control
472 MaxSearchTime = myTime / 30 + myIncrement;
473 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
474 } else { // Blitz game without increment
475 MaxSearchTime = myTime / 30;
476 AbsoluteMaxSearchTime = myTime / 8;
479 else // (x moves) / (y minutes)
483 MaxSearchTime = myTime / 2;
484 AbsoluteMaxSearchTime =
485 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
487 MaxSearchTime = myTime / Min(movesToGo, 20);
488 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
492 if (PonderingEnabled)
494 MaxSearchTime += MaxSearchTime / 4;
495 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
498 // Fixed depth or fixed number of nodes?
501 InfiniteSearch = true; // HACK
506 NodesBetweenPolls = Min(MaxNodes, 30000);
507 InfiniteSearch = true; // HACK
509 else if (myTime && myTime < 1000)
510 NodesBetweenPolls = 1000;
511 else if (myTime && myTime < 5000)
512 NodesBetweenPolls = 5000;
514 NodesBetweenPolls = 30000;
516 // Write information to search log file
518 LogFile << "Searching: " << pos.to_fen() << std::endl
519 << "infinite: " << infinite
520 << " ponder: " << ponder
521 << " time: " << myTime
522 << " increment: " << myIncrement
523 << " moves to go: " << movesToGo << std::endl;
526 // We're ready to start thinking. Call the iterative deepening loop function
528 // FIXME we really need to cleanup all this LSN ugliness
531 Value v = id_loop(pos, searchMoves);
532 loseOnTime = ( UseLSNFiltering
539 loseOnTime = false; // reset for next match
540 while (SearchStartTime + myTime + 1000 > get_system_time())
542 id_loop(pos, searchMoves); // to fail gracefully
553 /// init_threads() is called during startup. It launches all helper threads,
554 /// and initializes the split point stack and the global locks and condition
557 void init_threads() {
561 #if !defined(_MSC_VER)
562 pthread_t pthread[1];
565 for (i = 0; i < THREAD_MAX; i++)
566 Threads[i].activeSplitPoints = 0;
568 // Initialize global locks
569 lock_init(&MPLock, NULL);
570 lock_init(&IOLock, NULL);
572 init_split_point_stack();
574 #if !defined(_MSC_VER)
575 pthread_mutex_init(&WaitLock, NULL);
576 pthread_cond_init(&WaitCond, NULL);
578 for (i = 0; i < THREAD_MAX; i++)
579 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
582 // All threads except the main thread should be initialized to idle state
583 for (i = 1; i < THREAD_MAX; i++)
585 Threads[i].stop = false;
586 Threads[i].workIsWaiting = false;
587 Threads[i].idle = true;
588 Threads[i].running = false;
591 // Launch the helper threads
592 for(i = 1; i < THREAD_MAX; i++)
594 #if !defined(_MSC_VER)
595 pthread_create(pthread, NULL, init_thread, (void*)(&i));
598 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
601 // Wait until the thread has finished launching
602 while (!Threads[i].running);
607 /// stop_threads() is called when the program exits. It makes all the
608 /// helper threads exit cleanly.
610 void stop_threads() {
612 ActiveThreads = THREAD_MAX; // HACK
613 Idle = false; // HACK
614 wake_sleeping_threads();
615 AllThreadsShouldExit = true;
616 for (int i = 1; i < THREAD_MAX; i++)
618 Threads[i].stop = true;
619 while(Threads[i].running);
621 destroy_split_point_stack();
625 /// nodes_searched() returns the total number of nodes searched so far in
626 /// the current search.
628 int64_t nodes_searched() {
630 int64_t result = 0ULL;
631 for (int i = 0; i < ActiveThreads; i++)
632 result += Threads[i].nodes;
637 // SearchStack::init() initializes a search stack. Used at the beginning of a
638 // new search from the root.
639 void SearchStack::init(int ply) {
641 pv[ply] = pv[ply + 1] = MOVE_NONE;
642 currentMove = threatMove = MOVE_NONE;
643 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 // Print RootMoveList c'tor startup scoring to the standard output,
669 // so that we print information also for iteration 1.
670 std::cout << "info depth " << 1 << "\ninfo depth " << 1
671 << " score " << value_to_string(rml.get_move_score(0))
672 << " time " << current_search_time()
673 << " nodes " << nodes_searched()
675 << " pv " << rml.get_move(0) << "\n";
681 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
684 Move EasyMove = rml.scan_for_easy_move();
686 // Iterative deepening loop
687 while (Iteration < PLY_MAX)
689 // Initialize iteration
692 BestMoveChangesByIteration[Iteration] = 0;
696 std::cout << "info depth " << Iteration << std::endl;
698 // Calculate dynamic search window based on previous iterations
701 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
703 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
704 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
706 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
708 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
709 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
713 alpha = - VALUE_INFINITE;
714 beta = VALUE_INFINITE;
717 // Search to the current depth
718 Value value = root_search(p, ss, rml, alpha, beta);
720 // Write PV to transposition table, in case the relevant entries have
721 // been overwritten during the search.
722 TT.insert_pv(p, ss[0].pv);
725 break; // Value cannot be trusted. Break out immediately!
727 //Save info about search result
728 Value speculatedValue;
731 Value delta = value - IterationInfo[Iteration - 1].value;
738 speculatedValue = value + delta;
739 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
741 else if (value <= alpha)
743 assert(value == alpha);
747 speculatedValue = value + delta;
748 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
750 speculatedValue = value;
752 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
753 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
755 // Erase the easy move if it differs from the new best move
756 if (ss[0].pv[0] != EasyMove)
757 EasyMove = MOVE_NONE;
764 bool stopSearch = false;
766 // Stop search early if there is only a single legal move
767 if (Iteration >= 6 && rml.move_count() == 1)
770 // Stop search early when the last two iterations returned a mate score
772 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
773 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
776 // Stop search early if one move seems to be much better than the rest
777 int64_t nodes = nodes_searched();
781 && EasyMove == ss[0].pv[0]
782 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
783 && current_search_time() > MaxSearchTime / 16)
784 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
785 && current_search_time() > MaxSearchTime / 32)))
788 // Add some extra time if the best move has changed during the last two iterations
789 if (Iteration > 5 && Iteration <= 50)
790 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
791 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
793 // Stop search if most of MaxSearchTime is consumed at the end of the
794 // iteration. We probably don't have enough time to search the first
795 // move at the next iteration anyway.
796 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
801 //FIXME: Implement fail-low emergency measures
805 StopOnPonderhit = true;
809 if (MaxDepth && Iteration >= MaxDepth)
815 // If we are pondering, we shouldn't print the best move before we
818 wait_for_stop_or_ponderhit();
820 // Print final search statistics
821 std::cout << "info nodes " << nodes_searched()
823 << " time " << current_search_time()
824 << " hashfull " << TT.full() << std::endl;
826 // Print the best move and the ponder move to the standard output
827 if (ss[0].pv[0] == MOVE_NONE)
829 ss[0].pv[0] = rml.get_move(0);
830 ss[0].pv[1] = MOVE_NONE;
832 std::cout << "bestmove " << ss[0].pv[0];
833 if (ss[0].pv[1] != MOVE_NONE)
834 std::cout << " ponder " << ss[0].pv[1];
836 std::cout << std::endl;
841 dbg_print_mean(LogFile);
843 if (dbg_show_hit_rate)
844 dbg_print_hit_rate(LogFile);
847 LogFile << "Nodes: " << nodes_searched() << std::endl
848 << "Nodes/second: " << nps() << std::endl
849 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
851 p.do_move(ss[0].pv[0], st);
852 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
853 << std::endl << std::endl;
855 return rml.get_move_score(0);
859 // root_search() is the function which searches the root node. It is
860 // similar to search_pv except that it uses a different move ordering
861 // scheme (perhaps we should try to use this at internal PV nodes, too?)
862 // and prints some information to the standard output.
864 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
866 Value oldAlpha = alpha;
870 // Loop through all the moves in the root move list
871 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
875 // We failed high, invalidate and skip next moves, leave node-counters
876 // and beta-counters as they are and quickly return, we will try to do
877 // a research at the next iteration with a bigger aspiration window.
878 rml.set_move_score(i, -VALUE_INFINITE);
886 RootMoveNumber = i + 1;
889 // Remember the node count before the move is searched. The node counts
890 // are used to sort the root moves at the next iteration.
891 nodes = nodes_searched();
893 // Reset beta cut-off counters
896 // Pick the next root move, and print the move and the move number to
897 // the standard output.
898 move = ss[0].currentMove = rml.get_move(i);
899 if (current_search_time() >= 1000)
900 std::cout << "info currmove " << move
901 << " currmovenumber " << i + 1 << std::endl;
903 // Decide search depth for this move
904 bool moveIsCheck = pos.move_is_check(move);
905 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
907 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
908 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
910 // Make the move, and search it
911 pos.do_move(move, st, ci, moveIsCheck);
915 // Aspiration window is disabled in multi-pv case
917 alpha = -VALUE_INFINITE;
919 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
920 // If the value has dropped a lot compared to the last iteration,
921 // set the boolean variable Problem to true. This variable is used
922 // for time managment: When Problem is true, we try to complete the
923 // current iteration before playing a move.
924 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
926 if (Problem && StopOnPonderhit)
927 StopOnPonderhit = false;
931 if ( newDepth >= 3*OnePly
932 && i >= MultiPV + LMRPVMoves
934 && !captureOrPromotion
935 && !move_is_castle(move))
937 ss[0].reduction = OnePly;
938 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
940 value = alpha + 1; // Just to trigger next condition
944 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
947 // Fail high! Set the boolean variable FailHigh to true, and
948 // re-search the move with a big window. The variable FailHigh is
949 // used for time managment: We try to avoid aborting the search
950 // prematurely during a fail high research.
952 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
959 // Finished searching the move. If AbortSearch is true, the search
960 // was aborted because the user interrupted the search or because we
961 // ran out of time. In this case, the return value of the search cannot
962 // be trusted, and we break out of the loop without updating the best
967 // Remember the node count for this move. The node counts are used to
968 // sort the root moves at the next iteration.
969 rml.set_move_nodes(i, nodes_searched() - nodes);
971 // Remember the beta-cutoff statistics
973 BetaCounter.read(pos.side_to_move(), our, their);
974 rml.set_beta_counters(i, our, their);
976 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
978 if (value <= alpha && i >= MultiPV)
979 rml.set_move_score(i, -VALUE_INFINITE);
982 // PV move or new best move!
985 rml.set_move_score(i, value);
987 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
988 rml.set_move_pv(i, ss[0].pv);
992 // We record how often the best move has been changed in each
993 // iteration. This information is used for time managment: When
994 // the best move changes frequently, we allocate some more time.
996 BestMoveChangesByIteration[Iteration]++;
998 // Print search information to the standard output
999 std::cout << "info depth " << Iteration
1000 << " score " << value_to_string(value)
1001 << ((value >= beta)?
1002 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
1003 << " time " << current_search_time()
1004 << " nodes " << nodes_searched()
1008 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
1009 std::cout << ss[0].pv[j] << " ";
1011 std::cout << std::endl;
1014 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
1015 ((value >= beta)? VALUE_TYPE_LOWER
1016 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
1023 // Reset the global variable Problem to false if the value isn't too
1024 // far below the final value from the last iteration.
1025 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
1030 rml.sort_multipv(i);
1031 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1034 std::cout << "info multipv " << j + 1
1035 << " score " << value_to_string(rml.get_move_score(j))
1036 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1037 << " time " << current_search_time()
1038 << " nodes " << nodes_searched()
1042 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1043 std::cout << rml.get_move_pv(j, k) << " ";
1045 std::cout << std::endl;
1047 alpha = rml.get_move_score(Min(i, MultiPV-1));
1049 } // New best move case
1051 assert(alpha >= oldAlpha);
1053 FailLow = (alpha == oldAlpha);
1059 // search_pv() is the main search function for PV nodes.
1061 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1062 Depth depth, int ply, int threadID) {
1064 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1065 assert(beta > alpha && beta <= VALUE_INFINITE);
1066 assert(ply >= 0 && ply < PLY_MAX);
1067 assert(threadID >= 0 && threadID < ActiveThreads);
1069 Move movesSearched[256];
1074 Depth ext, newDepth;
1075 Value oldAlpha, value;
1076 bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1078 Value bestValue = -VALUE_INFINITE;
1081 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1083 // Initialize, and make an early exit in case of an aborted search,
1084 // an instant draw, maximum ply reached, etc.
1085 init_node(ss, ply, threadID);
1087 // After init_node() that calls poll()
1088 if (AbortSearch || thread_should_stop(threadID))
1094 if (ply >= PLY_MAX - 1)
1095 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1097 // Mate distance pruning
1099 alpha = Max(value_mated_in(ply), alpha);
1100 beta = Min(value_mate_in(ply+1), beta);
1104 // Transposition table lookup. At PV nodes, we don't use the TT for
1105 // pruning, but only for move ordering.
1106 tte = TT.retrieve(pos.get_key());
1107 ttMove = (tte ? tte->move() : MOVE_NONE);
1109 // Go with internal iterative deepening if we don't have a TT move
1110 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1112 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1113 ttMove = ss[ply].pv[ply];
1116 // Initialize a MovePicker object for the current position, and prepare
1117 // to search all moves
1118 isCheck = pos.is_check();
1119 mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
1121 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1123 // Loop through all legal moves until no moves remain or a beta cutoff
1125 while ( alpha < beta
1126 && (move = mp.get_next_move()) != MOVE_NONE
1127 && !thread_should_stop(threadID))
1129 assert(move_is_ok(move));
1131 singleReply = (isCheck && mp.number_of_evasions() == 1);
1132 moveIsCheck = pos.move_is_check(move, ci);
1133 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1135 movesSearched[moveCount++] = ss[ply].currentMove = move;
1137 // Decide the new search depth
1138 ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1139 newDepth = depth - OnePly + ext;
1141 // Make and search the move
1142 pos.do_move(move, st, ci, moveIsCheck);
1144 if (moveCount == 1) // The first move in list is the PV
1145 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1148 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1149 // if the move fails high will be re-searched at full depth.
1150 if ( depth >= 3*OnePly
1151 && moveCount >= LMRPVMoves
1153 && !captureOrPromotion
1154 && !move_is_castle(move)
1155 && !move_is_killer(move, ss[ply]))
1157 ss[ply].reduction = OnePly;
1158 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1161 value = alpha + 1; // Just to trigger next condition
1163 if (value > alpha) // Go with full depth non-pv search
1165 ss[ply].reduction = Depth(0);
1166 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1167 if (value > alpha && value < beta)
1169 // When the search fails high at ply 1 while searching the first
1170 // move at the root, set the flag failHighPly1. This is used for
1171 // time managment: We don't want to stop the search early in
1172 // such cases, because resolving the fail high at ply 1 could
1173 // result in a big drop in score at the root.
1174 if (ply == 1 && RootMoveNumber == 1)
1175 Threads[threadID].failHighPly1 = true;
1177 // A fail high occurred. Re-search at full window (pv search)
1178 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1179 Threads[threadID].failHighPly1 = false;
1183 pos.undo_move(move);
1185 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1188 if (value > bestValue)
1195 if (value == value_mate_in(ply + 1))
1196 ss[ply].mateKiller = move;
1198 // If we are at ply 1, and we are searching the first root move at
1199 // ply 0, set the 'Problem' variable if the score has dropped a lot
1200 // (from the computer's point of view) since the previous iteration.
1203 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1208 if ( ActiveThreads > 1
1210 && depth >= MinimumSplitDepth
1212 && idle_thread_exists(threadID)
1214 && !thread_should_stop(threadID)
1215 && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE,
1216 depth, &moveCount, &mp, threadID, true))
1220 // All legal moves have been searched. A special case: If there were
1221 // no legal moves, it must be mate or stalemate.
1223 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1225 // If the search is not aborted, update the transposition table,
1226 // history counters, and killer moves.
1227 if (AbortSearch || thread_should_stop(threadID))
1230 if (bestValue <= oldAlpha)
1231 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1233 else if (bestValue >= beta)
1235 BetaCounter.add(pos.side_to_move(), depth, threadID);
1236 move = ss[ply].pv[ply];
1237 if (!pos.move_is_capture_or_promotion(move))
1239 update_history(pos, move, depth, movesSearched, moveCount);
1240 update_killers(move, ss[ply]);
1242 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1245 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1251 // search() is the search function for zero-width nodes.
1253 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1254 int ply, bool allowNullmove, int threadID, Move forbiddenMove) {
1256 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1257 assert(ply >= 0 && ply < PLY_MAX);
1258 assert(threadID >= 0 && threadID < ActiveThreads);
1260 Move movesSearched[256];
1265 Depth ext, newDepth;
1266 Value approximateEval, nullValue, value, futilityValue, futilityValueScaled;
1267 bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous;
1268 bool mateThreat = false;
1270 Value bestValue = -VALUE_INFINITE;
1273 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1275 // Initialize, and make an early exit in case of an aborted search,
1276 // an instant draw, maximum ply reached, etc.
1277 init_node(ss, ply, threadID);
1279 // After init_node() that calls poll()
1280 if (AbortSearch || thread_should_stop(threadID))
1286 if (ply >= PLY_MAX - 1)
1287 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1289 // Mate distance pruning
1290 if (value_mated_in(ply) >= beta)
1293 if (value_mate_in(ply + 1) < beta)
1296 // Position key calculation
1297 Key posKey = pos.get_key();
1299 if (forbiddenMove != MOVE_NONE)
1300 posKey ^= Position::zobExclusion;
1302 // Transposition table lookup
1303 tte = TT.retrieve(posKey);
1304 ttMove = (tte ? tte->move() : MOVE_NONE);
1306 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1308 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1309 return value_from_tt(tte->value(), ply);
1312 approximateEval = quick_evaluate(pos);
1313 isCheck = pos.is_check();
1319 && !value_is_mate(beta)
1320 && ok_to_do_nullmove(pos)
1321 && approximateEval >= beta - NullMoveMargin)
1323 ss[ply].currentMove = MOVE_NULL;
1325 pos.do_null_move(st);
1327 // Null move dynamic reduction based on depth
1328 int R = (depth >= 5 * OnePly ? 4 : 3);
1330 // Null move dynamic reduction based on value
1331 if (approximateEval - beta > PawnValueMidgame)
1334 nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1336 pos.undo_null_move();
1338 if (nullValue >= beta)
1340 if (depth < 6 * OnePly)
1343 // Do zugzwang verification search
1344 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1348 // The null move failed low, which means that we may be faced with
1349 // some kind of threat. If the previous move was reduced, check if
1350 // the move that refuted the null move was somehow connected to the
1351 // move which was reduced. If a connection is found, return a fail
1352 // low score (which will cause the reduced move to fail high in the
1353 // parent node, which will trigger a re-search with full depth).
1354 if (nullValue == value_mated_in(ply + 2))
1357 ss[ply].threatMove = ss[ply + 1].currentMove;
1358 if ( depth < ThreatDepth
1359 && ss[ply - 1].reduction
1360 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1364 // Null move search not allowed, try razoring
1365 else if ( !value_is_mate(beta)
1366 && depth < RazorDepth
1367 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1368 && ss[ply - 1].currentMove != MOVE_NULL
1369 && ttMove == MOVE_NONE
1370 && !pos.has_pawn_on_7th(pos.side_to_move()))
1372 Value rbeta = beta - RazorMargins[int(depth) - 2];
1373 Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID);
1378 // Go with internal iterative deepening if we don't have a TT move
1379 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1380 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1382 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1383 ttMove = ss[ply].pv[ply];
1386 // Initialize a MovePicker object for the current position, and prepare
1387 // to search all moves.
1388 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1390 futilityValue = VALUE_NONE;
1391 useFutilityPruning = depth < SelectiveDepth && !isCheck;
1393 // Avoid calling evaluate() if we already have the score in TT
1394 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1395 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1397 // Move count pruning limit
1398 const int MCLimit = 3 + (1 << (3*int(depth)/8));
1400 // Loop through all legal moves until no moves remain or a beta cutoff
1402 while ( bestValue < beta
1403 && (move = mp.get_next_move()) != MOVE_NONE
1404 && !thread_should_stop(threadID))
1406 assert(move_is_ok(move));
1408 if (move == forbiddenMove)
1411 singleReply = (isCheck && mp.number_of_evasions() == 1);
1412 moveIsCheck = pos.move_is_check(move, ci);
1413 captureOrPromotion = pos.move_is_capture_or_promotion(move);
1415 movesSearched[moveCount++] = ss[ply].currentMove = move;
1417 // Decide the new search depth
1418 ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous);
1419 newDepth = depth - OnePly + ext;
1422 if ( useFutilityPruning
1424 && !captureOrPromotion
1427 //std::cout << std::endl;
1428 //for (int d = 2; d < 14; d++)
1429 // std::cout << d << ", " << 64*(1+bitScanReverse32(d*d)) << std::endl;
1431 //std::cout << std::endl;
1433 64*(1+bitScanReverse32(d*d))
1448 300 + 2*(1 << (3*d/4))
1464 3 + (1 << (3*int(depth)/8))
1466 1 * onePly - > moveCount >= 4
1467 2 * onePly - > moveCount >= 5
1468 3 * onePly - > moveCount >= 7
1469 4 * onePly - > moveCount >= 11
1470 5 * onePly - > moveCount >= 11
1471 6 * onePly - > moveCount >= 19
1472 7 * onePly - > moveCount >= 35
1474 // History pruning. See ok_to_prune() definition
1475 if ( moveCount >= MCLimit
1476 && ok_to_prune(pos, move, ss[ply].threatMove, depth)
1477 && bestValue > value_mated_in(PLY_MAX))
1480 // Value based pruning
1481 if (approximateEval < beta)
1483 if (futilityValue == VALUE_NONE)
1484 futilityValue = evaluate(pos, ei, threadID)
1485 + 64*(2+bitScanReverse32(int(depth) * int(depth)));
1487 futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin;
1489 if (futilityValueScaled < beta)
1491 if (futilityValueScaled > bestValue)
1492 bestValue = futilityValueScaled;
1498 // Make and search the move
1499 pos.do_move(move, st, ci, moveIsCheck);
1501 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1502 // if the move fails high will be re-searched at full depth.
1503 if ( depth >= 3*OnePly
1504 && moveCount >= LMRNonPVMoves
1506 && !captureOrPromotion
1507 && !move_is_castle(move)
1508 && !move_is_killer(move, ss[ply]))
1510 ss[ply].reduction = OnePly;
1511 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1514 value = beta; // Just to trigger next condition
1516 if (value >= beta) // Go with full depth non-pv search
1518 ss[ply].reduction = Depth(0);
1519 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1521 pos.undo_move(move);
1523 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1526 if (value > bestValue)
1532 if (value == value_mate_in(ply + 1))
1533 ss[ply].mateKiller = move;
1537 if ( ActiveThreads > 1
1539 && depth >= MinimumSplitDepth
1541 && idle_thread_exists(threadID)
1543 && !thread_should_stop(threadID)
1544 && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval,
1545 depth, &moveCount, &mp, threadID, false))
1549 // All legal moves have been searched. A special case: If there were
1550 // no legal moves, it must be mate or stalemate.
1552 return (forbiddenMove == MOVE_NONE ? (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW) : beta - 1);
1554 // If the search is not aborted, update the transposition table,
1555 // history counters, and killer moves.
1556 if (AbortSearch || thread_should_stop(threadID))
1559 if (bestValue < beta)
1560 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1563 BetaCounter.add(pos.side_to_move(), depth, threadID);
1564 move = ss[ply].pv[ply];
1565 if (!pos.move_is_capture_or_promotion(move))
1567 update_history(pos, move, depth, movesSearched, moveCount);
1568 update_killers(move, ss[ply]);
1570 TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move);
1573 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1579 // qsearch() is the quiescence search function, which is called by the main
1580 // search function when the remaining depth is zero (or, to be more precise,
1581 // less than OnePly).
1583 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1584 Depth depth, int ply, int threadID) {
1586 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1587 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1589 assert(ply >= 0 && ply < PLY_MAX);
1590 assert(threadID >= 0 && threadID < ActiveThreads);
1595 Value staticValue, bestValue, value, futilityValue;
1596 bool isCheck, enoughMaterial, moveIsCheck;
1597 const TTEntry* tte = NULL;
1599 bool pvNode = (beta - alpha != 1);
1601 // Initialize, and make an early exit in case of an aborted search,
1602 // an instant draw, maximum ply reached, etc.
1603 init_node(ss, ply, threadID);
1605 // After init_node() that calls poll()
1606 if (AbortSearch || thread_should_stop(threadID))
1612 // Transposition table lookup, only when not in PV
1615 tte = TT.retrieve(pos.get_key());
1616 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1618 assert(tte->type() != VALUE_TYPE_EVAL);
1620 return value_from_tt(tte->value(), ply);
1623 ttMove = (tte ? tte->move() : MOVE_NONE);
1625 // Evaluate the position statically
1626 isCheck = pos.is_check();
1627 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1630 staticValue = -VALUE_INFINITE;
1632 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1634 // Use the cached evaluation score if possible
1635 assert(ei.futilityMargin == Value(0));
1637 staticValue = tte->value();
1640 staticValue = evaluate(pos, ei, threadID);
1642 if (ply >= PLY_MAX - 1)
1643 return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID);
1645 // Initialize "stand pat score", and return it immediately if it is
1647 bestValue = staticValue;
1649 if (bestValue >= beta)
1651 // Store the score to avoid a future costly evaluation() call
1652 if (!isCheck && !tte && ei.futilityMargin == 0)
1653 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1658 if (bestValue > alpha)
1661 // Initialize a MovePicker object for the current position, and prepare
1662 // to search the moves. Because the depth is <= 0 here, only captures,
1663 // queen promotions and checks (only if depth == 0) will be generated.
1664 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1666 enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1668 // Loop through the moves until no moves remain or a beta cutoff
1670 while ( alpha < beta
1671 && (move = mp.get_next_move()) != MOVE_NONE)
1673 assert(move_is_ok(move));
1676 ss[ply].currentMove = move;
1678 moveIsCheck = pos.move_is_check(move, ci);
1686 && !move_is_promotion(move)
1687 && !pos.move_is_passed_pawn_push(move))
1689 futilityValue = staticValue
1690 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1691 pos.endgame_value_of_piece_on(move_to(move)))
1692 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1694 + ei.futilityMargin;
1696 if (futilityValue < alpha)
1698 if (futilityValue > bestValue)
1699 bestValue = futilityValue;
1704 // Don't search captures and checks with negative SEE values
1707 && !move_is_promotion(move)
1708 && pos.see_sign(move) < 0)
1711 // Make and search the move
1712 pos.do_move(move, st, ci, moveIsCheck);
1713 value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1714 pos.undo_move(move);
1716 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1719 if (value > bestValue)
1730 // All legal moves have been searched. A special case: If we're in check
1731 // and no legal moves were found, it is checkmate.
1732 if (!moveCount && pos.is_check()) // Mate!
1733 return value_mated_in(ply);
1735 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1737 // Update transposition table
1738 move = ss[ply].pv[ply];
1741 // If bestValue isn't changed it means it is still the static evaluation of
1742 // the node, so keep this info to avoid a future costly evaluation() call.
1743 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1744 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1746 if (bestValue < beta)
1747 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1749 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move);
1752 // Update killers only for good check moves
1753 if (alpha >= beta && !pos.move_is_capture_or_promotion(move))
1754 update_killers(move, ss[ply]);
1760 // sp_search() is used to search from a split point. This function is called
1761 // by each thread working at the split point. It is similar to the normal
1762 // search() function, but simpler. Because we have already probed the hash
1763 // table, done a null move search, and searched the first move before
1764 // splitting, we don't have to repeat all this work in sp_search(). We
1765 // also don't need to store anything to the hash table here: This is taken
1766 // care of after we return from the split point.
1768 void sp_search(SplitPoint* sp, int threadID) {
1770 assert(threadID >= 0 && threadID < ActiveThreads);
1771 assert(ActiveThreads > 1);
1773 Position pos = Position(sp->pos);
1775 SearchStack* ss = sp->sstack[threadID];
1778 bool isCheck = pos.is_check();
1779 bool useFutilityPruning = sp->depth < SelectiveDepth
1782 while ( sp->bestValue < sp->beta
1783 && !thread_should_stop(threadID)
1784 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1786 assert(move_is_ok(move));
1788 bool moveIsCheck = pos.move_is_check(move, ci);
1789 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1791 lock_grab(&(sp->lock));
1792 int moveCount = ++sp->moves;
1793 lock_release(&(sp->lock));
1795 ss[sp->ply].currentMove = move;
1797 // Decide the new search depth.
1799 Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1800 Depth newDepth = sp->depth - OnePly + ext;
1803 if ( useFutilityPruning
1805 && !captureOrPromotion)
1807 // History pruning. See ok_to_prune() definition
1808 if ( moveCount >= 2 + int(sp->depth)
1809 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)
1810 && sp->bestValue > value_mated_in(PLY_MAX))
1813 // Value based pruning
1814 if (sp->approximateEval < sp->beta)
1816 if (sp->futilityValue == VALUE_NONE)
1819 sp->futilityValue = evaluate(pos, ei, threadID)
1820 + FutilityMargins[int(sp->depth) - 2];
1823 if (sp->futilityValue < sp->beta)
1825 if (sp->futilityValue > sp->bestValue) // Less then 1% of cases
1827 lock_grab(&(sp->lock));
1828 if (sp->futilityValue > sp->bestValue)
1829 sp->bestValue = sp->futilityValue;
1830 lock_release(&(sp->lock));
1837 // Make and search the move.
1839 pos.do_move(move, st, ci, moveIsCheck);
1841 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1842 // if the move fails high will be re-searched at full depth.
1844 && moveCount >= LMRNonPVMoves
1845 && !captureOrPromotion
1846 && !move_is_castle(move)
1847 && !move_is_killer(move, ss[sp->ply]))
1849 ss[sp->ply].reduction = OnePly;
1850 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1853 value = sp->beta; // Just to trigger next condition
1855 if (value >= sp->beta) // Go with full depth non-pv search
1857 ss[sp->ply].reduction = Depth(0);
1858 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1860 pos.undo_move(move);
1862 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1864 if (thread_should_stop(threadID))
1868 if (value > sp->bestValue) // Less then 2% of cases
1870 lock_grab(&(sp->lock));
1871 if (value > sp->bestValue && !thread_should_stop(threadID))
1873 sp->bestValue = value;
1874 if (sp->bestValue >= sp->beta)
1876 sp_update_pv(sp->parentSstack, ss, sp->ply);
1877 for (int i = 0; i < ActiveThreads; i++)
1878 if (i != threadID && (i == sp->master || sp->slaves[i]))
1879 Threads[i].stop = true;
1881 sp->finished = true;
1884 lock_release(&(sp->lock));
1888 lock_grab(&(sp->lock));
1890 // If this is the master thread and we have been asked to stop because of
1891 // a beta cutoff higher up in the tree, stop all slave threads.
1892 if (sp->master == threadID && thread_should_stop(threadID))
1893 for (int i = 0; i < ActiveThreads; i++)
1895 Threads[i].stop = true;
1898 sp->slaves[threadID] = 0;
1900 lock_release(&(sp->lock));
1904 // sp_search_pv() is used to search from a PV split point. This function
1905 // is called by each thread working at the split point. It is similar to
1906 // the normal search_pv() function, but simpler. Because we have already
1907 // probed the hash table and searched the first move before splitting, we
1908 // don't have to repeat all this work in sp_search_pv(). We also don't
1909 // need to store anything to the hash table here: This is taken care of
1910 // after we return from the split point.
1912 void sp_search_pv(SplitPoint* sp, int threadID) {
1914 assert(threadID >= 0 && threadID < ActiveThreads);
1915 assert(ActiveThreads > 1);
1917 Position pos = Position(sp->pos);
1919 SearchStack* ss = sp->sstack[threadID];
1923 while ( sp->alpha < sp->beta
1924 && !thread_should_stop(threadID)
1925 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1927 bool moveIsCheck = pos.move_is_check(move, ci);
1928 bool captureOrPromotion = pos.move_is_capture_or_promotion(move);
1930 assert(move_is_ok(move));
1932 lock_grab(&(sp->lock));
1933 int moveCount = ++sp->moves;
1934 lock_release(&(sp->lock));
1936 ss[sp->ply].currentMove = move;
1938 // Decide the new search depth.
1940 Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous);
1941 Depth newDepth = sp->depth - OnePly + ext;
1943 // Make and search the move.
1945 pos.do_move(move, st, ci, moveIsCheck);
1947 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1948 // if the move fails high will be re-searched at full depth.
1950 && moveCount >= LMRPVMoves
1951 && !captureOrPromotion
1952 && !move_is_castle(move)
1953 && !move_is_killer(move, ss[sp->ply]))
1955 ss[sp->ply].reduction = OnePly;
1956 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1959 value = sp->alpha + 1; // Just to trigger next condition
1961 if (value > sp->alpha) // Go with full depth non-pv search
1963 ss[sp->ply].reduction = Depth(0);
1964 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1966 if (value > sp->alpha && value < sp->beta)
1968 // When the search fails high at ply 1 while searching the first
1969 // move at the root, set the flag failHighPly1. This is used for
1970 // time managment: We don't want to stop the search early in
1971 // such cases, because resolving the fail high at ply 1 could
1972 // result in a big drop in score at the root.
1973 if (sp->ply == 1 && RootMoveNumber == 1)
1974 Threads[threadID].failHighPly1 = true;
1976 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1977 Threads[threadID].failHighPly1 = false;
1980 pos.undo_move(move);
1982 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1984 if (thread_should_stop(threadID))
1988 lock_grab(&(sp->lock));
1989 if (value > sp->bestValue && !thread_should_stop(threadID))
1991 sp->bestValue = value;
1992 if (value > sp->alpha)
1995 sp_update_pv(sp->parentSstack, ss, sp->ply);
1996 if (value == value_mate_in(sp->ply + 1))
1997 ss[sp->ply].mateKiller = move;
1999 if (value >= sp->beta)
2001 for (int i = 0; i < ActiveThreads; i++)
2002 if (i != threadID && (i == sp->master || sp->slaves[i]))
2003 Threads[i].stop = true;
2005 sp->finished = true;
2008 // If we are at ply 1, and we are searching the first root move at
2009 // ply 0, set the 'Problem' variable if the score has dropped a lot
2010 // (from the computer's point of view) since the previous iteration.
2013 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
2016 lock_release(&(sp->lock));
2019 lock_grab(&(sp->lock));
2021 // If this is the master thread and we have been asked to stop because of
2022 // a beta cutoff higher up in the tree, stop all slave threads.
2023 if (sp->master == threadID && thread_should_stop(threadID))
2024 for (int i = 0; i < ActiveThreads; i++)
2026 Threads[i].stop = true;
2029 sp->slaves[threadID] = 0;
2031 lock_release(&(sp->lock));
2034 /// The BetaCounterType class
2036 BetaCounterType::BetaCounterType() { clear(); }
2038 void BetaCounterType::clear() {
2040 for (int i = 0; i < THREAD_MAX; i++)
2041 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
2044 void BetaCounterType::add(Color us, Depth d, int threadID) {
2046 // Weighted count based on depth
2047 Threads[threadID].betaCutOffs[us] += unsigned(d);
2050 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
2053 for (int i = 0; i < THREAD_MAX; i++)
2055 our += Threads[i].betaCutOffs[us];
2056 their += Threads[i].betaCutOffs[opposite_color(us)];
2061 /// The RootMove class
2065 RootMove::RootMove() {
2066 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
2069 // RootMove::operator<() is the comparison function used when
2070 // sorting the moves. A move m1 is considered to be better
2071 // than a move m2 if it has a higher score, or if the moves
2072 // have equal score but m1 has the higher node count.
2074 bool RootMove::operator<(const RootMove& m) {
2076 if (score != m.score)
2077 return (score < m.score);
2079 return theirBeta <= m.theirBeta;
2082 /// The RootMoveList class
2086 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
2088 MoveStack mlist[MaxRootMoves];
2089 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
2091 // Generate all legal moves
2092 MoveStack* last = generate_moves(pos, mlist);
2094 // Add each move to the moves[] array
2095 for (MoveStack* cur = mlist; cur != last; cur++)
2097 bool includeMove = includeAllMoves;
2099 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
2100 includeMove = (searchMoves[k] == cur->move);
2105 // Find a quick score for the move
2107 SearchStack ss[PLY_MAX_PLUS_2];
2110 moves[count].move = cur->move;
2111 pos.do_move(moves[count].move, st);
2112 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
2113 pos.undo_move(moves[count].move);
2114 moves[count].pv[0] = moves[count].move;
2115 moves[count].pv[1] = MOVE_NONE; // FIXME
2122 // Simple accessor methods for the RootMoveList class
2124 inline Move RootMoveList::get_move(int moveNum) const {
2125 return moves[moveNum].move;
2128 inline Value RootMoveList::get_move_score(int moveNum) const {
2129 return moves[moveNum].score;
2132 inline void RootMoveList::set_move_score(int moveNum, Value score) {
2133 moves[moveNum].score = score;
2136 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2137 moves[moveNum].nodes = nodes;
2138 moves[moveNum].cumulativeNodes += nodes;
2141 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2142 moves[moveNum].ourBeta = our;
2143 moves[moveNum].theirBeta = their;
2146 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2148 for(j = 0; pv[j] != MOVE_NONE; j++)
2149 moves[moveNum].pv[j] = pv[j];
2150 moves[moveNum].pv[j] = MOVE_NONE;
2153 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2154 return moves[moveNum].pv[i];
2157 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2158 return moves[moveNum].cumulativeNodes;
2161 inline int RootMoveList::move_count() const {
2166 // RootMoveList::scan_for_easy_move() is called at the end of the first
2167 // iteration, and is used to detect an "easy move", i.e. a move which appears
2168 // to be much bester than all the rest. If an easy move is found, the move
2169 // is returned, otherwise the function returns MOVE_NONE. It is very
2170 // important that this function is called at the right moment: The code
2171 // assumes that the first iteration has been completed and the moves have
2172 // been sorted. This is done in RootMoveList c'tor.
2174 Move RootMoveList::scan_for_easy_move() const {
2181 // moves are sorted so just consider the best and the second one
2182 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2188 // RootMoveList::sort() sorts the root move list at the beginning of a new
2191 inline void RootMoveList::sort() {
2193 sort_multipv(count - 1); // all items
2197 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2198 // list by their scores and depths. It is used to order the different PVs
2199 // correctly in MultiPV mode.
2201 void RootMoveList::sort_multipv(int n) {
2203 for (int i = 1; i <= n; i++)
2205 RootMove rm = moves[i];
2207 for (j = i; j > 0 && moves[j-1] < rm; j--)
2208 moves[j] = moves[j-1];
2214 // init_node() is called at the beginning of all the search functions
2215 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2216 // stack object corresponding to the current node. Once every
2217 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2218 // for user input and checks whether it is time to stop the search.
2220 void init_node(SearchStack ss[], int ply, int threadID) {
2222 assert(ply >= 0 && ply < PLY_MAX);
2223 assert(threadID >= 0 && threadID < ActiveThreads);
2225 Threads[threadID].nodes++;
2230 if (NodesSincePoll >= NodesBetweenPolls)
2237 ss[ply+2].initKillers();
2239 if (Threads[threadID].printCurrentLine)
2240 print_current_line(ss, ply, threadID);
2244 // update_pv() is called whenever a search returns a value > alpha. It
2245 // updates the PV in the SearchStack object corresponding to the current
2248 void update_pv(SearchStack ss[], int ply) {
2249 assert(ply >= 0 && ply < PLY_MAX);
2251 ss[ply].pv[ply] = ss[ply].currentMove;
2253 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2254 ss[ply].pv[p] = ss[ply+1].pv[p];
2255 ss[ply].pv[p] = MOVE_NONE;
2259 // sp_update_pv() is a variant of update_pv for use at split points. The
2260 // difference between the two functions is that sp_update_pv also updates
2261 // the PV at the parent node.
2263 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2264 assert(ply >= 0 && ply < PLY_MAX);
2266 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2268 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2269 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2270 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2274 // connected_moves() tests whether two moves are 'connected' in the sense
2275 // that the first move somehow made the second move possible (for instance
2276 // if the moving piece is the same in both moves). The first move is
2277 // assumed to be the move that was made to reach the current position, while
2278 // the second move is assumed to be a move from the current position.
2280 bool connected_moves(const Position& pos, Move m1, Move m2) {
2282 Square f1, t1, f2, t2;
2285 assert(move_is_ok(m1));
2286 assert(move_is_ok(m2));
2288 if (m2 == MOVE_NONE)
2291 // Case 1: The moving piece is the same in both moves
2297 // Case 2: The destination square for m2 was vacated by m1
2303 // Case 3: Moving through the vacated square
2304 if ( piece_is_slider(pos.piece_on(f2))
2305 && bit_is_set(squares_between(f2, t2), f1))
2308 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2309 p = pos.piece_on(t1);
2310 if (bit_is_set(pos.attacks_from(p, t1), t2))
2313 // Case 5: Discovered check, checking piece is the piece moved in m1
2314 if ( piece_is_slider(p)
2315 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2316 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2318 Bitboard occ = pos.occupied_squares();
2319 Color us = pos.side_to_move();
2320 Square ksq = pos.king_square(us);
2321 clear_bit(&occ, f2);
2322 if (type_of_piece(p) == BISHOP)
2324 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2327 else if (type_of_piece(p) == ROOK)
2329 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2334 assert(type_of_piece(p) == QUEEN);
2335 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
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 check, bool singleReply, bool mateThreat, bool* dangerous) {
2379 assert(m != MOVE_NONE);
2381 Depth result = Depth(0);
2382 *dangerous = check | singleReply | mateThreat;
2387 result += CheckExtension[pvNode];
2390 result += SingleReplyExtension[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. It's
2440 // 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, Depth d) {
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));
2460 assert(d >= OnePly);
2462 Square mfrom, mto, tfrom, tto;
2464 mfrom = move_from(m);
2466 tfrom = move_from(threat);
2467 tto = move_to(threat);
2469 // Case 1: Castling moves are never pruned
2470 if (move_is_castle(m))
2473 // Case 2: Don't prune moves which move the threatened piece
2474 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2477 // Case 3: If the threatened piece has value less than or equal to the
2478 // value of the threatening piece, don't prune move which defend it.
2479 if ( !PruneDefendingMoves
2480 && threat != MOVE_NONE
2481 && pos.move_is_capture(threat)
2482 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2483 || pos.type_of_piece_on(tfrom) == KING)
2484 && pos.move_attacks_square(m, tto))
2487 // Case 4: Don't prune moves with good history
2488 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2491 // Case 5: If the moving piece in the threatened move is a slider, don't
2492 // prune safe moves which block its ray.
2493 if ( !PruneBlockingMoves
2494 && threat != MOVE_NONE
2495 && piece_is_slider(pos.piece_on(tfrom))
2496 && bit_is_set(squares_between(tfrom, tto), mto)
2497 && pos.see_sign(m) >= 0)
2504 // ok_to_use_TT() returns true if a transposition table score
2505 // can be used at a given point in search.
2507 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2509 Value v = value_from_tt(tte->value(), ply);
2511 return ( tte->depth() >= depth
2512 || v >= Max(value_mate_in(100), beta)
2513 || v < Min(value_mated_in(100), beta))
2515 && ( (is_lower_bound(tte->type()) && v >= beta)
2516 || (is_upper_bound(tte->type()) && v < beta));
2520 // update_history() registers a good move that produced a beta-cutoff
2521 // in history and marks as failures all the other moves of that ply.
2523 void update_history(const Position& pos, Move m, Depth depth,
2524 Move movesSearched[], int moveCount) {
2526 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2528 for (int i = 0; i < moveCount - 1; i++)
2530 assert(m != movesSearched[i]);
2531 if (!pos.move_is_capture_or_promotion(movesSearched[i]))
2532 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2537 // update_killers() add a good move that produced a beta-cutoff
2538 // among the killer moves of that ply.
2540 void update_killers(Move m, SearchStack& ss) {
2542 if (m == ss.killers[0])
2545 for (int i = KILLER_MAX - 1; i > 0; i--)
2546 ss.killers[i] = ss.killers[i - 1];
2552 // fail_high_ply_1() checks if some thread is currently resolving a fail
2553 // high at ply 1 at the node below the first root node. This information
2554 // is used for time managment.
2556 bool fail_high_ply_1() {
2558 for(int i = 0; i < ActiveThreads; i++)
2559 if (Threads[i].failHighPly1)
2566 // current_search_time() returns the number of milliseconds which have passed
2567 // since the beginning of the current search.
2569 int current_search_time() {
2570 return get_system_time() - SearchStartTime;
2574 // nps() computes the current nodes/second count.
2577 int t = current_search_time();
2578 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2582 // poll() performs two different functions: It polls for user input, and it
2583 // looks at the time consumed so far and decides if it's time to abort the
2588 static int lastInfoTime;
2589 int t = current_search_time();
2594 // We are line oriented, don't read single chars
2595 std::string command;
2596 if (!std::getline(std::cin, command))
2599 if (command == "quit")
2602 PonderSearch = false;
2606 else if (command == "stop")
2609 PonderSearch = false;
2611 else if (command == "ponderhit")
2614 // Print search information
2618 else if (lastInfoTime > t)
2619 // HACK: Must be a new search where we searched less than
2620 // NodesBetweenPolls nodes during the first second of search.
2623 else if (t - lastInfoTime >= 1000)
2630 if (dbg_show_hit_rate)
2631 dbg_print_hit_rate();
2633 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2634 << " time " << t << " hashfull " << TT.full() << std::endl;
2635 lock_release(&IOLock);
2636 if (ShowCurrentLine)
2637 Threads[0].printCurrentLine = true;
2639 // Should we stop the search?
2643 bool overTime = t > AbsoluteMaxSearchTime
2644 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2645 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2646 && t > 6*(MaxSearchTime + ExtraSearchTime));
2648 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2649 || (ExactMaxTime && t >= ExactMaxTime)
2650 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2655 // ponderhit() is called when the program is pondering (i.e. thinking while
2656 // it's the opponent's turn to move) in order to let the engine know that
2657 // it correctly predicted the opponent's move.
2661 int t = current_search_time();
2662 PonderSearch = false;
2663 if (Iteration >= 3 &&
2664 (!InfiniteSearch && (StopOnPonderhit ||
2665 t > AbsoluteMaxSearchTime ||
2666 (RootMoveNumber == 1 &&
2667 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2668 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2669 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2674 // print_current_line() prints the current line of search for a given
2675 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2677 void print_current_line(SearchStack ss[], int ply, int threadID) {
2679 assert(ply >= 0 && ply < PLY_MAX);
2680 assert(threadID >= 0 && threadID < ActiveThreads);
2682 if (!Threads[threadID].idle)
2685 std::cout << "info currline " << (threadID + 1);
2686 for (int p = 0; p < ply; p++)
2687 std::cout << " " << ss[p].currentMove;
2689 std::cout << std::endl;
2690 lock_release(&IOLock);
2692 Threads[threadID].printCurrentLine = false;
2693 if (threadID + 1 < ActiveThreads)
2694 Threads[threadID + 1].printCurrentLine = true;
2698 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2700 void init_ss_array(SearchStack ss[]) {
2702 for (int i = 0; i < 3; i++)
2705 ss[i].initKillers();
2710 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2711 // while the program is pondering. The point is to work around a wrinkle in
2712 // the UCI protocol: When pondering, the engine is not allowed to give a
2713 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2714 // We simply wait here until one of these commands is sent, and return,
2715 // after which the bestmove and pondermove will be printed (in id_loop()).
2717 void wait_for_stop_or_ponderhit() {
2719 std::string command;
2723 if (!std::getline(std::cin, command))
2726 if (command == "quit")
2731 else if (command == "ponderhit" || command == "stop")
2737 // idle_loop() is where the threads are parked when they have no work to do.
2738 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2739 // object for which the current thread is the master.
2741 void idle_loop(int threadID, SplitPoint* waitSp) {
2742 assert(threadID >= 0 && threadID < THREAD_MAX);
2744 Threads[threadID].running = true;
2747 if(AllThreadsShouldExit && threadID != 0)
2750 // If we are not thinking, wait for a condition to be signaled instead
2751 // of wasting CPU time polling for work:
2752 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2753 #if !defined(_MSC_VER)
2754 pthread_mutex_lock(&WaitLock);
2755 if(Idle || threadID >= ActiveThreads)
2756 pthread_cond_wait(&WaitCond, &WaitLock);
2757 pthread_mutex_unlock(&WaitLock);
2759 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2763 // If this thread has been assigned work, launch a search
2764 if(Threads[threadID].workIsWaiting) {
2765 Threads[threadID].workIsWaiting = false;
2766 if(Threads[threadID].splitPoint->pvNode)
2767 sp_search_pv(Threads[threadID].splitPoint, threadID);
2769 sp_search(Threads[threadID].splitPoint, threadID);
2770 Threads[threadID].idle = true;
2773 // If this thread is the master of a split point and all threads have
2774 // finished their work at this split point, return from the idle loop.
2775 if(waitSp != NULL && waitSp->cpus == 0)
2779 Threads[threadID].running = false;
2783 // init_split_point_stack() is called during program initialization, and
2784 // initializes all split point objects.
2786 void init_split_point_stack() {
2787 for(int i = 0; i < THREAD_MAX; i++)
2788 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2789 SplitPointStack[i][j].parent = NULL;
2790 lock_init(&(SplitPointStack[i][j].lock), NULL);
2795 // destroy_split_point_stack() is called when the program exits, and
2796 // destroys all locks in the precomputed split point objects.
2798 void destroy_split_point_stack() {
2799 for(int i = 0; i < THREAD_MAX; i++)
2800 for(int j = 0; j < MaxActiveSplitPoints; j++)
2801 lock_destroy(&(SplitPointStack[i][j].lock));
2805 // thread_should_stop() checks whether the thread with a given threadID has
2806 // been asked to stop, directly or indirectly. This can happen if a beta
2807 // cutoff has occured in thre thread's currently active split point, or in
2808 // some ancestor of the current split point.
2810 bool thread_should_stop(int threadID) {
2811 assert(threadID >= 0 && threadID < ActiveThreads);
2815 if(Threads[threadID].stop)
2817 if(ActiveThreads <= 2)
2819 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2821 Threads[threadID].stop = true;
2828 // thread_is_available() checks whether the thread with threadID "slave" is
2829 // available to help the thread with threadID "master" at a split point. An
2830 // obvious requirement is that "slave" must be idle. With more than two
2831 // threads, this is not by itself sufficient: If "slave" is the master of
2832 // some active split point, it is only available as a slave to the other
2833 // threads which are busy searching the split point at the top of "slave"'s
2834 // split point stack (the "helpful master concept" in YBWC terminology).
2836 bool thread_is_available(int slave, int master) {
2837 assert(slave >= 0 && slave < ActiveThreads);
2838 assert(master >= 0 && master < ActiveThreads);
2839 assert(ActiveThreads > 1);
2841 if(!Threads[slave].idle || slave == master)
2844 if(Threads[slave].activeSplitPoints == 0)
2845 // No active split points means that the thread is available as a slave
2846 // for any other thread.
2849 if(ActiveThreads == 2)
2852 // Apply the "helpful master" concept if possible.
2853 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2860 // idle_thread_exists() tries to find an idle thread which is available as
2861 // a slave for the thread with threadID "master".
2863 bool idle_thread_exists(int master) {
2864 assert(master >= 0 && master < ActiveThreads);
2865 assert(ActiveThreads > 1);
2867 for(int i = 0; i < ActiveThreads; i++)
2868 if(thread_is_available(i, master))
2874 // split() does the actual work of distributing the work at a node between
2875 // several threads at PV nodes. If it does not succeed in splitting the
2876 // node (because no idle threads are available, or because we have no unused
2877 // split point objects), the function immediately returns false. If
2878 // splitting is possible, a SplitPoint object is initialized with all the
2879 // data that must be copied to the helper threads (the current position and
2880 // search stack, alpha, beta, the search depth, etc.), and we tell our
2881 // helper threads that they have been assigned work. This will cause them
2882 // to instantly leave their idle loops and call sp_search_pv(). When all
2883 // threads have returned from sp_search_pv (or, equivalently, when
2884 // splitPoint->cpus becomes 0), split() returns true.
2886 bool split(const Position& p, SearchStack* sstck, int ply,
2887 Value* alpha, Value* beta, Value* bestValue, const Value futilityValue,
2888 const Value approximateEval, Depth depth, int* moves,
2889 MovePicker* mp, int master, bool pvNode) {
2892 assert(sstck != NULL);
2893 assert(ply >= 0 && ply < PLY_MAX);
2894 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2895 assert(!pvNode || *alpha < *beta);
2896 assert(*beta <= VALUE_INFINITE);
2897 assert(depth > Depth(0));
2898 assert(master >= 0 && master < ActiveThreads);
2899 assert(ActiveThreads > 1);
2901 SplitPoint* splitPoint;
2906 // If no other thread is available to help us, or if we have too many
2907 // active split points, don't split.
2908 if(!idle_thread_exists(master) ||
2909 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2910 lock_release(&MPLock);
2914 // Pick the next available split point object from the split point stack
2915 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2916 Threads[master].activeSplitPoints++;
2918 // Initialize the split point object
2919 splitPoint->parent = Threads[master].splitPoint;
2920 splitPoint->finished = false;
2921 splitPoint->ply = ply;
2922 splitPoint->depth = depth;
2923 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2924 splitPoint->beta = *beta;
2925 splitPoint->pvNode = pvNode;
2926 splitPoint->bestValue = *bestValue;
2927 splitPoint->futilityValue = futilityValue;
2928 splitPoint->approximateEval = approximateEval;
2929 splitPoint->master = master;
2930 splitPoint->mp = mp;
2931 splitPoint->moves = *moves;
2932 splitPoint->cpus = 1;
2933 splitPoint->pos.copy(p);
2934 splitPoint->parentSstack = sstck;
2935 for(i = 0; i < ActiveThreads; i++)
2936 splitPoint->slaves[i] = 0;
2938 // Copy the current position and the search stack to the master thread
2939 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2940 Threads[master].splitPoint = splitPoint;
2942 // Make copies of the current position and search stack for each thread
2943 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2945 if(thread_is_available(i, master)) {
2946 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2947 Threads[i].splitPoint = splitPoint;
2948 splitPoint->slaves[i] = 1;
2952 // Tell the threads that they have work to do. This will make them leave
2954 for(i = 0; i < ActiveThreads; i++)
2955 if(i == master || splitPoint->slaves[i]) {
2956 Threads[i].workIsWaiting = true;
2957 Threads[i].idle = false;
2958 Threads[i].stop = false;
2961 lock_release(&MPLock);
2963 // Everything is set up. The master thread enters the idle loop, from
2964 // which it will instantly launch a search, because its workIsWaiting
2965 // slot is 'true'. We send the split point as a second parameter to the
2966 // idle loop, which means that the main thread will return from the idle
2967 // loop when all threads have finished their work at this split point
2968 // (i.e. when // splitPoint->cpus == 0).
2969 idle_loop(master, splitPoint);
2971 // We have returned from the idle loop, which means that all threads are
2972 // finished. Update alpha, beta and bestvalue, and return.
2974 if(pvNode) *alpha = splitPoint->alpha;
2975 *beta = splitPoint->beta;
2976 *bestValue = splitPoint->bestValue;
2977 Threads[master].stop = false;
2978 Threads[master].idle = false;
2979 Threads[master].activeSplitPoints--;
2980 Threads[master].splitPoint = splitPoint->parent;
2981 lock_release(&MPLock);
2987 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2988 // to start a new search from the root.
2990 void wake_sleeping_threads() {
2991 if(ActiveThreads > 1) {
2992 for(int i = 1; i < ActiveThreads; i++) {
2993 Threads[i].idle = true;
2994 Threads[i].workIsWaiting = false;
2996 #if !defined(_MSC_VER)
2997 pthread_mutex_lock(&WaitLock);
2998 pthread_cond_broadcast(&WaitCond);
2999 pthread_mutex_unlock(&WaitLock);
3001 for(int i = 1; i < THREAD_MAX; i++)
3002 SetEvent(SitIdleEvent[i]);
3008 // init_thread() is the function which is called when a new thread is
3009 // launched. It simply calls the idle_loop() function with the supplied
3010 // threadID. There are two versions of this function; one for POSIX threads
3011 // and one for Windows threads.
3013 #if !defined(_MSC_VER)
3015 void *init_thread(void *threadID) {
3016 idle_loop(*(int *)threadID, NULL);
3022 DWORD WINAPI init_thread(LPVOID threadID) {
3023 idle_loop(*(int *)threadID, NULL);