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 bool ok_to_history(const Position& pos, Move m);
292 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
293 void update_killers(Move m, SearchStack& ss);
295 bool fail_high_ply_1();
296 int current_search_time();
300 void print_current_line(SearchStack ss[], int ply, int threadID);
301 void wait_for_stop_or_ponderhit();
302 void init_ss_array(SearchStack ss[]);
304 void idle_loop(int threadID, SplitPoint* waitSp);
305 void init_split_point_stack();
306 void destroy_split_point_stack();
307 bool thread_should_stop(int threadID);
308 bool thread_is_available(int slave, int master);
309 bool idle_thread_exists(int master);
310 bool split(const Position& pos, SearchStack* ss, int ply,
311 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
312 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
313 void wake_sleeping_threads();
315 #if !defined(_MSC_VER)
316 void *init_thread(void *threadID);
318 DWORD WINAPI init_thread(LPVOID threadID);
328 /// think() is the external interface to Stockfish's search, and is called when
329 /// the program receives the UCI 'go' command. It initializes various
330 /// search-related global variables, and calls root_search(). It returns false
331 /// when a quit command is received during the search.
333 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
334 int time[], int increment[], int movesToGo, int maxDepth,
335 int maxNodes, int maxTime, Move searchMoves[]) {
337 // Look for a book move
338 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
341 if (get_option_value_string("Book File") != OpeningBook.file_name())
342 OpeningBook.open("book.bin");
344 bookMove = OpeningBook.get_move(pos);
345 if (bookMove != MOVE_NONE)
347 std::cout << "bestmove " << bookMove << std::endl;
352 // Initialize global search variables
354 SearchStartTime = get_system_time();
355 for (int i = 0; i < THREAD_MAX; i++)
357 Threads[i].nodes = 0ULL;
358 Threads[i].failHighPly1 = false;
361 InfiniteSearch = infinite;
362 PonderSearch = ponder;
363 StopOnPonderhit = false;
369 ExactMaxTime = maxTime;
371 // Read UCI option values
372 TT.set_size(get_option_value_int("Hash"));
373 if (button_was_pressed("Clear Hash"))
376 loseOnTime = false; // reset at the beginning of a new game
379 bool PonderingEnabled = get_option_value_bool("Ponder");
380 MultiPV = get_option_value_int("MultiPV");
382 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
383 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
385 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
386 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
388 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
389 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
391 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
392 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
394 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
395 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
397 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
398 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
400 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
401 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
402 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
404 Chess960 = get_option_value_bool("UCI_Chess960");
405 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
406 UseLogFile = get_option_value_bool("Use Search Log");
408 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
410 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
411 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
413 read_weights(pos.side_to_move());
415 // Set the number of active threads
416 int newActiveThreads = get_option_value_int("Threads");
417 if (newActiveThreads != ActiveThreads)
419 ActiveThreads = newActiveThreads;
420 init_eval(ActiveThreads);
423 // Wake up sleeping threads
424 wake_sleeping_threads();
426 for (int i = 1; i < ActiveThreads; i++)
427 assert(thread_is_available(i, 0));
430 int myTime = time[side_to_move];
431 int myIncrement = increment[side_to_move];
433 if (!movesToGo) // Sudden death time control
437 MaxSearchTime = myTime / 30 + myIncrement;
438 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
439 } else { // Blitz game without increment
440 MaxSearchTime = myTime / 30;
441 AbsoluteMaxSearchTime = myTime / 8;
444 else // (x moves) / (y minutes)
448 MaxSearchTime = myTime / 2;
449 AbsoluteMaxSearchTime =
450 (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4);
452 MaxSearchTime = myTime / Min(movesToGo, 20);
453 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
457 if (PonderingEnabled)
459 MaxSearchTime += MaxSearchTime / 4;
460 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
463 // Fixed depth or fixed number of nodes?
466 InfiniteSearch = true; // HACK
471 NodesBetweenPolls = Min(MaxNodes, 30000);
472 InfiniteSearch = true; // HACK
474 else if (InfiniteSearch)
475 NodesBetweenPolls = 30000;
476 else if (myTime < 1000)
477 NodesBetweenPolls = 1000;
478 else if (myTime < 5000)
479 NodesBetweenPolls = 5000;
481 NodesBetweenPolls = 30000;
483 // Write information to search log file
485 LogFile << "Searching: " << pos.to_fen() << std::endl
486 << "infinite: " << infinite
487 << " ponder: " << ponder
488 << " time: " << myTime
489 << " increment: " << myIncrement
490 << " moves to go: " << movesToGo << std::endl;
493 // We're ready to start thinking. Call the iterative deepening loop function
495 // FIXME we really need to cleanup all this LSN ugliness
498 Value v = id_loop(pos, searchMoves);
499 loseOnTime = ( UseLSNFiltering
506 loseOnTime = false; // reset for next match
507 while (SearchStartTime + myTime + 1000 > get_system_time())
509 id_loop(pos, searchMoves); // to fail gracefully
520 /// init_threads() is called during startup. It launches all helper threads,
521 /// and initializes the split point stack and the global locks and condition
524 void init_threads() {
528 #if !defined(_MSC_VER)
529 pthread_t pthread[1];
532 for (i = 0; i < THREAD_MAX; i++)
533 Threads[i].activeSplitPoints = 0;
535 // Initialize global locks
536 lock_init(&MPLock, NULL);
537 lock_init(&IOLock, NULL);
539 init_split_point_stack();
541 #if !defined(_MSC_VER)
542 pthread_mutex_init(&WaitLock, NULL);
543 pthread_cond_init(&WaitCond, NULL);
545 for (i = 0; i < THREAD_MAX; i++)
546 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
549 // All threads except the main thread should be initialized to idle state
550 for (i = 1; i < THREAD_MAX; i++)
552 Threads[i].stop = false;
553 Threads[i].workIsWaiting = false;
554 Threads[i].idle = true;
555 Threads[i].running = false;
558 // Launch the helper threads
559 for(i = 1; i < THREAD_MAX; i++)
561 #if !defined(_MSC_VER)
562 pthread_create(pthread, NULL, init_thread, (void*)(&i));
565 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
568 // Wait until the thread has finished launching
569 while (!Threads[i].running);
574 /// stop_threads() is called when the program exits. It makes all the
575 /// helper threads exit cleanly.
577 void stop_threads() {
579 ActiveThreads = THREAD_MAX; // HACK
580 Idle = false; // HACK
581 wake_sleeping_threads();
582 AllThreadsShouldExit = true;
583 for (int i = 1; i < THREAD_MAX; i++)
585 Threads[i].stop = true;
586 while(Threads[i].running);
588 destroy_split_point_stack();
592 /// nodes_searched() returns the total number of nodes searched so far in
593 /// the current search.
595 int64_t nodes_searched() {
597 int64_t result = 0ULL;
598 for (int i = 0; i < ActiveThreads; i++)
599 result += Threads[i].nodes;
604 // SearchStack::init() initializes a search stack. Used at the beginning of a
605 // new search from the root.
606 void SearchStack::init(int ply) {
608 pv[ply] = pv[ply + 1] = MOVE_NONE;
609 currentMove = threatMove = MOVE_NONE;
610 reduction = Depth(0);
613 void SearchStack::initKillers() {
615 mateKiller = MOVE_NONE;
616 for (int i = 0; i < KILLER_MAX; i++)
617 killers[i] = MOVE_NONE;
622 // id_loop() is the main iterative deepening loop. It calls root_search
623 // repeatedly with increasing depth until the allocated thinking time has
624 // been consumed, the user stops the search, or the maximum search depth is
627 Value id_loop(const Position& pos, Move searchMoves[]) {
630 SearchStack ss[PLY_MAX_PLUS_2];
632 // searchMoves are verified, copied, scored and sorted
633 RootMoveList rml(p, searchMoves);
635 // Print RootMoveList c'tor startup scoring to the standard output,
636 // so that we print information also for iteration 1.
637 std::cout << "info depth " << 1 << "\ninfo depth " << 1
638 << " score " << value_to_string(rml.get_move_score(0))
639 << " time " << current_search_time()
640 << " nodes " << nodes_searched()
642 << " pv " << rml.get_move(0) << "\n";
648 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
651 Move EasyMove = rml.scan_for_easy_move();
653 // Iterative deepening loop
654 while (Iteration < PLY_MAX)
656 // Initialize iteration
659 BestMoveChangesByIteration[Iteration] = 0;
663 std::cout << "info depth " << Iteration << std::endl;
665 // Calculate dynamic search window based on previous iterations
668 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
670 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
671 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
673 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
675 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
676 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
680 alpha = - VALUE_INFINITE;
681 beta = VALUE_INFINITE;
684 // Search to the current depth
685 Value value = root_search(p, ss, rml, alpha, beta);
687 // Write PV to transposition table, in case the relevant entries have
688 // been overwritten during the search.
689 TT.insert_pv(p, ss[0].pv);
692 break; // Value cannot be trusted. Break out immediately!
694 //Save info about search result
695 Value speculatedValue;
698 Value delta = value - IterationInfo[Iteration - 1].value;
705 speculatedValue = value + delta;
706 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
708 else if (value <= alpha)
710 assert(value == alpha);
714 speculatedValue = value + delta;
715 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
717 speculatedValue = value;
719 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
720 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
722 // Erase the easy move if it differs from the new best move
723 if (ss[0].pv[0] != EasyMove)
724 EasyMove = MOVE_NONE;
731 bool stopSearch = false;
733 // Stop search early if there is only a single legal move
734 if (Iteration >= 6 && rml.move_count() == 1)
737 // Stop search early when the last two iterations returned a mate score
739 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
740 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
743 // Stop search early if one move seems to be much better than the rest
744 int64_t nodes = nodes_searched();
748 && EasyMove == ss[0].pv[0]
749 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
750 && current_search_time() > MaxSearchTime / 16)
751 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
752 && current_search_time() > MaxSearchTime / 32)))
755 // Add some extra time if the best move has changed during the last two iterations
756 if (Iteration > 5 && Iteration <= 50)
757 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
758 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
760 // Stop search if most of MaxSearchTime is consumed at the end of the
761 // iteration. We probably don't have enough time to search the first
762 // move at the next iteration anyway.
763 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
768 //FIXME: Implement fail-low emergency measures
772 StopOnPonderhit = true;
776 if (MaxDepth && Iteration >= MaxDepth)
782 // If we are pondering, we shouldn't print the best move before we
785 wait_for_stop_or_ponderhit();
787 // Print final search statistics
788 std::cout << "info nodes " << nodes_searched()
790 << " time " << current_search_time()
791 << " hashfull " << TT.full() << std::endl;
793 // Print the best move and the ponder move to the standard output
794 if (ss[0].pv[0] == MOVE_NONE)
796 ss[0].pv[0] = rml.get_move(0);
797 ss[0].pv[1] = MOVE_NONE;
799 std::cout << "bestmove " << ss[0].pv[0];
800 if (ss[0].pv[1] != MOVE_NONE)
801 std::cout << " ponder " << ss[0].pv[1];
803 std::cout << std::endl;
808 dbg_print_mean(LogFile);
810 if (dbg_show_hit_rate)
811 dbg_print_hit_rate(LogFile);
814 LogFile << "Nodes: " << nodes_searched() << std::endl
815 << "Nodes/second: " << nps() << std::endl
816 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
818 p.do_move(ss[0].pv[0], st);
819 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
820 << std::endl << std::endl;
822 return rml.get_move_score(0);
826 // root_search() is the function which searches the root node. It is
827 // similar to search_pv except that it uses a different move ordering
828 // scheme (perhaps we should try to use this at internal PV nodes, too?)
829 // and prints some information to the standard output.
831 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
833 Value oldAlpha = alpha;
835 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
837 // Loop through all the moves in the root move list
838 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
842 // We failed high, invalidate and skip next moves, leave node-counters
843 // and beta-counters as they are and quickly return, we will try to do
844 // a research at the next iteration with a bigger aspiration window.
845 rml.set_move_score(i, -VALUE_INFINITE);
853 RootMoveNumber = i + 1;
856 // Remember the node count before the move is searched. The node counts
857 // are used to sort the root moves at the next iteration.
858 nodes = nodes_searched();
860 // Reset beta cut-off counters
863 // Pick the next root move, and print the move and the move number to
864 // the standard output.
865 move = ss[0].currentMove = rml.get_move(i);
866 if (current_search_time() >= 1000)
867 std::cout << "info currmove " << move
868 << " currmovenumber " << i + 1 << std::endl;
870 // Decide search depth for this move
871 bool moveIsCapture = pos.move_is_capture(move);
873 ext = extension(pos, move, true, moveIsCapture, pos.move_is_check(move), false, false, &dangerous);
874 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
876 // Make the move, and search it
877 pos.do_move(move, st, dcCandidates);
881 // Aspiration window is disabled in multi-pv case
883 alpha = -VALUE_INFINITE;
885 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
886 // If the value has dropped a lot compared to the last iteration,
887 // set the boolean variable Problem to true. This variable is used
888 // for time managment: When Problem is true, we try to complete the
889 // current iteration before playing a move.
890 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
892 if (Problem && StopOnPonderhit)
893 StopOnPonderhit = false;
897 if ( newDepth >= 3*OnePly
898 && i >= MultiPV + LMRPVMoves
901 && !move_is_promotion(move)
902 && !move_is_castle(move))
904 ss[0].reduction = OnePly;
905 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
907 value = alpha + 1; // Just to trigger next condition
911 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
914 // Fail high! Set the boolean variable FailHigh to true, and
915 // re-search the move with a big window. The variable FailHigh is
916 // used for time managment: We try to avoid aborting the search
917 // prematurely during a fail high research.
919 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
926 // Finished searching the move. If AbortSearch is true, the search
927 // was aborted because the user interrupted the search or because we
928 // ran out of time. In this case, the return value of the search cannot
929 // be trusted, and we break out of the loop without updating the best
934 // Remember the node count for this move. The node counts are used to
935 // sort the root moves at the next iteration.
936 rml.set_move_nodes(i, nodes_searched() - nodes);
938 // Remember the beta-cutoff statistics
940 BetaCounter.read(pos.side_to_move(), our, their);
941 rml.set_beta_counters(i, our, their);
943 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
945 if (value <= alpha && i >= MultiPV)
946 rml.set_move_score(i, -VALUE_INFINITE);
949 // PV move or new best move!
952 rml.set_move_score(i, value);
954 TT.extract_pv(pos, ss[0].pv, PLY_MAX);
955 rml.set_move_pv(i, ss[0].pv);
959 // We record how often the best move has been changed in each
960 // iteration. This information is used for time managment: When
961 // the best move changes frequently, we allocate some more time.
963 BestMoveChangesByIteration[Iteration]++;
965 // Print search information to the standard output
966 std::cout << "info depth " << Iteration
967 << " score " << value_to_string(value)
969 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
970 << " time " << current_search_time()
971 << " nodes " << nodes_searched()
975 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
976 std::cout << ss[0].pv[j] << " ";
978 std::cout << std::endl;
981 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value,
982 ((value >= beta)? VALUE_TYPE_LOWER
983 : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)),
990 // Reset the global variable Problem to false if the value isn't too
991 // far below the final value from the last iteration.
992 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
998 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
1001 std::cout << "info multipv " << j + 1
1002 << " score " << value_to_string(rml.get_move_score(j))
1003 << " depth " << ((j <= i)? Iteration : Iteration - 1)
1004 << " time " << current_search_time()
1005 << " nodes " << nodes_searched()
1009 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1010 std::cout << rml.get_move_pv(j, k) << " ";
1012 std::cout << std::endl;
1014 alpha = rml.get_move_score(Min(i, MultiPV-1));
1016 } // New best move case
1018 assert(alpha >= oldAlpha);
1020 FailLow = (alpha == oldAlpha);
1026 // search_pv() is the main search function for PV nodes.
1028 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1029 Depth depth, int ply, int threadID) {
1031 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1032 assert(beta > alpha && beta <= VALUE_INFINITE);
1033 assert(ply >= 0 && ply < PLY_MAX);
1034 assert(threadID >= 0 && threadID < ActiveThreads);
1037 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1039 // Initialize, and make an early exit in case of an aborted search,
1040 // an instant draw, maximum ply reached, etc.
1041 init_node(ss, ply, threadID);
1043 // After init_node() that calls poll()
1044 if (AbortSearch || thread_should_stop(threadID))
1052 if (ply >= PLY_MAX - 1)
1053 return evaluate(pos, ei, threadID);
1055 // Mate distance pruning
1056 Value oldAlpha = alpha;
1057 alpha = Max(value_mated_in(ply), alpha);
1058 beta = Min(value_mate_in(ply+1), beta);
1062 // Transposition table lookup. At PV nodes, we don't use the TT for
1063 // pruning, but only for move ordering.
1064 const TTEntry* tte = TT.retrieve(pos.get_key());
1065 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1067 // Go with internal iterative deepening if we don't have a TT move
1068 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1070 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1071 ttMove = ss[ply].pv[ply];
1074 // Initialize a MovePicker object for the current position, and prepare
1075 // to search all moves
1076 Move move, movesSearched[256];
1078 Value value, bestValue = -VALUE_INFINITE;
1079 Color us = pos.side_to_move();
1080 bool isCheck = pos.is_check();
1081 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1083 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1084 Bitboard dcCandidates = mp.discovered_check_candidates();
1086 // Loop through all legal moves until no moves remain or a beta cutoff
1088 while ( alpha < beta
1089 && (move = mp.get_next_move()) != MOVE_NONE
1090 && !thread_should_stop(threadID))
1092 assert(move_is_ok(move));
1094 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1095 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1096 bool moveIsCapture = pos.move_is_capture(move);
1098 movesSearched[moveCount++] = ss[ply].currentMove = move;
1100 // Decide the new search depth
1102 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1103 Depth newDepth = depth - OnePly + ext;
1105 // Make and search the move
1107 pos.do_move(move, st, dcCandidates);
1109 if (moveCount == 1) // The first move in list is the PV
1110 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1113 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1114 // if the move fails high will be re-searched at full depth.
1115 if ( depth >= 3*OnePly
1116 && moveCount >= LMRPVMoves
1119 && !move_is_promotion(move)
1120 && !move_is_castle(move)
1121 && !move_is_killer(move, ss[ply]))
1123 ss[ply].reduction = OnePly;
1124 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1127 value = alpha + 1; // Just to trigger next condition
1129 if (value > alpha) // Go with full depth non-pv search
1131 ss[ply].reduction = Depth(0);
1132 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1133 if (value > alpha && value < beta)
1135 // When the search fails high at ply 1 while searching the first
1136 // move at the root, set the flag failHighPly1. This is used for
1137 // time managment: We don't want to stop the search early in
1138 // such cases, because resolving the fail high at ply 1 could
1139 // result in a big drop in score at the root.
1140 if (ply == 1 && RootMoveNumber == 1)
1141 Threads[threadID].failHighPly1 = true;
1143 // A fail high occurred. Re-search at full window (pv search)
1144 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1145 Threads[threadID].failHighPly1 = false;
1149 pos.undo_move(move);
1151 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1154 if (value > bestValue)
1161 if (value == value_mate_in(ply + 1))
1162 ss[ply].mateKiller = move;
1164 // If we are at ply 1, and we are searching the first root move at
1165 // ply 0, set the 'Problem' variable if the score has dropped a lot
1166 // (from the computer's point of view) since the previous iteration.
1169 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1174 if ( ActiveThreads > 1
1176 && depth >= MinimumSplitDepth
1178 && idle_thread_exists(threadID)
1180 && !thread_should_stop(threadID)
1181 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1182 &moveCount, &mp, dcCandidates, threadID, true))
1186 // All legal moves have been searched. A special case: If there were
1187 // no legal moves, it must be mate or stalemate.
1189 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1191 // If the search is not aborted, update the transposition table,
1192 // history counters, and killer moves.
1193 if (AbortSearch || thread_should_stop(threadID))
1196 if (bestValue <= oldAlpha)
1197 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1199 else if (bestValue >= beta)
1201 BetaCounter.add(pos.side_to_move(), depth, threadID);
1202 Move m = ss[ply].pv[ply];
1203 if (ok_to_history(pos, m)) // Only non capture moves are considered
1205 update_history(pos, m, depth, movesSearched, moveCount);
1206 update_killers(m, ss[ply]);
1208 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1211 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1217 // search() is the search function for zero-width nodes.
1219 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1220 int ply, bool allowNullmove, int threadID) {
1222 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1223 assert(ply >= 0 && ply < PLY_MAX);
1224 assert(threadID >= 0 && threadID < ActiveThreads);
1227 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1229 // Initialize, and make an early exit in case of an aborted search,
1230 // an instant draw, maximum ply reached, etc.
1231 init_node(ss, ply, threadID);
1233 // After init_node() that calls poll()
1234 if (AbortSearch || thread_should_stop(threadID))
1242 if (ply >= PLY_MAX - 1)
1243 return evaluate(pos, ei, threadID);
1245 // Mate distance pruning
1246 if (value_mated_in(ply) >= beta)
1249 if (value_mate_in(ply + 1) < beta)
1252 // Transposition table lookup
1253 const TTEntry* tte = TT.retrieve(pos.get_key());
1254 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1256 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1258 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1259 return value_from_tt(tte->value(), ply);
1262 Value approximateEval = quick_evaluate(pos);
1263 bool mateThreat = false;
1264 bool isCheck = pos.is_check();
1270 && !value_is_mate(beta)
1271 && ok_to_do_nullmove(pos)
1272 && approximateEval >= beta - NullMoveMargin)
1274 ss[ply].currentMove = MOVE_NULL;
1277 pos.do_null_move(st);
1278 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1280 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1282 pos.undo_null_move();
1284 if (nullValue >= beta)
1286 if (depth < 6 * OnePly)
1289 // Do zugzwang verification search
1290 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1294 // The null move failed low, which means that we may be faced with
1295 // some kind of threat. If the previous move was reduced, check if
1296 // the move that refuted the null move was somehow connected to the
1297 // move which was reduced. If a connection is found, return a fail
1298 // low score (which will cause the reduced move to fail high in the
1299 // parent node, which will trigger a re-search with full depth).
1300 if (nullValue == value_mated_in(ply + 2))
1303 ss[ply].threatMove = ss[ply + 1].currentMove;
1304 if ( depth < ThreatDepth
1305 && ss[ply - 1].reduction
1306 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1310 // Null move search not allowed, try razoring
1311 else if ( !value_is_mate(beta)
1312 && depth < RazorDepth
1313 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1314 && ss[ply - 1].currentMove != MOVE_NULL
1315 && ttMove == MOVE_NONE
1316 && !pos.has_pawn_on_7th(pos.side_to_move()))
1318 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1319 if (v < beta - RazorMargins[int(depth) - 2])
1323 // Go with internal iterative deepening if we don't have a TT move
1324 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1325 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1327 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1328 ttMove = ss[ply].pv[ply];
1331 // Initialize a MovePicker object for the current position, and prepare
1332 // to search all moves.
1333 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1335 Move move, movesSearched[256];
1337 Value value, bestValue = -VALUE_INFINITE;
1338 Bitboard dcCandidates = mp.discovered_check_candidates();
1339 Value futilityValue = VALUE_NONE;
1340 bool useFutilityPruning = depth < SelectiveDepth
1343 // Avoid calling evaluate() if we already have the score in TT
1344 if (tte && (tte->type() & VALUE_TYPE_EVAL))
1345 futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2];
1347 // Loop through all legal moves until no moves remain or a beta cutoff
1349 while ( bestValue < beta
1350 && (move = mp.get_next_move()) != MOVE_NONE
1351 && !thread_should_stop(threadID))
1353 assert(move_is_ok(move));
1355 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1356 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1357 bool moveIsCapture = pos.move_is_capture(move);
1359 movesSearched[moveCount++] = ss[ply].currentMove = move;
1361 // Decide the new search depth
1363 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1364 Depth newDepth = depth - OnePly + ext;
1367 if ( useFutilityPruning
1370 && !move_is_promotion(move))
1372 // History pruning. See ok_to_prune() definition
1373 if ( moveCount >= 2 + int(depth)
1374 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1377 // Value based pruning
1378 if (approximateEval < beta)
1380 if (futilityValue == VALUE_NONE)
1381 futilityValue = evaluate(pos, ei, threadID)
1382 + FutilityMargins[int(depth) - 2];
1384 if (futilityValue < beta)
1386 if (futilityValue > bestValue)
1387 bestValue = futilityValue;
1393 // Make and search the move
1395 pos.do_move(move, st, dcCandidates);
1397 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1398 // if the move fails high will be re-searched at full depth.
1399 if ( depth >= 3*OnePly
1400 && moveCount >= LMRNonPVMoves
1403 && !move_is_promotion(move)
1404 && !move_is_castle(move)
1405 && !move_is_killer(move, ss[ply]))
1407 ss[ply].reduction = OnePly;
1408 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1411 value = beta; // Just to trigger next condition
1413 if (value >= beta) // Go with full depth non-pv search
1415 ss[ply].reduction = Depth(0);
1416 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1418 pos.undo_move(move);
1420 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1423 if (value > bestValue)
1429 if (value == value_mate_in(ply + 1))
1430 ss[ply].mateKiller = move;
1434 if ( ActiveThreads > 1
1436 && depth >= MinimumSplitDepth
1438 && idle_thread_exists(threadID)
1440 && !thread_should_stop(threadID)
1441 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1442 &mp, dcCandidates, threadID, false))
1446 // All legal moves have been searched. A special case: If there were
1447 // no legal moves, it must be mate or stalemate.
1449 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1451 // If the search is not aborted, update the transposition table,
1452 // history counters, and killer moves.
1453 if (AbortSearch || thread_should_stop(threadID))
1456 if (bestValue < beta)
1457 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1460 BetaCounter.add(pos.side_to_move(), depth, threadID);
1461 Move m = ss[ply].pv[ply];
1462 if (ok_to_history(pos, m)) // Only non capture moves are considered
1464 update_history(pos, m, depth, movesSearched, moveCount);
1465 update_killers(m, ss[ply]);
1467 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1470 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1476 // qsearch() is the quiescence search function, which is called by the main
1477 // search function when the remaining depth is zero (or, to be more precise,
1478 // less than OnePly).
1480 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1481 Depth depth, int ply, int threadID) {
1483 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1484 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1486 assert(ply >= 0 && ply < PLY_MAX);
1487 assert(threadID >= 0 && threadID < ActiveThreads);
1489 // Initialize, and make an early exit in case of an aborted search,
1490 // an instant draw, maximum ply reached, etc.
1491 init_node(ss, ply, threadID);
1493 // After init_node() that calls poll()
1494 if (AbortSearch || thread_should_stop(threadID))
1500 // Transposition table lookup, only when not in PV
1501 TTEntry* tte = NULL;
1502 bool pvNode = (beta - alpha != 1);
1505 tte = TT.retrieve(pos.get_key());
1506 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1508 assert(tte->type() != VALUE_TYPE_EVAL);
1510 return value_from_tt(tte->value(), ply);
1513 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1515 // Evaluate the position statically
1518 bool isCheck = pos.is_check();
1519 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1522 staticValue = -VALUE_INFINITE;
1524 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1526 // Use the cached evaluation score if possible
1527 assert(ei.futilityMargin == Value(0));
1529 staticValue = tte->value();
1532 staticValue = evaluate(pos, ei, threadID);
1534 if (ply == PLY_MAX - 1)
1535 return evaluate(pos, ei, threadID);
1537 // Initialize "stand pat score", and return it immediately if it is
1539 Value bestValue = staticValue;
1541 if (bestValue >= beta)
1543 // Store the score to avoid a future costly evaluation() call
1544 if (!isCheck && !tte && ei.futilityMargin == 0)
1545 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1550 if (bestValue > alpha)
1553 // Initialize a MovePicker object for the current position, and prepare
1554 // to search the moves. Because the depth is <= 0 here, only captures,
1555 // queen promotions and checks (only if depth == 0) will be generated.
1556 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1559 Bitboard dcCandidates = mp.discovered_check_candidates();
1560 Color us = pos.side_to_move();
1561 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1563 // Loop through the moves until no moves remain or a beta cutoff
1565 while ( alpha < beta
1566 && (move = mp.get_next_move()) != MOVE_NONE)
1568 assert(move_is_ok(move));
1571 ss[ply].currentMove = move;
1577 && !move_is_promotion(move)
1578 && !pos.move_is_check(move, dcCandidates)
1579 && !pos.move_is_passed_pawn_push(move))
1581 Value futilityValue = staticValue
1582 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1583 pos.endgame_value_of_piece_on(move_to(move)))
1584 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1586 + ei.futilityMargin;
1588 if (futilityValue < alpha)
1590 if (futilityValue > bestValue)
1591 bestValue = futilityValue;
1596 // Don't search captures and checks with negative SEE values
1598 && !move_is_promotion(move)
1599 && pos.see_sign(move) < 0)
1602 // Make and search the move.
1604 pos.do_move(move, st, dcCandidates);
1605 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1606 pos.undo_move(move);
1608 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1611 if (value > bestValue)
1622 // All legal moves have been searched. A special case: If we're in check
1623 // and no legal moves were found, it is checkmate.
1624 if (pos.is_check() && moveCount == 0) // Mate!
1625 return value_mated_in(ply);
1627 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1629 // Update transposition table
1630 Move m = ss[ply].pv[ply];
1633 // If bestValue isn't changed it means it is still the static evaluation of
1634 // the node, so keep this info to avoid a future costly evaluation() call.
1635 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1636 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1638 if (bestValue < beta)
1639 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1641 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1644 // Update killers only for good check moves
1645 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1646 update_killers(m, ss[ply]);
1652 // sp_search() is used to search from a split point. This function is called
1653 // by each thread working at the split point. It is similar to the normal
1654 // search() function, but simpler. Because we have already probed the hash
1655 // table, done a null move search, and searched the first move before
1656 // splitting, we don't have to repeat all this work in sp_search(). We
1657 // also don't need to store anything to the hash table here: This is taken
1658 // care of after we return from the split point.
1660 void sp_search(SplitPoint* sp, int threadID) {
1662 assert(threadID >= 0 && threadID < ActiveThreads);
1663 assert(ActiveThreads > 1);
1665 Position pos = Position(sp->pos);
1666 SearchStack* ss = sp->sstack[threadID];
1669 bool isCheck = pos.is_check();
1670 bool useFutilityPruning = sp->depth < SelectiveDepth
1673 while ( sp->bestValue < sp->beta
1674 && !thread_should_stop(threadID)
1675 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1677 assert(move_is_ok(move));
1679 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1680 bool moveIsCapture = pos.move_is_capture(move);
1682 lock_grab(&(sp->lock));
1683 int moveCount = ++sp->moves;
1684 lock_release(&(sp->lock));
1686 ss[sp->ply].currentMove = move;
1688 // Decide the new search depth.
1690 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1691 Depth newDepth = sp->depth - OnePly + ext;
1694 if ( useFutilityPruning
1697 && !move_is_promotion(move)
1698 && moveCount >= 2 + int(sp->depth)
1699 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1702 // Make and search the move.
1704 pos.do_move(move, st, sp->dcCandidates);
1706 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1707 // if the move fails high will be re-searched at full depth.
1709 && moveCount >= LMRNonPVMoves
1711 && !move_is_promotion(move)
1712 && !move_is_castle(move)
1713 && !move_is_killer(move, ss[sp->ply]))
1715 ss[sp->ply].reduction = OnePly;
1716 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1719 value = sp->beta; // Just to trigger next condition
1721 if (value >= sp->beta) // Go with full depth non-pv search
1723 ss[sp->ply].reduction = Depth(0);
1724 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1726 pos.undo_move(move);
1728 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1730 if (thread_should_stop(threadID))
1734 lock_grab(&(sp->lock));
1735 if (value > sp->bestValue && !thread_should_stop(threadID))
1737 sp->bestValue = value;
1738 if (sp->bestValue >= sp->beta)
1740 sp_update_pv(sp->parentSstack, ss, sp->ply);
1741 for (int i = 0; i < ActiveThreads; i++)
1742 if (i != threadID && (i == sp->master || sp->slaves[i]))
1743 Threads[i].stop = true;
1745 sp->finished = true;
1748 lock_release(&(sp->lock));
1751 lock_grab(&(sp->lock));
1753 // If this is the master thread and we have been asked to stop because of
1754 // a beta cutoff higher up in the tree, stop all slave threads.
1755 if (sp->master == threadID && thread_should_stop(threadID))
1756 for (int i = 0; i < ActiveThreads; i++)
1758 Threads[i].stop = true;
1761 sp->slaves[threadID] = 0;
1763 lock_release(&(sp->lock));
1767 // sp_search_pv() is used to search from a PV split point. This function
1768 // is called by each thread working at the split point. It is similar to
1769 // the normal search_pv() function, but simpler. Because we have already
1770 // probed the hash table and searched the first move before splitting, we
1771 // don't have to repeat all this work in sp_search_pv(). We also don't
1772 // need to store anything to the hash table here: This is taken care of
1773 // after we return from the split point.
1775 void sp_search_pv(SplitPoint* sp, int threadID) {
1777 assert(threadID >= 0 && threadID < ActiveThreads);
1778 assert(ActiveThreads > 1);
1780 Position pos = Position(sp->pos);
1781 SearchStack* ss = sp->sstack[threadID];
1785 while ( sp->alpha < sp->beta
1786 && !thread_should_stop(threadID)
1787 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1789 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1790 bool moveIsCapture = pos.move_is_capture(move);
1792 assert(move_is_ok(move));
1794 lock_grab(&(sp->lock));
1795 int moveCount = ++sp->moves;
1796 lock_release(&(sp->lock));
1798 ss[sp->ply].currentMove = move;
1800 // Decide the new search depth.
1802 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1803 Depth newDepth = sp->depth - OnePly + ext;
1805 // Make and search the move.
1807 pos.do_move(move, st, sp->dcCandidates);
1809 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1810 // if the move fails high will be re-searched at full depth.
1812 && moveCount >= LMRPVMoves
1814 && !move_is_promotion(move)
1815 && !move_is_castle(move)
1816 && !move_is_killer(move, ss[sp->ply]))
1818 ss[sp->ply].reduction = OnePly;
1819 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1822 value = sp->alpha + 1; // Just to trigger next condition
1824 if (value > sp->alpha) // Go with full depth non-pv search
1826 ss[sp->ply].reduction = Depth(0);
1827 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1829 if (value > sp->alpha && value < sp->beta)
1831 // When the search fails high at ply 1 while searching the first
1832 // move at the root, set the flag failHighPly1. This is used for
1833 // time managment: We don't want to stop the search early in
1834 // such cases, because resolving the fail high at ply 1 could
1835 // result in a big drop in score at the root.
1836 if (sp->ply == 1 && RootMoveNumber == 1)
1837 Threads[threadID].failHighPly1 = true;
1839 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1840 Threads[threadID].failHighPly1 = false;
1843 pos.undo_move(move);
1845 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1847 if (thread_should_stop(threadID))
1851 lock_grab(&(sp->lock));
1852 if (value > sp->bestValue && !thread_should_stop(threadID))
1854 sp->bestValue = value;
1855 if (value > sp->alpha)
1858 sp_update_pv(sp->parentSstack, ss, sp->ply);
1859 if (value == value_mate_in(sp->ply + 1))
1860 ss[sp->ply].mateKiller = move;
1862 if (value >= sp->beta)
1864 for (int i = 0; i < ActiveThreads; i++)
1865 if (i != threadID && (i == sp->master || sp->slaves[i]))
1866 Threads[i].stop = true;
1868 sp->finished = true;
1871 // If we are at ply 1, and we are searching the first root move at
1872 // ply 0, set the 'Problem' variable if the score has dropped a lot
1873 // (from the computer's point of view) since the previous iteration.
1876 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1879 lock_release(&(sp->lock));
1882 lock_grab(&(sp->lock));
1884 // If this is the master thread and we have been asked to stop because of
1885 // a beta cutoff higher up in the tree, stop all slave threads.
1886 if (sp->master == threadID && thread_should_stop(threadID))
1887 for (int i = 0; i < ActiveThreads; i++)
1889 Threads[i].stop = true;
1892 sp->slaves[threadID] = 0;
1894 lock_release(&(sp->lock));
1897 /// The BetaCounterType class
1899 BetaCounterType::BetaCounterType() { clear(); }
1901 void BetaCounterType::clear() {
1903 for (int i = 0; i < THREAD_MAX; i++)
1904 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1907 void BetaCounterType::add(Color us, Depth d, int threadID) {
1909 // Weighted count based on depth
1910 Threads[threadID].betaCutOffs[us] += unsigned(d);
1913 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1916 for (int i = 0; i < THREAD_MAX; i++)
1918 our += Threads[i].betaCutOffs[us];
1919 their += Threads[i].betaCutOffs[opposite_color(us)];
1924 /// The RootMove class
1928 RootMove::RootMove() {
1929 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1932 // RootMove::operator<() is the comparison function used when
1933 // sorting the moves. A move m1 is considered to be better
1934 // than a move m2 if it has a higher score, or if the moves
1935 // have equal score but m1 has the higher node count.
1937 bool RootMove::operator<(const RootMove& m) {
1939 if (score != m.score)
1940 return (score < m.score);
1942 return theirBeta <= m.theirBeta;
1945 /// The RootMoveList class
1949 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1951 MoveStack mlist[MaxRootMoves];
1952 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1954 // Generate all legal moves
1955 MoveStack* last = generate_moves(pos, mlist);
1957 // Add each move to the moves[] array
1958 for (MoveStack* cur = mlist; cur != last; cur++)
1960 bool includeMove = includeAllMoves;
1962 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1963 includeMove = (searchMoves[k] == cur->move);
1968 // Find a quick score for the move
1970 SearchStack ss[PLY_MAX_PLUS_2];
1973 moves[count].move = cur->move;
1974 pos.do_move(moves[count].move, st);
1975 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1976 pos.undo_move(moves[count].move);
1977 moves[count].pv[0] = moves[count].move;
1978 moves[count].pv[1] = MOVE_NONE; // FIXME
1985 // Simple accessor methods for the RootMoveList class
1987 inline Move RootMoveList::get_move(int moveNum) const {
1988 return moves[moveNum].move;
1991 inline Value RootMoveList::get_move_score(int moveNum) const {
1992 return moves[moveNum].score;
1995 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1996 moves[moveNum].score = score;
1999 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
2000 moves[moveNum].nodes = nodes;
2001 moves[moveNum].cumulativeNodes += nodes;
2004 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
2005 moves[moveNum].ourBeta = our;
2006 moves[moveNum].theirBeta = their;
2009 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2011 for(j = 0; pv[j] != MOVE_NONE; j++)
2012 moves[moveNum].pv[j] = pv[j];
2013 moves[moveNum].pv[j] = MOVE_NONE;
2016 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2017 return moves[moveNum].pv[i];
2020 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2021 return moves[moveNum].cumulativeNodes;
2024 inline int RootMoveList::move_count() const {
2029 // RootMoveList::scan_for_easy_move() is called at the end of the first
2030 // iteration, and is used to detect an "easy move", i.e. a move which appears
2031 // to be much bester than all the rest. If an easy move is found, the move
2032 // is returned, otherwise the function returns MOVE_NONE. It is very
2033 // important that this function is called at the right moment: The code
2034 // assumes that the first iteration has been completed and the moves have
2035 // been sorted. This is done in RootMoveList c'tor.
2037 Move RootMoveList::scan_for_easy_move() const {
2044 // moves are sorted so just consider the best and the second one
2045 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2051 // RootMoveList::sort() sorts the root move list at the beginning of a new
2054 inline void RootMoveList::sort() {
2056 sort_multipv(count - 1); // all items
2060 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2061 // list by their scores and depths. It is used to order the different PVs
2062 // correctly in MultiPV mode.
2064 void RootMoveList::sort_multipv(int n) {
2066 for (int i = 1; i <= n; i++)
2068 RootMove rm = moves[i];
2070 for (j = i; j > 0 && moves[j-1] < rm; j--)
2071 moves[j] = moves[j-1];
2077 // init_node() is called at the beginning of all the search functions
2078 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2079 // stack object corresponding to the current node. Once every
2080 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2081 // for user input and checks whether it is time to stop the search.
2083 void init_node(SearchStack ss[], int ply, int threadID) {
2085 assert(ply >= 0 && ply < PLY_MAX);
2086 assert(threadID >= 0 && threadID < ActiveThreads);
2088 Threads[threadID].nodes++;
2093 if (NodesSincePoll >= NodesBetweenPolls)
2100 ss[ply+2].initKillers();
2102 if (Threads[threadID].printCurrentLine)
2103 print_current_line(ss, ply, threadID);
2107 // update_pv() is called whenever a search returns a value > alpha. It
2108 // updates the PV in the SearchStack object corresponding to the current
2111 void update_pv(SearchStack ss[], int ply) {
2112 assert(ply >= 0 && ply < PLY_MAX);
2114 ss[ply].pv[ply] = ss[ply].currentMove;
2116 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2117 ss[ply].pv[p] = ss[ply+1].pv[p];
2118 ss[ply].pv[p] = MOVE_NONE;
2122 // sp_update_pv() is a variant of update_pv for use at split points. The
2123 // difference between the two functions is that sp_update_pv also updates
2124 // the PV at the parent node.
2126 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2127 assert(ply >= 0 && ply < PLY_MAX);
2129 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2131 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2132 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2133 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2137 // connected_moves() tests whether two moves are 'connected' in the sense
2138 // that the first move somehow made the second move possible (for instance
2139 // if the moving piece is the same in both moves). The first move is
2140 // assumed to be the move that was made to reach the current position, while
2141 // the second move is assumed to be a move from the current position.
2143 bool connected_moves(const Position& pos, Move m1, Move m2) {
2145 Square f1, t1, f2, t2;
2148 assert(move_is_ok(m1));
2149 assert(move_is_ok(m2));
2151 if (m2 == MOVE_NONE)
2154 // Case 1: The moving piece is the same in both moves
2160 // Case 2: The destination square for m2 was vacated by m1
2166 // Case 3: Moving through the vacated square
2167 if ( piece_is_slider(pos.piece_on(f2))
2168 && bit_is_set(squares_between(f2, t2), f1))
2171 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2172 p = pos.piece_on(t1);
2173 if (bit_is_set(pos.attacks_from(p, t1), t2))
2176 // Case 5: Discovered check, checking piece is the piece moved in m1
2177 if ( piece_is_slider(p)
2178 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2179 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2181 Bitboard occ = pos.occupied_squares();
2182 Color us = pos.side_to_move();
2183 Square ksq = pos.king_square(us);
2184 clear_bit(&occ, f2);
2185 if (type_of_piece(p) == BISHOP)
2187 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2190 else if (type_of_piece(p) == ROOK)
2192 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2197 assert(type_of_piece(p) == QUEEN);
2198 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2206 // value_is_mate() checks if the given value is a mate one
2207 // eventually compensated for the ply.
2209 bool value_is_mate(Value value) {
2211 assert(abs(value) <= VALUE_INFINITE);
2213 return value <= value_mated_in(PLY_MAX)
2214 || value >= value_mate_in(PLY_MAX);
2218 // move_is_killer() checks if the given move is among the
2219 // killer moves of that ply.
2221 bool move_is_killer(Move m, const SearchStack& ss) {
2223 const Move* k = ss.killers;
2224 for (int i = 0; i < KILLER_MAX; i++, k++)
2232 // extension() decides whether a move should be searched with normal depth,
2233 // or with extended depth. Certain classes of moves (checking moves, in
2234 // particular) are searched with bigger depth than ordinary moves and in
2235 // any case are marked as 'dangerous'. Note that also if a move is not
2236 // extended, as example because the corresponding UCI option is set to zero,
2237 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2239 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2240 bool singleReply, bool mateThreat, bool* dangerous) {
2242 assert(m != MOVE_NONE);
2244 Depth result = Depth(0);
2245 *dangerous = check | singleReply | mateThreat;
2250 result += CheckExtension[pvNode];
2253 result += SingleReplyExtension[pvNode];
2256 result += MateThreatExtension[pvNode];
2259 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2261 Color c = pos.side_to_move();
2262 if (relative_rank(c, move_to(m)) == RANK_7)
2264 result += PawnPushTo7thExtension[pvNode];
2267 if (pos.pawn_is_passed(c, move_to(m)))
2269 result += PassedPawnExtension[pvNode];
2275 && pos.type_of_piece_on(move_to(m)) != PAWN
2276 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2277 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2278 && !move_is_promotion(m)
2281 result += PawnEndgameExtension[pvNode];
2287 && pos.type_of_piece_on(move_to(m)) != PAWN
2288 && pos.see_sign(m) >= 0)
2294 return Min(result, OnePly);
2298 // ok_to_do_nullmove() looks at the current position and decides whether
2299 // doing a 'null move' should be allowed. In order to avoid zugzwang
2300 // problems, null moves are not allowed when the side to move has very
2301 // little material left. Currently, the test is a bit too simple: Null
2302 // moves are avoided only when the side to move has only pawns left. It's
2303 // probably a good idea to avoid null moves in at least some more
2304 // complicated endgames, e.g. KQ vs KR. FIXME
2306 bool ok_to_do_nullmove(const Position& pos) {
2308 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2312 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2313 // non-tactical moves late in the move list close to the leaves are
2314 // candidates for pruning.
2316 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2318 assert(move_is_ok(m));
2319 assert(threat == MOVE_NONE || move_is_ok(threat));
2320 assert(!move_is_promotion(m));
2321 assert(!pos.move_is_check(m));
2322 assert(!pos.move_is_capture(m));
2323 assert(!pos.move_is_passed_pawn_push(m));
2324 assert(d >= OnePly);
2326 Square mfrom, mto, tfrom, tto;
2328 mfrom = move_from(m);
2330 tfrom = move_from(threat);
2331 tto = move_to(threat);
2333 // Case 1: Castling moves are never pruned
2334 if (move_is_castle(m))
2337 // Case 2: Don't prune moves which move the threatened piece
2338 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2341 // Case 3: If the threatened piece has value less than or equal to the
2342 // value of the threatening piece, don't prune move which defend it.
2343 if ( !PruneDefendingMoves
2344 && threat != MOVE_NONE
2345 && pos.move_is_capture(threat)
2346 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2347 || pos.type_of_piece_on(tfrom) == KING)
2348 && pos.move_attacks_square(m, tto))
2351 // Case 4: Don't prune moves with good history
2352 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2355 // Case 5: If the moving piece in the threatened move is a slider, don't
2356 // prune safe moves which block its ray.
2357 if ( !PruneBlockingMoves
2358 && threat != MOVE_NONE
2359 && piece_is_slider(pos.piece_on(tfrom))
2360 && bit_is_set(squares_between(tfrom, tto), mto)
2361 && pos.see_sign(m) >= 0)
2368 // ok_to_use_TT() returns true if a transposition table score
2369 // can be used at a given point in search.
2371 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2373 Value v = value_from_tt(tte->value(), ply);
2375 return ( tte->depth() >= depth
2376 || v >= Max(value_mate_in(100), beta)
2377 || v < Min(value_mated_in(100), beta))
2379 && ( (is_lower_bound(tte->type()) && v >= beta)
2380 || (is_upper_bound(tte->type()) && v < beta));
2384 // ok_to_history() returns true if a move m can be stored
2385 // in history. Should be a non capturing move nor a promotion.
2387 bool ok_to_history(const Position& pos, Move m) {
2389 return !pos.move_is_capture(m) && !move_is_promotion(m);
2393 // update_history() registers a good move that produced a beta-cutoff
2394 // in history and marks as failures all the other moves of that ply.
2396 void update_history(const Position& pos, Move m, Depth depth,
2397 Move movesSearched[], int moveCount) {
2399 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2401 for (int i = 0; i < moveCount - 1; i++)
2403 assert(m != movesSearched[i]);
2404 if (ok_to_history(pos, movesSearched[i]))
2405 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2410 // update_killers() add a good move that produced a beta-cutoff
2411 // among the killer moves of that ply.
2413 void update_killers(Move m, SearchStack& ss) {
2415 if (m == ss.killers[0])
2418 for (int i = KILLER_MAX - 1; i > 0; i--)
2419 ss.killers[i] = ss.killers[i - 1];
2425 // fail_high_ply_1() checks if some thread is currently resolving a fail
2426 // high at ply 1 at the node below the first root node. This information
2427 // is used for time managment.
2429 bool fail_high_ply_1() {
2431 for(int i = 0; i < ActiveThreads; i++)
2432 if (Threads[i].failHighPly1)
2439 // current_search_time() returns the number of milliseconds which have passed
2440 // since the beginning of the current search.
2442 int current_search_time() {
2443 return get_system_time() - SearchStartTime;
2447 // nps() computes the current nodes/second count.
2450 int t = current_search_time();
2451 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2455 // poll() performs two different functions: It polls for user input, and it
2456 // looks at the time consumed so far and decides if it's time to abort the
2461 static int lastInfoTime;
2462 int t = current_search_time();
2467 // We are line oriented, don't read single chars
2468 std::string command;
2469 if (!std::getline(std::cin, command))
2472 if (command == "quit")
2475 PonderSearch = false;
2479 else if (command == "stop")
2482 PonderSearch = false;
2484 else if (command == "ponderhit")
2487 // Print search information
2491 else if (lastInfoTime > t)
2492 // HACK: Must be a new search where we searched less than
2493 // NodesBetweenPolls nodes during the first second of search.
2496 else if (t - lastInfoTime >= 1000)
2503 if (dbg_show_hit_rate)
2504 dbg_print_hit_rate();
2506 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2507 << " time " << t << " hashfull " << TT.full() << std::endl;
2508 lock_release(&IOLock);
2509 if (ShowCurrentLine)
2510 Threads[0].printCurrentLine = true;
2512 // Should we stop the search?
2516 bool overTime = t > AbsoluteMaxSearchTime
2517 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2518 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2519 && t > 6*(MaxSearchTime + ExtraSearchTime));
2521 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2522 || (ExactMaxTime && t >= ExactMaxTime)
2523 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2528 // ponderhit() is called when the program is pondering (i.e. thinking while
2529 // it's the opponent's turn to move) in order to let the engine know that
2530 // it correctly predicted the opponent's move.
2534 int t = current_search_time();
2535 PonderSearch = false;
2536 if (Iteration >= 3 &&
2537 (!InfiniteSearch && (StopOnPonderhit ||
2538 t > AbsoluteMaxSearchTime ||
2539 (RootMoveNumber == 1 &&
2540 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2541 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2542 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2547 // print_current_line() prints the current line of search for a given
2548 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2550 void print_current_line(SearchStack ss[], int ply, int threadID) {
2552 assert(ply >= 0 && ply < PLY_MAX);
2553 assert(threadID >= 0 && threadID < ActiveThreads);
2555 if (!Threads[threadID].idle)
2558 std::cout << "info currline " << (threadID + 1);
2559 for (int p = 0; p < ply; p++)
2560 std::cout << " " << ss[p].currentMove;
2562 std::cout << std::endl;
2563 lock_release(&IOLock);
2565 Threads[threadID].printCurrentLine = false;
2566 if (threadID + 1 < ActiveThreads)
2567 Threads[threadID + 1].printCurrentLine = true;
2571 // init_ss_array() does a fast reset of the first entries of a SearchStack array
2573 void init_ss_array(SearchStack ss[]) {
2575 for (int i = 0; i < 3; i++)
2578 ss[i].initKillers();
2583 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2584 // while the program is pondering. The point is to work around a wrinkle in
2585 // the UCI protocol: When pondering, the engine is not allowed to give a
2586 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2587 // We simply wait here until one of these commands is sent, and return,
2588 // after which the bestmove and pondermove will be printed (in id_loop()).
2590 void wait_for_stop_or_ponderhit() {
2592 std::string command;
2596 if (!std::getline(std::cin, command))
2599 if (command == "quit")
2604 else if (command == "ponderhit" || command == "stop")
2610 // idle_loop() is where the threads are parked when they have no work to do.
2611 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2612 // object for which the current thread is the master.
2614 void idle_loop(int threadID, SplitPoint* waitSp) {
2615 assert(threadID >= 0 && threadID < THREAD_MAX);
2617 Threads[threadID].running = true;
2620 if(AllThreadsShouldExit && threadID != 0)
2623 // If we are not thinking, wait for a condition to be signaled instead
2624 // of wasting CPU time polling for work:
2625 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2626 #if !defined(_MSC_VER)
2627 pthread_mutex_lock(&WaitLock);
2628 if(Idle || threadID >= ActiveThreads)
2629 pthread_cond_wait(&WaitCond, &WaitLock);
2630 pthread_mutex_unlock(&WaitLock);
2632 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2636 // If this thread has been assigned work, launch a search
2637 if(Threads[threadID].workIsWaiting) {
2638 Threads[threadID].workIsWaiting = false;
2639 if(Threads[threadID].splitPoint->pvNode)
2640 sp_search_pv(Threads[threadID].splitPoint, threadID);
2642 sp_search(Threads[threadID].splitPoint, threadID);
2643 Threads[threadID].idle = true;
2646 // If this thread is the master of a split point and all threads have
2647 // finished their work at this split point, return from the idle loop.
2648 if(waitSp != NULL && waitSp->cpus == 0)
2652 Threads[threadID].running = false;
2656 // init_split_point_stack() is called during program initialization, and
2657 // initializes all split point objects.
2659 void init_split_point_stack() {
2660 for(int i = 0; i < THREAD_MAX; i++)
2661 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2662 SplitPointStack[i][j].parent = NULL;
2663 lock_init(&(SplitPointStack[i][j].lock), NULL);
2668 // destroy_split_point_stack() is called when the program exits, and
2669 // destroys all locks in the precomputed split point objects.
2671 void destroy_split_point_stack() {
2672 for(int i = 0; i < THREAD_MAX; i++)
2673 for(int j = 0; j < MaxActiveSplitPoints; j++)
2674 lock_destroy(&(SplitPointStack[i][j].lock));
2678 // thread_should_stop() checks whether the thread with a given threadID has
2679 // been asked to stop, directly or indirectly. This can happen if a beta
2680 // cutoff has occured in thre thread's currently active split point, or in
2681 // some ancestor of the current split point.
2683 bool thread_should_stop(int threadID) {
2684 assert(threadID >= 0 && threadID < ActiveThreads);
2688 if(Threads[threadID].stop)
2690 if(ActiveThreads <= 2)
2692 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2694 Threads[threadID].stop = true;
2701 // thread_is_available() checks whether the thread with threadID "slave" is
2702 // available to help the thread with threadID "master" at a split point. An
2703 // obvious requirement is that "slave" must be idle. With more than two
2704 // threads, this is not by itself sufficient: If "slave" is the master of
2705 // some active split point, it is only available as a slave to the other
2706 // threads which are busy searching the split point at the top of "slave"'s
2707 // split point stack (the "helpful master concept" in YBWC terminology).
2709 bool thread_is_available(int slave, int master) {
2710 assert(slave >= 0 && slave < ActiveThreads);
2711 assert(master >= 0 && master < ActiveThreads);
2712 assert(ActiveThreads > 1);
2714 if(!Threads[slave].idle || slave == master)
2717 if(Threads[slave].activeSplitPoints == 0)
2718 // No active split points means that the thread is available as a slave
2719 // for any other thread.
2722 if(ActiveThreads == 2)
2725 // Apply the "helpful master" concept if possible.
2726 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2733 // idle_thread_exists() tries to find an idle thread which is available as
2734 // a slave for the thread with threadID "master".
2736 bool idle_thread_exists(int master) {
2737 assert(master >= 0 && master < ActiveThreads);
2738 assert(ActiveThreads > 1);
2740 for(int i = 0; i < ActiveThreads; i++)
2741 if(thread_is_available(i, master))
2747 // split() does the actual work of distributing the work at a node between
2748 // several threads at PV nodes. If it does not succeed in splitting the
2749 // node (because no idle threads are available, or because we have no unused
2750 // split point objects), the function immediately returns false. If
2751 // splitting is possible, a SplitPoint object is initialized with all the
2752 // data that must be copied to the helper threads (the current position and
2753 // search stack, alpha, beta, the search depth, etc.), and we tell our
2754 // helper threads that they have been assigned work. This will cause them
2755 // to instantly leave their idle loops and call sp_search_pv(). When all
2756 // threads have returned from sp_search_pv (or, equivalently, when
2757 // splitPoint->cpus becomes 0), split() returns true.
2759 bool split(const Position& p, SearchStack* sstck, int ply,
2760 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2761 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2764 assert(sstck != NULL);
2765 assert(ply >= 0 && ply < PLY_MAX);
2766 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2767 assert(!pvNode || *alpha < *beta);
2768 assert(*beta <= VALUE_INFINITE);
2769 assert(depth > Depth(0));
2770 assert(master >= 0 && master < ActiveThreads);
2771 assert(ActiveThreads > 1);
2773 SplitPoint* splitPoint;
2778 // If no other thread is available to help us, or if we have too many
2779 // active split points, don't split.
2780 if(!idle_thread_exists(master) ||
2781 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2782 lock_release(&MPLock);
2786 // Pick the next available split point object from the split point stack
2787 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2788 Threads[master].activeSplitPoints++;
2790 // Initialize the split point object
2791 splitPoint->parent = Threads[master].splitPoint;
2792 splitPoint->finished = false;
2793 splitPoint->ply = ply;
2794 splitPoint->depth = depth;
2795 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2796 splitPoint->beta = *beta;
2797 splitPoint->pvNode = pvNode;
2798 splitPoint->dcCandidates = dcCandidates;
2799 splitPoint->bestValue = *bestValue;
2800 splitPoint->master = master;
2801 splitPoint->mp = mp;
2802 splitPoint->moves = *moves;
2803 splitPoint->cpus = 1;
2804 splitPoint->pos.copy(p);
2805 splitPoint->parentSstack = sstck;
2806 for(i = 0; i < ActiveThreads; i++)
2807 splitPoint->slaves[i] = 0;
2809 // Copy the current position and the search stack to the master thread
2810 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2811 Threads[master].splitPoint = splitPoint;
2813 // Make copies of the current position and search stack for each thread
2814 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2816 if(thread_is_available(i, master)) {
2817 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2818 Threads[i].splitPoint = splitPoint;
2819 splitPoint->slaves[i] = 1;
2823 // Tell the threads that they have work to do. This will make them leave
2825 for(i = 0; i < ActiveThreads; i++)
2826 if(i == master || splitPoint->slaves[i]) {
2827 Threads[i].workIsWaiting = true;
2828 Threads[i].idle = false;
2829 Threads[i].stop = false;
2832 lock_release(&MPLock);
2834 // Everything is set up. The master thread enters the idle loop, from
2835 // which it will instantly launch a search, because its workIsWaiting
2836 // slot is 'true'. We send the split point as a second parameter to the
2837 // idle loop, which means that the main thread will return from the idle
2838 // loop when all threads have finished their work at this split point
2839 // (i.e. when // splitPoint->cpus == 0).
2840 idle_loop(master, splitPoint);
2842 // We have returned from the idle loop, which means that all threads are
2843 // finished. Update alpha, beta and bestvalue, and return.
2845 if(pvNode) *alpha = splitPoint->alpha;
2846 *beta = splitPoint->beta;
2847 *bestValue = splitPoint->bestValue;
2848 Threads[master].stop = false;
2849 Threads[master].idle = false;
2850 Threads[master].activeSplitPoints--;
2851 Threads[master].splitPoint = splitPoint->parent;
2852 lock_release(&MPLock);
2858 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2859 // to start a new search from the root.
2861 void wake_sleeping_threads() {
2862 if(ActiveThreads > 1) {
2863 for(int i = 1; i < ActiveThreads; i++) {
2864 Threads[i].idle = true;
2865 Threads[i].workIsWaiting = false;
2867 #if !defined(_MSC_VER)
2868 pthread_mutex_lock(&WaitLock);
2869 pthread_cond_broadcast(&WaitCond);
2870 pthread_mutex_unlock(&WaitLock);
2872 for(int i = 1; i < THREAD_MAX; i++)
2873 SetEvent(SitIdleEvent[i]);
2879 // init_thread() is the function which is called when a new thread is
2880 // launched. It simply calls the idle_loop() function with the supplied
2881 // threadID. There are two versions of this function; one for POSIX threads
2882 // and one for Windows threads.
2884 #if !defined(_MSC_VER)
2886 void *init_thread(void *threadID) {
2887 idle_loop(*(int *)threadID, NULL);
2893 DWORD WINAPI init_thread(LPVOID threadID) {
2894 idle_loop(*(int *)threadID, NULL);