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) };
192 // The main transposition table
193 TranspositionTable TT;
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);
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 bool ok_to_history(const Position& pos, Move m);
295 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
296 void update_killers(Move m, SearchStack& ss);
298 bool fail_high_ply_1();
299 int current_search_time();
303 void print_current_line(SearchStack ss[], int ply, int threadID);
304 void wait_for_stop_or_ponderhit();
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, Depth depth, int *moves,
314 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
315 void wake_sleeping_threads();
317 #if !defined(_MSC_VER)
318 void *init_thread(void *threadID);
320 DWORD WINAPI init_thread(LPVOID threadID);
330 /// think() is the external interface to Stockfish's search, and is called when
331 /// the program receives the UCI 'go' command. It initializes various
332 /// search-related global variables, and calls root_search(). It returns false
333 /// when a quit command is received during the search.
335 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
336 int time[], int increment[], int movesToGo, int maxDepth,
337 int maxNodes, int maxTime, Move searchMoves[]) {
339 // Look for a book move
340 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
343 if (get_option_value_string("Book File") != OpeningBook.file_name())
344 OpeningBook.open("book.bin");
346 bookMove = OpeningBook.get_move(pos);
347 if (bookMove != MOVE_NONE)
349 std::cout << "bestmove " << bookMove << std::endl;
354 // Initialize global search variables
356 SearchStartTime = get_system_time();
357 for (int i = 0; i < THREAD_MAX; i++)
359 Threads[i].nodes = 0ULL;
360 Threads[i].failHighPly1 = false;
363 InfiniteSearch = infinite;
364 PonderSearch = ponder;
365 StopOnPonderhit = false;
371 ExactMaxTime = maxTime;
373 // Read UCI option values
374 TT.set_size(get_option_value_int("Hash"));
375 if (button_was_pressed("Clear Hash"))
378 loseOnTime = false; // reset at the beginning of a new game
381 bool PonderingEnabled = get_option_value_bool("Ponder");
382 MultiPV = get_option_value_int("MultiPV");
384 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
385 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
387 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
388 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
390 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
391 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
393 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
394 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
396 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
397 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
399 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
400 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
402 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
403 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
404 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
406 Chess960 = get_option_value_bool("UCI_Chess960");
407 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
408 UseLogFile = get_option_value_bool("Use Search Log");
410 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
412 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
413 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
415 read_weights(pos.side_to_move());
417 int newActiveThreads = get_option_value_int("Threads");
418 if (newActiveThreads != ActiveThreads)
420 ActiveThreads = newActiveThreads;
421 init_eval(ActiveThreads);
424 // Wake up sleeping threads
425 wake_sleeping_threads();
427 for (int i = 1; i < ActiveThreads; i++)
428 assert(thread_is_available(i, 0));
431 int myTime = time[side_to_move];
432 int myIncrement = increment[side_to_move];
434 if (!movesToGo) // Sudden death time control
438 MaxSearchTime = myTime / 30 + myIncrement;
439 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
440 } else { // Blitz game without increment
441 MaxSearchTime = myTime / 30;
442 AbsoluteMaxSearchTime = myTime / 8;
445 else // (x moves) / (y minutes)
449 MaxSearchTime = myTime / 2;
450 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
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
475 NodesBetweenPolls = 30000;
478 // Write information to search log file
480 LogFile << "Searching: " << pos.to_fen() << std::endl
481 << "infinite: " << infinite
482 << " ponder: " << ponder
483 << " time: " << myTime
484 << " increment: " << myIncrement
485 << " moves to go: " << movesToGo << std::endl;
488 // We're ready to start thinking. Call the iterative deepening loop function
490 // FIXME we really need to cleanup all this LSN ugliness
493 Value v = id_loop(pos, searchMoves);
494 loseOnTime = ( UseLSNFiltering
501 loseOnTime = false; // reset for next match
502 while (SearchStartTime + myTime + 1000 > get_system_time())
504 id_loop(pos, searchMoves); // to fail gracefully
515 /// init_threads() is called during startup. It launches all helper threads,
516 /// and initializes the split point stack and the global locks and condition
519 void init_threads() {
523 #if !defined(_MSC_VER)
524 pthread_t pthread[1];
527 for (i = 0; i < THREAD_MAX; i++)
528 Threads[i].activeSplitPoints = 0;
530 // Initialize global locks
531 lock_init(&MPLock, NULL);
532 lock_init(&IOLock, NULL);
534 init_split_point_stack();
536 #if !defined(_MSC_VER)
537 pthread_mutex_init(&WaitLock, NULL);
538 pthread_cond_init(&WaitCond, NULL);
540 for (i = 0; i < THREAD_MAX; i++)
541 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
544 // All threads except the main thread should be initialized to idle state
545 for (i = 1; i < THREAD_MAX; i++)
547 Threads[i].stop = false;
548 Threads[i].workIsWaiting = false;
549 Threads[i].idle = true;
550 Threads[i].running = false;
553 // Launch the helper threads
554 for(i = 1; i < THREAD_MAX; i++)
556 #if !defined(_MSC_VER)
557 pthread_create(pthread, NULL, init_thread, (void*)(&i));
560 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
563 // Wait until the thread has finished launching
564 while (!Threads[i].running);
569 /// stop_threads() is called when the program exits. It makes all the
570 /// helper threads exit cleanly.
572 void stop_threads() {
574 ActiveThreads = THREAD_MAX; // HACK
575 Idle = false; // HACK
576 wake_sleeping_threads();
577 AllThreadsShouldExit = true;
578 for (int i = 1; i < THREAD_MAX; i++)
580 Threads[i].stop = true;
581 while(Threads[i].running);
583 destroy_split_point_stack();
587 /// nodes_searched() returns the total number of nodes searched so far in
588 /// the current search.
590 int64_t nodes_searched() {
592 int64_t result = 0ULL;
593 for (int i = 0; i < ActiveThreads; i++)
594 result += Threads[i].nodes;
599 // SearchStack::init() initializes a search stack. Used at the beginning of a
600 // new search from the root.
601 void SearchStack::init(int ply) {
603 pv[ply] = pv[ply + 1] = MOVE_NONE;
604 currentMove = threatMove = MOVE_NONE;
605 reduction = Depth(0);
608 void SearchStack::initKillers() {
610 mateKiller = MOVE_NONE;
611 for (int i = 0; i < KILLER_MAX; i++)
612 killers[i] = MOVE_NONE;
617 // id_loop() is the main iterative deepening loop. It calls root_search
618 // repeatedly with increasing depth until the allocated thinking time has
619 // been consumed, the user stops the search, or the maximum search depth is
622 Value id_loop(const Position& pos, Move searchMoves[]) {
625 SearchStack ss[PLY_MAX_PLUS_2];
627 // searchMoves are verified, copied, scored and sorted
628 RootMoveList rml(p, searchMoves);
633 for (int i = 0; i < 3; i++)
638 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
641 Move EasyMove = rml.scan_for_easy_move();
643 // Iterative deepening loop
644 while (Iteration < PLY_MAX)
646 // Initialize iteration
649 BestMoveChangesByIteration[Iteration] = 0;
653 std::cout << "info depth " << Iteration << std::endl;
655 // Calculate dynamic search window based on previous iterations
658 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
660 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
661 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
663 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
665 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
666 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
670 alpha = - VALUE_INFINITE;
671 beta = VALUE_INFINITE;
674 // Search to the current depth
675 Value value = root_search(p, ss, rml, alpha, beta);
677 // Write PV to transposition table, in case the relevant entries have
678 // been overwritten during the search.
679 TT.insert_pv(p, ss[0].pv);
682 break; // Value cannot be trusted. Break out immediately!
684 //Save info about search result
685 Value speculatedValue;
688 Value delta = value - IterationInfo[Iteration - 1].value;
695 speculatedValue = value + delta;
696 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
698 else if (value <= alpha)
700 assert(value == alpha);
704 speculatedValue = value + delta;
705 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
707 speculatedValue = value;
709 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
710 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
712 // Erase the easy move if it differs from the new best move
713 if (ss[0].pv[0] != EasyMove)
714 EasyMove = MOVE_NONE;
721 bool stopSearch = false;
723 // Stop search early if there is only a single legal move
724 if (Iteration >= 6 && rml.move_count() == 1)
727 // Stop search early when the last two iterations returned a mate score
729 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
730 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
733 // Stop search early if one move seems to be much better than the rest
734 int64_t nodes = nodes_searched();
738 && EasyMove == ss[0].pv[0]
739 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
740 && current_search_time() > MaxSearchTime / 16)
741 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
742 && current_search_time() > MaxSearchTime / 32)))
745 // Add some extra time if the best move has changed during the last two iterations
746 if (Iteration > 5 && Iteration <= 50)
747 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
748 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
750 // Stop search if most of MaxSearchTime is consumed at the end of the
751 // iteration. We probably don't have enough time to search the first
752 // move at the next iteration anyway.
753 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
758 //FIXME: Implement fail-low emergency measures
762 StopOnPonderhit = true;
766 if (MaxDepth && Iteration >= MaxDepth)
772 // If we are pondering, we shouldn't print the best move before we
775 wait_for_stop_or_ponderhit();
777 // Print final search statistics
778 std::cout << "info nodes " << nodes_searched()
780 << " time " << current_search_time()
781 << " hashfull " << TT.full() << std::endl;
783 // Print the best move and the ponder move to the standard output
784 if (ss[0].pv[0] == MOVE_NONE)
786 ss[0].pv[0] = rml.get_move(0);
787 ss[0].pv[1] = MOVE_NONE;
789 std::cout << "bestmove " << ss[0].pv[0];
790 if (ss[0].pv[1] != MOVE_NONE)
791 std::cout << " ponder " << ss[0].pv[1];
793 std::cout << std::endl;
798 dbg_print_mean(LogFile);
800 if (dbg_show_hit_rate)
801 dbg_print_hit_rate(LogFile);
804 LogFile << "Nodes: " << nodes_searched() << std::endl
805 << "Nodes/second: " << nps() << std::endl
806 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
808 p.do_move(ss[0].pv[0], st);
809 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
810 << std::endl << std::endl;
812 return rml.get_move_score(0);
816 // root_search() is the function which searches the root node. It is
817 // similar to search_pv except that it uses a different move ordering
818 // scheme (perhaps we should try to use this at internal PV nodes, too?)
819 // and prints some information to the standard output.
821 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
823 Value oldAlpha = alpha;
825 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
827 // Loop through all the moves in the root move list
828 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
832 // We failed high, invalidate and skip next moves, leave node-counters
833 // and beta-counters as they are and quickly return, we will try to do
834 // a research at the next iteration with a bigger aspiration window.
835 rml.set_move_score(i, -VALUE_INFINITE);
843 RootMoveNumber = i + 1;
846 // Remember the node count before the move is searched. The node counts
847 // are used to sort the root moves at the next iteration.
848 nodes = nodes_searched();
850 // Reset beta cut-off counters
853 // Pick the next root move, and print the move and the move number to
854 // the standard output.
855 move = ss[0].currentMove = rml.get_move(i);
856 if (current_search_time() >= 1000)
857 std::cout << "info currmove " << move
858 << " currmovenumber " << i + 1 << std::endl;
860 // Decide search depth for this move
861 bool moveIsCapture = pos.move_is_capture(move);
863 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
864 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
866 // Make the move, and search it
867 pos.do_move(move, st, dcCandidates);
871 // Aspiration window is disabled in multi-pv case
873 alpha = -VALUE_INFINITE;
875 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
876 // If the value has dropped a lot compared to the last iteration,
877 // set the boolean variable Problem to true. This variable is used
878 // for time managment: When Problem is true, we try to complete the
879 // current iteration before playing a move.
880 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
882 if (Problem && StopOnPonderhit)
883 StopOnPonderhit = false;
887 if (newDepth >= 3*OnePly
888 && i + MultiPV >= LMRPVMoves
891 && !move_is_promotion(move)
892 && !move_is_castle(move))
894 ss[0].reduction = OnePly;
895 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
898 value = alpha + 1; // Just to trigger next condition
901 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
904 // Fail high! Set the boolean variable FailHigh to true, and
905 // re-search the move with a big window. The variable FailHigh is
906 // used for time managment: We try to avoid aborting the search
907 // prematurely during a fail high research.
909 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
916 // Finished searching the move. If AbortSearch is true, the search
917 // was aborted because the user interrupted the search or because we
918 // ran out of time. In this case, the return value of the search cannot
919 // be trusted, and we break out of the loop without updating the best
924 // Remember the node count for this move. The node counts are used to
925 // sort the root moves at the next iteration.
926 rml.set_move_nodes(i, nodes_searched() - nodes);
928 // Remember the beta-cutoff statistics
930 BetaCounter.read(pos.side_to_move(), our, their);
931 rml.set_beta_counters(i, our, their);
933 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
935 if (value <= alpha && i >= MultiPV)
936 rml.set_move_score(i, -VALUE_INFINITE);
939 // PV move or new best move!
942 rml.set_move_score(i, value);
944 rml.set_move_pv(i, ss[0].pv);
948 // We record how often the best move has been changed in each
949 // iteration. This information is used for time managment: When
950 // the best move changes frequently, we allocate some more time.
952 BestMoveChangesByIteration[Iteration]++;
954 // Print search information to the standard output
955 std::cout << "info depth " << Iteration
956 << " score " << value_to_string(value)
957 << " time " << current_search_time()
958 << " nodes " << nodes_searched()
962 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
963 std::cout << ss[0].pv[j] << " ";
965 std::cout << std::endl;
968 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
974 // Reset the global variable Problem to false if the value isn't too
975 // far below the final value from the last iteration.
976 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
982 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
985 std::cout << "info multipv " << j + 1
986 << " score " << value_to_string(rml.get_move_score(j))
987 << " depth " << ((j <= i)? Iteration : Iteration - 1)
988 << " time " << current_search_time()
989 << " nodes " << nodes_searched()
993 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
994 std::cout << rml.get_move_pv(j, k) << " ";
996 std::cout << std::endl;
998 alpha = rml.get_move_score(Min(i, MultiPV-1));
1000 } // New best move case
1002 assert(alpha >= oldAlpha);
1004 FailLow = (alpha == oldAlpha);
1010 // search_pv() is the main search function for PV nodes.
1012 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1013 Depth depth, int ply, int threadID) {
1015 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1016 assert(beta > alpha && beta <= VALUE_INFINITE);
1017 assert(ply >= 0 && ply < PLY_MAX);
1018 assert(threadID >= 0 && threadID < ActiveThreads);
1021 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1023 // Initialize, and make an early exit in case of an aborted search,
1024 // an instant draw, maximum ply reached, etc.
1025 init_node(ss, ply, threadID);
1027 // After init_node() that calls poll()
1028 if (AbortSearch || thread_should_stop(threadID))
1036 if (ply >= PLY_MAX - 1)
1037 return evaluate(pos, ei, threadID);
1039 // Mate distance pruning
1040 Value oldAlpha = alpha;
1041 alpha = Max(value_mated_in(ply), alpha);
1042 beta = Min(value_mate_in(ply+1), beta);
1046 // Transposition table lookup. At PV nodes, we don't use the TT for
1047 // pruning, but only for move ordering.
1048 const TTEntry* tte = TT.retrieve(pos.get_key());
1049 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1051 // Go with internal iterative deepening if we don't have a TT move
1052 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1054 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1055 ttMove = ss[ply].pv[ply];
1058 // Initialize a MovePicker object for the current position, and prepare
1059 // to search all moves
1060 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1062 Move move, movesSearched[256];
1064 Value value, bestValue = -VALUE_INFINITE;
1065 Bitboard dcCandidates = mp.discovered_check_candidates();
1066 Color us = pos.side_to_move();
1067 bool isCheck = pos.is_check();
1068 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1070 // Loop through all legal moves until no moves remain or a beta cutoff
1072 while ( alpha < beta
1073 && (move = mp.get_next_move()) != MOVE_NONE
1074 && !thread_should_stop(threadID))
1076 assert(move_is_ok(move));
1078 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1079 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1080 bool moveIsCapture = pos.move_is_capture(move);
1082 movesSearched[moveCount++] = ss[ply].currentMove = move;
1084 // Decide the new search depth
1086 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1087 Depth newDepth = depth - OnePly + ext;
1089 // Make and search the move
1091 pos.do_move(move, st, dcCandidates);
1093 if (moveCount == 1) // The first move in list is the PV
1094 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1097 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1098 // if the move fails high will be re-searched at full depth.
1099 if ( depth >= 3*OnePly
1100 && moveCount >= LMRPVMoves
1103 && !move_is_promotion(move)
1104 && !move_is_castle(move)
1105 && !move_is_killer(move, ss[ply]))
1107 ss[ply].reduction = OnePly;
1108 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1111 value = alpha + 1; // Just to trigger next condition
1113 if (value > alpha) // Go with full depth non-pv search
1115 ss[ply].reduction = Depth(0);
1116 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1117 if (value > alpha && value < beta)
1119 // When the search fails high at ply 1 while searching the first
1120 // move at the root, set the flag failHighPly1. This is used for
1121 // time managment: We don't want to stop the search early in
1122 // such cases, because resolving the fail high at ply 1 could
1123 // result in a big drop in score at the root.
1124 if (ply == 1 && RootMoveNumber == 1)
1125 Threads[threadID].failHighPly1 = true;
1127 // A fail high occurred. Re-search at full window (pv search)
1128 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1129 Threads[threadID].failHighPly1 = false;
1133 pos.undo_move(move);
1135 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1138 if (value > bestValue)
1145 if (value == value_mate_in(ply + 1))
1146 ss[ply].mateKiller = move;
1148 // If we are at ply 1, and we are searching the first root move at
1149 // ply 0, set the 'Problem' variable if the score has dropped a lot
1150 // (from the computer's point of view) since the previous iteration.
1153 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1158 if ( ActiveThreads > 1
1160 && depth >= MinimumSplitDepth
1162 && idle_thread_exists(threadID)
1164 && !thread_should_stop(threadID)
1165 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1166 &moveCount, &mp, dcCandidates, threadID, true))
1170 // All legal moves have been searched. A special case: If there were
1171 // no legal moves, it must be mate or stalemate.
1173 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1175 // If the search is not aborted, update the transposition table,
1176 // history counters, and killer moves.
1177 if (AbortSearch || thread_should_stop(threadID))
1180 if (bestValue <= oldAlpha)
1181 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1183 else if (bestValue >= beta)
1185 BetaCounter.add(pos.side_to_move(), depth, threadID);
1186 Move m = ss[ply].pv[ply];
1187 if (ok_to_history(pos, m)) // Only non capture moves are considered
1189 update_history(pos, m, depth, movesSearched, moveCount);
1190 update_killers(m, ss[ply]);
1192 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1195 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1201 // search() is the search function for zero-width nodes.
1203 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1204 int ply, bool allowNullmove, int threadID) {
1206 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1207 assert(ply >= 0 && ply < PLY_MAX);
1208 assert(threadID >= 0 && threadID < ActiveThreads);
1211 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1213 // Initialize, and make an early exit in case of an aborted search,
1214 // an instant draw, maximum ply reached, etc.
1215 init_node(ss, ply, threadID);
1217 // After init_node() that calls poll()
1218 if (AbortSearch || thread_should_stop(threadID))
1226 if (ply >= PLY_MAX - 1)
1227 return evaluate(pos, ei, threadID);
1229 // Mate distance pruning
1230 if (value_mated_in(ply) >= beta)
1233 if (value_mate_in(ply + 1) < beta)
1236 // Transposition table lookup
1237 const TTEntry* tte = TT.retrieve(pos.get_key());
1238 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1240 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1242 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1243 return value_from_tt(tte->value(), ply);
1246 Value approximateEval = quick_evaluate(pos);
1247 bool mateThreat = false;
1248 bool isCheck = pos.is_check();
1254 && !value_is_mate(beta)
1255 && ok_to_do_nullmove(pos)
1256 && approximateEval >= beta - NullMoveMargin)
1258 ss[ply].currentMove = MOVE_NULL;
1261 pos.do_null_move(st);
1262 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1264 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1266 pos.undo_null_move();
1268 if (nullValue >= beta)
1270 if (depth < 6 * OnePly)
1273 // Do zugzwang verification search
1274 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1278 // The null move failed low, which means that we may be faced with
1279 // some kind of threat. If the previous move was reduced, check if
1280 // the move that refuted the null move was somehow connected to the
1281 // move which was reduced. If a connection is found, return a fail
1282 // low score (which will cause the reduced move to fail high in the
1283 // parent node, which will trigger a re-search with full depth).
1284 if (nullValue == value_mated_in(ply + 2))
1287 ss[ply].threatMove = ss[ply + 1].currentMove;
1288 if ( depth < ThreatDepth
1289 && ss[ply - 1].reduction
1290 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1294 // Null move search not allowed, try razoring
1295 else if ( !value_is_mate(beta)
1296 && depth < RazorDepth
1297 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1298 && ss[ply - 1].currentMove != MOVE_NULL
1299 && ttMove == MOVE_NONE
1300 && !pos.has_pawn_on_7th(pos.side_to_move()))
1302 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1303 if (v < beta - RazorMargins[int(depth) - 2])
1307 // Go with internal iterative deepening if we don't have a TT move
1308 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1309 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1311 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1312 ttMove = ss[ply].pv[ply];
1315 // Initialize a MovePicker object for the current position, and prepare
1316 // to search all moves.
1317 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1319 Move move, movesSearched[256];
1321 Value value, bestValue = -VALUE_INFINITE;
1322 Bitboard dcCandidates = mp.discovered_check_candidates();
1323 Value futilityValue = VALUE_NONE;
1324 bool useFutilityPruning = depth < SelectiveDepth
1327 // Loop through all legal moves until no moves remain or a beta cutoff
1329 while ( bestValue < beta
1330 && (move = mp.get_next_move()) != MOVE_NONE
1331 && !thread_should_stop(threadID))
1333 assert(move_is_ok(move));
1335 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1336 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1337 bool moveIsCapture = pos.move_is_capture(move);
1339 movesSearched[moveCount++] = ss[ply].currentMove = move;
1341 // Decide the new search depth
1343 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1344 Depth newDepth = depth - OnePly + ext;
1347 if ( useFutilityPruning
1350 && !move_is_promotion(move))
1352 // History pruning. See ok_to_prune() definition
1353 if ( moveCount >= 2 + int(depth)
1354 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1357 // Value based pruning
1358 if (approximateEval < beta)
1360 if (futilityValue == VALUE_NONE)
1361 futilityValue = evaluate(pos, ei, threadID)
1362 + FutilityMargins[int(depth) - 2];
1364 if (futilityValue < beta)
1366 if (futilityValue > bestValue)
1367 bestValue = futilityValue;
1373 // Make and search the move
1375 pos.do_move(move, st, dcCandidates);
1377 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1378 // if the move fails high will be re-searched at full depth.
1379 if ( depth >= 3*OnePly
1380 && moveCount >= LMRNonPVMoves
1383 && !move_is_promotion(move)
1384 && !move_is_castle(move)
1385 && !move_is_killer(move, ss[ply]))
1387 ss[ply].reduction = OnePly;
1388 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1391 value = beta; // Just to trigger next condition
1393 if (value >= beta) // Go with full depth non-pv search
1395 ss[ply].reduction = Depth(0);
1396 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1398 pos.undo_move(move);
1400 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1403 if (value > bestValue)
1409 if (value == value_mate_in(ply + 1))
1410 ss[ply].mateKiller = move;
1414 if ( ActiveThreads > 1
1416 && depth >= MinimumSplitDepth
1418 && idle_thread_exists(threadID)
1420 && !thread_should_stop(threadID)
1421 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1422 &mp, dcCandidates, threadID, false))
1426 // All legal moves have been searched. A special case: If there were
1427 // no legal moves, it must be mate or stalemate.
1429 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1431 // If the search is not aborted, update the transposition table,
1432 // history counters, and killer moves.
1433 if (AbortSearch || thread_should_stop(threadID))
1436 if (bestValue < beta)
1437 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1440 BetaCounter.add(pos.side_to_move(), depth, threadID);
1441 Move m = ss[ply].pv[ply];
1442 if (ok_to_history(pos, m)) // Only non capture moves are considered
1444 update_history(pos, m, depth, movesSearched, moveCount);
1445 update_killers(m, ss[ply]);
1447 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1450 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1456 // qsearch() is the quiescence search function, which is called by the main
1457 // search function when the remaining depth is zero (or, to be more precise,
1458 // less than OnePly).
1460 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1461 Depth depth, int ply, int threadID) {
1463 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1464 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1466 assert(ply >= 0 && ply < PLY_MAX);
1467 assert(threadID >= 0 && threadID < ActiveThreads);
1469 // Initialize, and make an early exit in case of an aborted search,
1470 // an instant draw, maximum ply reached, etc.
1471 init_node(ss, ply, threadID);
1473 // After init_node() that calls poll()
1474 if (AbortSearch || thread_should_stop(threadID))
1480 // Transposition table lookup, only when not in PV
1481 TTEntry* tte = NULL;
1482 bool pvNode = (beta - alpha != 1);
1485 tte = TT.retrieve(pos.get_key());
1486 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1488 assert(tte->type() != VALUE_TYPE_EVAL);
1490 return value_from_tt(tte->value(), ply);
1493 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1495 // Evaluate the position statically
1498 bool isCheck = pos.is_check();
1499 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1502 staticValue = -VALUE_INFINITE;
1504 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1506 // Use the cached evaluation score if possible
1507 assert(ei.futilityMargin == Value(0));
1509 staticValue = tte->value();
1512 staticValue = evaluate(pos, ei, threadID);
1514 if (ply == PLY_MAX - 1)
1515 return evaluate(pos, ei, threadID);
1517 // Initialize "stand pat score", and return it immediately if it is
1519 Value bestValue = staticValue;
1521 if (bestValue >= beta)
1523 // Store the score to avoid a future costly evaluation() call
1524 if (!isCheck && !tte && ei.futilityMargin == 0)
1525 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1530 if (bestValue > alpha)
1533 // Initialize a MovePicker object for the current position, and prepare
1534 // to search the moves. Because the depth is <= 0 here, only captures,
1535 // queen promotions and checks (only if depth == 0) will be generated.
1536 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1539 Bitboard dcCandidates = mp.discovered_check_candidates();
1540 Color us = pos.side_to_move();
1541 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1543 // Loop through the moves until no moves remain or a beta cutoff
1545 while ( alpha < beta
1546 && (move = mp.get_next_move()) != MOVE_NONE)
1548 assert(move_is_ok(move));
1551 ss[ply].currentMove = move;
1557 && !move_is_promotion(move)
1558 && !pos.move_is_check(move, dcCandidates)
1559 && !pos.move_is_passed_pawn_push(move))
1561 Value futilityValue = staticValue
1562 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1563 pos.endgame_value_of_piece_on(move_to(move)))
1564 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1566 + ei.futilityMargin;
1568 if (futilityValue < alpha)
1570 if (futilityValue > bestValue)
1571 bestValue = futilityValue;
1576 // Don't search captures and checks with negative SEE values
1578 && !move_is_promotion(move)
1579 && pos.see_sign(move) < 0)
1582 // Make and search the move.
1584 pos.do_move(move, st, dcCandidates);
1585 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1586 pos.undo_move(move);
1588 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1591 if (value > bestValue)
1602 // All legal moves have been searched. A special case: If we're in check
1603 // and no legal moves were found, it is checkmate.
1604 if (pos.is_check() && moveCount == 0) // Mate!
1605 return value_mated_in(ply);
1607 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1609 // Update transposition table
1610 Move m = ss[ply].pv[ply];
1613 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1614 if (bestValue < beta)
1615 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1617 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1620 // Update killers only for good check moves
1621 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1622 update_killers(m, ss[ply]);
1628 // sp_search() is used to search from a split point. This function is called
1629 // by each thread working at the split point. It is similar to the normal
1630 // search() function, but simpler. Because we have already probed the hash
1631 // table, done a null move search, and searched the first move before
1632 // splitting, we don't have to repeat all this work in sp_search(). We
1633 // also don't need to store anything to the hash table here: This is taken
1634 // care of after we return from the split point.
1636 void sp_search(SplitPoint* sp, int threadID) {
1638 assert(threadID >= 0 && threadID < ActiveThreads);
1639 assert(ActiveThreads > 1);
1641 Position pos = Position(sp->pos);
1642 SearchStack* ss = sp->sstack[threadID];
1645 bool isCheck = pos.is_check();
1646 bool useFutilityPruning = sp->depth < SelectiveDepth
1649 while ( sp->bestValue < sp->beta
1650 && !thread_should_stop(threadID)
1651 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1653 assert(move_is_ok(move));
1655 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1656 bool moveIsCapture = pos.move_is_capture(move);
1658 lock_grab(&(sp->lock));
1659 int moveCount = ++sp->moves;
1660 lock_release(&(sp->lock));
1662 ss[sp->ply].currentMove = move;
1664 // Decide the new search depth.
1666 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1667 Depth newDepth = sp->depth - OnePly + ext;
1670 if ( useFutilityPruning
1673 && !move_is_promotion(move)
1674 && moveCount >= 2 + int(sp->depth)
1675 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1678 // Make and search the move.
1680 pos.do_move(move, st, sp->dcCandidates);
1682 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1683 // if the move fails high will be re-searched at full depth.
1685 && moveCount >= LMRNonPVMoves
1687 && !move_is_promotion(move)
1688 && !move_is_castle(move)
1689 && !move_is_killer(move, ss[sp->ply]))
1691 ss[sp->ply].reduction = OnePly;
1692 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1695 value = sp->beta; // Just to trigger next condition
1697 if (value >= sp->beta) // Go with full depth non-pv search
1699 ss[sp->ply].reduction = Depth(0);
1700 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1702 pos.undo_move(move);
1704 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1706 if (thread_should_stop(threadID))
1710 lock_grab(&(sp->lock));
1711 if (value > sp->bestValue && !thread_should_stop(threadID))
1713 sp->bestValue = value;
1714 if (sp->bestValue >= sp->beta)
1716 sp_update_pv(sp->parentSstack, ss, sp->ply);
1717 for (int i = 0; i < ActiveThreads; i++)
1718 if (i != threadID && (i == sp->master || sp->slaves[i]))
1719 Threads[i].stop = true;
1721 sp->finished = true;
1724 lock_release(&(sp->lock));
1727 lock_grab(&(sp->lock));
1729 // If this is the master thread and we have been asked to stop because of
1730 // a beta cutoff higher up in the tree, stop all slave threads.
1731 if (sp->master == threadID && thread_should_stop(threadID))
1732 for (int i = 0; i < ActiveThreads; i++)
1734 Threads[i].stop = true;
1737 sp->slaves[threadID] = 0;
1739 lock_release(&(sp->lock));
1743 // sp_search_pv() is used to search from a PV split point. This function
1744 // is called by each thread working at the split point. It is similar to
1745 // the normal search_pv() function, but simpler. Because we have already
1746 // probed the hash table and searched the first move before splitting, we
1747 // don't have to repeat all this work in sp_search_pv(). We also don't
1748 // need to store anything to the hash table here: This is taken care of
1749 // after we return from the split point.
1751 void sp_search_pv(SplitPoint* sp, int threadID) {
1753 assert(threadID >= 0 && threadID < ActiveThreads);
1754 assert(ActiveThreads > 1);
1756 Position pos = Position(sp->pos);
1757 SearchStack* ss = sp->sstack[threadID];
1761 while ( sp->alpha < sp->beta
1762 && !thread_should_stop(threadID)
1763 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1765 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1766 bool moveIsCapture = pos.move_is_capture(move);
1768 assert(move_is_ok(move));
1770 lock_grab(&(sp->lock));
1771 int moveCount = ++sp->moves;
1772 lock_release(&(sp->lock));
1774 ss[sp->ply].currentMove = move;
1776 // Decide the new search depth.
1778 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1779 Depth newDepth = sp->depth - OnePly + ext;
1781 // Make and search the move.
1783 pos.do_move(move, st, sp->dcCandidates);
1785 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1786 // if the move fails high will be re-searched at full depth.
1788 && moveCount >= LMRPVMoves
1790 && !move_is_promotion(move)
1791 && !move_is_castle(move)
1792 && !move_is_killer(move, ss[sp->ply]))
1794 ss[sp->ply].reduction = OnePly;
1795 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1798 value = sp->alpha + 1; // Just to trigger next condition
1800 if (value > sp->alpha) // Go with full depth non-pv search
1802 ss[sp->ply].reduction = Depth(0);
1803 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1805 if (value > sp->alpha && value < sp->beta)
1807 // When the search fails high at ply 1 while searching the first
1808 // move at the root, set the flag failHighPly1. This is used for
1809 // time managment: We don't want to stop the search early in
1810 // such cases, because resolving the fail high at ply 1 could
1811 // result in a big drop in score at the root.
1812 if (sp->ply == 1 && RootMoveNumber == 1)
1813 Threads[threadID].failHighPly1 = true;
1815 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1816 Threads[threadID].failHighPly1 = false;
1819 pos.undo_move(move);
1821 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1823 if (thread_should_stop(threadID))
1827 lock_grab(&(sp->lock));
1828 if (value > sp->bestValue && !thread_should_stop(threadID))
1830 sp->bestValue = value;
1831 if (value > sp->alpha)
1834 sp_update_pv(sp->parentSstack, ss, sp->ply);
1835 if (value == value_mate_in(sp->ply + 1))
1836 ss[sp->ply].mateKiller = move;
1838 if (value >= sp->beta)
1840 for (int i = 0; i < ActiveThreads; i++)
1841 if (i != threadID && (i == sp->master || sp->slaves[i]))
1842 Threads[i].stop = true;
1844 sp->finished = true;
1847 // If we are at ply 1, and we are searching the first root move at
1848 // ply 0, set the 'Problem' variable if the score has dropped a lot
1849 // (from the computer's point of view) since the previous iteration.
1852 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1855 lock_release(&(sp->lock));
1858 lock_grab(&(sp->lock));
1860 // If this is the master thread and we have been asked to stop because of
1861 // a beta cutoff higher up in the tree, stop all slave threads.
1862 if (sp->master == threadID && thread_should_stop(threadID))
1863 for (int i = 0; i < ActiveThreads; i++)
1865 Threads[i].stop = true;
1868 sp->slaves[threadID] = 0;
1870 lock_release(&(sp->lock));
1873 /// The BetaCounterType class
1875 BetaCounterType::BetaCounterType() { clear(); }
1877 void BetaCounterType::clear() {
1879 for (int i = 0; i < THREAD_MAX; i++)
1880 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1883 void BetaCounterType::add(Color us, Depth d, int threadID) {
1885 // Weighted count based on depth
1886 Threads[threadID].betaCutOffs[us] += unsigned(d);
1889 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1892 for (int i = 0; i < THREAD_MAX; i++)
1894 our += Threads[i].betaCutOffs[us];
1895 their += Threads[i].betaCutOffs[opposite_color(us)];
1900 /// The RootMove class
1904 RootMove::RootMove() {
1905 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1908 // RootMove::operator<() is the comparison function used when
1909 // sorting the moves. A move m1 is considered to be better
1910 // than a move m2 if it has a higher score, or if the moves
1911 // have equal score but m1 has the higher node count.
1913 bool RootMove::operator<(const RootMove& m) {
1915 if (score != m.score)
1916 return (score < m.score);
1918 return theirBeta <= m.theirBeta;
1921 /// The RootMoveList class
1925 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1927 MoveStack mlist[MaxRootMoves];
1928 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1930 // Generate all legal moves
1931 int lm_count = generate_legal_moves(pos, mlist);
1933 // Add each move to the moves[] array
1934 for (int i = 0; i < lm_count; i++)
1936 bool includeMove = includeAllMoves;
1938 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1939 includeMove = (searchMoves[k] == mlist[i].move);
1944 // Find a quick score for the move
1946 SearchStack ss[PLY_MAX_PLUS_2];
1948 moves[count].move = mlist[i].move;
1949 pos.do_move(moves[count].move, st);
1950 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1951 pos.undo_move(moves[count].move);
1952 moves[count].pv[0] = moves[count].move;
1953 moves[count].pv[1] = MOVE_NONE; // FIXME
1960 // Simple accessor methods for the RootMoveList class
1962 inline Move RootMoveList::get_move(int moveNum) const {
1963 return moves[moveNum].move;
1966 inline Value RootMoveList::get_move_score(int moveNum) const {
1967 return moves[moveNum].score;
1970 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1971 moves[moveNum].score = score;
1974 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1975 moves[moveNum].nodes = nodes;
1976 moves[moveNum].cumulativeNodes += nodes;
1979 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1980 moves[moveNum].ourBeta = our;
1981 moves[moveNum].theirBeta = their;
1984 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1986 for(j = 0; pv[j] != MOVE_NONE; j++)
1987 moves[moveNum].pv[j] = pv[j];
1988 moves[moveNum].pv[j] = MOVE_NONE;
1991 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1992 return moves[moveNum].pv[i];
1995 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1996 return moves[moveNum].cumulativeNodes;
1999 inline int RootMoveList::move_count() const {
2004 // RootMoveList::scan_for_easy_move() is called at the end of the first
2005 // iteration, and is used to detect an "easy move", i.e. a move which appears
2006 // to be much bester than all the rest. If an easy move is found, the move
2007 // is returned, otherwise the function returns MOVE_NONE. It is very
2008 // important that this function is called at the right moment: The code
2009 // assumes that the first iteration has been completed and the moves have
2010 // been sorted. This is done in RootMoveList c'tor.
2012 Move RootMoveList::scan_for_easy_move() const {
2019 // moves are sorted so just consider the best and the second one
2020 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2026 // RootMoveList::sort() sorts the root move list at the beginning of a new
2029 inline void RootMoveList::sort() {
2031 sort_multipv(count - 1); // all items
2035 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2036 // list by their scores and depths. It is used to order the different PVs
2037 // correctly in MultiPV mode.
2039 void RootMoveList::sort_multipv(int n) {
2041 for (int i = 1; i <= n; i++)
2043 RootMove rm = moves[i];
2045 for (j = i; j > 0 && moves[j-1] < rm; j--)
2046 moves[j] = moves[j-1];
2052 // init_node() is called at the beginning of all the search functions
2053 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2054 // stack object corresponding to the current node. Once every
2055 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2056 // for user input and checks whether it is time to stop the search.
2058 void init_node(SearchStack ss[], int ply, int threadID) {
2060 assert(ply >= 0 && ply < PLY_MAX);
2061 assert(threadID >= 0 && threadID < ActiveThreads);
2063 Threads[threadID].nodes++;
2068 if (NodesSincePoll >= NodesBetweenPolls)
2075 ss[ply+2].initKillers();
2077 if (Threads[threadID].printCurrentLine)
2078 print_current_line(ss, ply, threadID);
2082 // update_pv() is called whenever a search returns a value > alpha. It
2083 // updates the PV in the SearchStack object corresponding to the current
2086 void update_pv(SearchStack ss[], int ply) {
2087 assert(ply >= 0 && ply < PLY_MAX);
2089 ss[ply].pv[ply] = ss[ply].currentMove;
2091 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2092 ss[ply].pv[p] = ss[ply+1].pv[p];
2093 ss[ply].pv[p] = MOVE_NONE;
2097 // sp_update_pv() is a variant of update_pv for use at split points. The
2098 // difference between the two functions is that sp_update_pv also updates
2099 // the PV at the parent node.
2101 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2102 assert(ply >= 0 && ply < PLY_MAX);
2104 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2106 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2107 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2108 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2112 // connected_moves() tests whether two moves are 'connected' in the sense
2113 // that the first move somehow made the second move possible (for instance
2114 // if the moving piece is the same in both moves). The first move is
2115 // assumed to be the move that was made to reach the current position, while
2116 // the second move is assumed to be a move from the current position.
2118 bool connected_moves(const Position& pos, Move m1, Move m2) {
2119 Square f1, t1, f2, t2;
2121 assert(move_is_ok(m1));
2122 assert(move_is_ok(m2));
2124 if (m2 == MOVE_NONE)
2127 // Case 1: The moving piece is the same in both moves
2133 // Case 2: The destination square for m2 was vacated by m1
2139 // Case 3: Moving through the vacated square
2140 if ( piece_is_slider(pos.piece_on(f2))
2141 && bit_is_set(squares_between(f2, t2), f1))
2144 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2145 if (pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2148 // Case 5: Discovered check, checking piece is the piece moved in m1
2149 if ( piece_is_slider(pos.piece_on(t1))
2150 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2151 && !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())), t2))
2153 Bitboard occ = pos.occupied_squares();
2154 Color us = pos.side_to_move();
2155 Square ksq = pos.king_square(us);
2156 clear_bit(&occ, f2);
2157 if (pos.type_of_piece_on(t1) == BISHOP)
2159 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2162 else if (pos.type_of_piece_on(t1) == ROOK)
2164 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2169 assert(pos.type_of_piece_on(t1) == QUEEN);
2170 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2178 // value_is_mate() checks if the given value is a mate one
2179 // eventually compensated for the ply.
2181 bool value_is_mate(Value value) {
2183 assert(abs(value) <= VALUE_INFINITE);
2185 return value <= value_mated_in(PLY_MAX)
2186 || value >= value_mate_in(PLY_MAX);
2190 // move_is_killer() checks if the given move is among the
2191 // killer moves of that ply.
2193 bool move_is_killer(Move m, const SearchStack& ss) {
2195 const Move* k = ss.killers;
2196 for (int i = 0; i < KILLER_MAX; i++, k++)
2204 // extension() decides whether a move should be searched with normal depth,
2205 // or with extended depth. Certain classes of moves (checking moves, in
2206 // particular) are searched with bigger depth than ordinary moves and in
2207 // any case are marked as 'dangerous'. Note that also if a move is not
2208 // extended, as example because the corresponding UCI option is set to zero,
2209 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2211 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2212 bool singleReply, bool mateThreat, bool* dangerous) {
2214 assert(m != MOVE_NONE);
2216 Depth result = Depth(0);
2217 *dangerous = check | singleReply | mateThreat;
2222 result += CheckExtension[pvNode];
2225 result += SingleReplyExtension[pvNode];
2228 result += MateThreatExtension[pvNode];
2231 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2233 if (pos.move_is_pawn_push_to_7th(m))
2235 result += PawnPushTo7thExtension[pvNode];
2238 if (pos.move_is_passed_pawn_push(m))
2240 result += PassedPawnExtension[pvNode];
2246 && pos.type_of_piece_on(move_to(m)) != PAWN
2247 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2248 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2249 && !move_is_promotion(m)
2252 result += PawnEndgameExtension[pvNode];
2258 && pos.type_of_piece_on(move_to(m)) != PAWN
2259 && pos.see_sign(m) >= 0)
2265 return Min(result, OnePly);
2269 // ok_to_do_nullmove() looks at the current position and decides whether
2270 // doing a 'null move' should be allowed. In order to avoid zugzwang
2271 // problems, null moves are not allowed when the side to move has very
2272 // little material left. Currently, the test is a bit too simple: Null
2273 // moves are avoided only when the side to move has only pawns left. It's
2274 // probably a good idea to avoid null moves in at least some more
2275 // complicated endgames, e.g. KQ vs KR. FIXME
2277 bool ok_to_do_nullmove(const Position& pos) {
2279 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2283 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2284 // non-tactical moves late in the move list close to the leaves are
2285 // candidates for pruning.
2287 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2289 assert(move_is_ok(m));
2290 assert(threat == MOVE_NONE || move_is_ok(threat));
2291 assert(!move_is_promotion(m));
2292 assert(!pos.move_is_check(m));
2293 assert(!pos.move_is_capture(m));
2294 assert(!pos.move_is_passed_pawn_push(m));
2295 assert(d >= OnePly);
2297 Square mfrom, mto, tfrom, tto;
2299 mfrom = move_from(m);
2301 tfrom = move_from(threat);
2302 tto = move_to(threat);
2304 // Case 1: Castling moves are never pruned
2305 if (move_is_castle(m))
2308 // Case 2: Don't prune moves which move the threatened piece
2309 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2312 // Case 3: If the threatened piece has value less than or equal to the
2313 // value of the threatening piece, don't prune move which defend it.
2314 if ( !PruneDefendingMoves
2315 && threat != MOVE_NONE
2316 && pos.move_is_capture(threat)
2317 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2318 || pos.type_of_piece_on(tfrom) == KING)
2319 && pos.move_attacks_square(m, tto))
2322 // Case 4: Don't prune moves with good history
2323 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2326 // Case 5: If the moving piece in the threatened move is a slider, don't
2327 // prune safe moves which block its ray.
2328 if ( !PruneBlockingMoves
2329 && threat != MOVE_NONE
2330 && piece_is_slider(pos.piece_on(tfrom))
2331 && bit_is_set(squares_between(tfrom, tto), mto)
2332 && pos.see_sign(m) >= 0)
2339 // ok_to_use_TT() returns true if a transposition table score
2340 // can be used at a given point in search.
2342 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2344 Value v = value_from_tt(tte->value(), ply);
2346 return ( tte->depth() >= depth
2347 || v >= Max(value_mate_in(100), beta)
2348 || v < Min(value_mated_in(100), beta))
2350 && ( (is_lower_bound(tte->type()) && v >= beta)
2351 || (is_upper_bound(tte->type()) && v < beta));
2355 // ok_to_history() returns true if a move m can be stored
2356 // in history. Should be a non capturing move nor a promotion.
2358 bool ok_to_history(const Position& pos, Move m) {
2360 return !pos.move_is_capture(m) && !move_is_promotion(m);
2364 // update_history() registers a good move that produced a beta-cutoff
2365 // in history and marks as failures all the other moves of that ply.
2367 void update_history(const Position& pos, Move m, Depth depth,
2368 Move movesSearched[], int moveCount) {
2370 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2372 for (int i = 0; i < moveCount - 1; i++)
2374 assert(m != movesSearched[i]);
2375 if (ok_to_history(pos, movesSearched[i]))
2376 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2381 // update_killers() add a good move that produced a beta-cutoff
2382 // among the killer moves of that ply.
2384 void update_killers(Move m, SearchStack& ss) {
2386 if (m == ss.killers[0])
2389 for (int i = KILLER_MAX - 1; i > 0; i--)
2390 ss.killers[i] = ss.killers[i - 1];
2395 // fail_high_ply_1() checks if some thread is currently resolving a fail
2396 // high at ply 1 at the node below the first root node. This information
2397 // is used for time managment.
2399 bool fail_high_ply_1() {
2401 for(int i = 0; i < ActiveThreads; i++)
2402 if (Threads[i].failHighPly1)
2409 // current_search_time() returns the number of milliseconds which have passed
2410 // since the beginning of the current search.
2412 int current_search_time() {
2413 return get_system_time() - SearchStartTime;
2417 // nps() computes the current nodes/second count.
2420 int t = current_search_time();
2421 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2425 // poll() performs two different functions: It polls for user input, and it
2426 // looks at the time consumed so far and decides if it's time to abort the
2431 static int lastInfoTime;
2432 int t = current_search_time();
2437 // We are line oriented, don't read single chars
2438 std::string command;
2439 if (!std::getline(std::cin, command))
2442 if (command == "quit")
2445 PonderSearch = false;
2449 else if (command == "stop")
2452 PonderSearch = false;
2454 else if (command == "ponderhit")
2457 // Print search information
2461 else if (lastInfoTime > t)
2462 // HACK: Must be a new search where we searched less than
2463 // NodesBetweenPolls nodes during the first second of search.
2466 else if (t - lastInfoTime >= 1000)
2473 if (dbg_show_hit_rate)
2474 dbg_print_hit_rate();
2476 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2477 << " time " << t << " hashfull " << TT.full() << std::endl;
2478 lock_release(&IOLock);
2479 if (ShowCurrentLine)
2480 Threads[0].printCurrentLine = true;
2482 // Should we stop the search?
2486 bool overTime = t > AbsoluteMaxSearchTime
2487 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2488 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2489 && t > 6*(MaxSearchTime + ExtraSearchTime));
2491 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2492 || (ExactMaxTime && t >= ExactMaxTime)
2493 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2498 // ponderhit() is called when the program is pondering (i.e. thinking while
2499 // it's the opponent's turn to move) in order to let the engine know that
2500 // it correctly predicted the opponent's move.
2504 int t = current_search_time();
2505 PonderSearch = false;
2506 if (Iteration >= 3 &&
2507 (!InfiniteSearch && (StopOnPonderhit ||
2508 t > AbsoluteMaxSearchTime ||
2509 (RootMoveNumber == 1 &&
2510 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2511 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2512 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2517 // print_current_line() prints the current line of search for a given
2518 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2520 void print_current_line(SearchStack ss[], int ply, int threadID) {
2522 assert(ply >= 0 && ply < PLY_MAX);
2523 assert(threadID >= 0 && threadID < ActiveThreads);
2525 if (!Threads[threadID].idle)
2528 std::cout << "info currline " << (threadID + 1);
2529 for (int p = 0; p < ply; p++)
2530 std::cout << " " << ss[p].currentMove;
2532 std::cout << std::endl;
2533 lock_release(&IOLock);
2535 Threads[threadID].printCurrentLine = false;
2536 if (threadID + 1 < ActiveThreads)
2537 Threads[threadID + 1].printCurrentLine = true;
2541 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2542 // while the program is pondering. The point is to work around a wrinkle in
2543 // the UCI protocol: When pondering, the engine is not allowed to give a
2544 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2545 // We simply wait here until one of these commands is sent, and return,
2546 // after which the bestmove and pondermove will be printed (in id_loop()).
2548 void wait_for_stop_or_ponderhit() {
2550 std::string command;
2554 if (!std::getline(std::cin, command))
2557 if (command == "quit")
2562 else if (command == "ponderhit" || command == "stop")
2568 // idle_loop() is where the threads are parked when they have no work to do.
2569 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2570 // object for which the current thread is the master.
2572 void idle_loop(int threadID, SplitPoint* waitSp) {
2573 assert(threadID >= 0 && threadID < THREAD_MAX);
2575 Threads[threadID].running = true;
2578 if(AllThreadsShouldExit && threadID != 0)
2581 // If we are not thinking, wait for a condition to be signaled instead
2582 // of wasting CPU time polling for work:
2583 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2584 #if !defined(_MSC_VER)
2585 pthread_mutex_lock(&WaitLock);
2586 if(Idle || threadID >= ActiveThreads)
2587 pthread_cond_wait(&WaitCond, &WaitLock);
2588 pthread_mutex_unlock(&WaitLock);
2590 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2594 // If this thread has been assigned work, launch a search
2595 if(Threads[threadID].workIsWaiting) {
2596 Threads[threadID].workIsWaiting = false;
2597 if(Threads[threadID].splitPoint->pvNode)
2598 sp_search_pv(Threads[threadID].splitPoint, threadID);
2600 sp_search(Threads[threadID].splitPoint, threadID);
2601 Threads[threadID].idle = true;
2604 // If this thread is the master of a split point and all threads have
2605 // finished their work at this split point, return from the idle loop.
2606 if(waitSp != NULL && waitSp->cpus == 0)
2610 Threads[threadID].running = false;
2614 // init_split_point_stack() is called during program initialization, and
2615 // initializes all split point objects.
2617 void init_split_point_stack() {
2618 for(int i = 0; i < THREAD_MAX; i++)
2619 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2620 SplitPointStack[i][j].parent = NULL;
2621 lock_init(&(SplitPointStack[i][j].lock), NULL);
2626 // destroy_split_point_stack() is called when the program exits, and
2627 // destroys all locks in the precomputed split point objects.
2629 void destroy_split_point_stack() {
2630 for(int i = 0; i < THREAD_MAX; i++)
2631 for(int j = 0; j < MaxActiveSplitPoints; j++)
2632 lock_destroy(&(SplitPointStack[i][j].lock));
2636 // thread_should_stop() checks whether the thread with a given threadID has
2637 // been asked to stop, directly or indirectly. This can happen if a beta
2638 // cutoff has occured in thre thread's currently active split point, or in
2639 // some ancestor of the current split point.
2641 bool thread_should_stop(int threadID) {
2642 assert(threadID >= 0 && threadID < ActiveThreads);
2646 if(Threads[threadID].stop)
2648 if(ActiveThreads <= 2)
2650 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2652 Threads[threadID].stop = true;
2659 // thread_is_available() checks whether the thread with threadID "slave" is
2660 // available to help the thread with threadID "master" at a split point. An
2661 // obvious requirement is that "slave" must be idle. With more than two
2662 // threads, this is not by itself sufficient: If "slave" is the master of
2663 // some active split point, it is only available as a slave to the other
2664 // threads which are busy searching the split point at the top of "slave"'s
2665 // split point stack (the "helpful master concept" in YBWC terminology).
2667 bool thread_is_available(int slave, int master) {
2668 assert(slave >= 0 && slave < ActiveThreads);
2669 assert(master >= 0 && master < ActiveThreads);
2670 assert(ActiveThreads > 1);
2672 if(!Threads[slave].idle || slave == master)
2675 if(Threads[slave].activeSplitPoints == 0)
2676 // No active split points means that the thread is available as a slave
2677 // for any other thread.
2680 if(ActiveThreads == 2)
2683 // Apply the "helpful master" concept if possible.
2684 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2691 // idle_thread_exists() tries to find an idle thread which is available as
2692 // a slave for the thread with threadID "master".
2694 bool idle_thread_exists(int master) {
2695 assert(master >= 0 && master < ActiveThreads);
2696 assert(ActiveThreads > 1);
2698 for(int i = 0; i < ActiveThreads; i++)
2699 if(thread_is_available(i, master))
2705 // split() does the actual work of distributing the work at a node between
2706 // several threads at PV nodes. If it does not succeed in splitting the
2707 // node (because no idle threads are available, or because we have no unused
2708 // split point objects), the function immediately returns false. If
2709 // splitting is possible, a SplitPoint object is initialized with all the
2710 // data that must be copied to the helper threads (the current position and
2711 // search stack, alpha, beta, the search depth, etc.), and we tell our
2712 // helper threads that they have been assigned work. This will cause them
2713 // to instantly leave their idle loops and call sp_search_pv(). When all
2714 // threads have returned from sp_search_pv (or, equivalently, when
2715 // splitPoint->cpus becomes 0), split() returns true.
2717 bool split(const Position& p, SearchStack* sstck, int ply,
2718 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2719 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2722 assert(sstck != NULL);
2723 assert(ply >= 0 && ply < PLY_MAX);
2724 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2725 assert(!pvNode || *alpha < *beta);
2726 assert(*beta <= VALUE_INFINITE);
2727 assert(depth > Depth(0));
2728 assert(master >= 0 && master < ActiveThreads);
2729 assert(ActiveThreads > 1);
2731 SplitPoint* splitPoint;
2736 // If no other thread is available to help us, or if we have too many
2737 // active split points, don't split.
2738 if(!idle_thread_exists(master) ||
2739 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2740 lock_release(&MPLock);
2744 // Pick the next available split point object from the split point stack
2745 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2746 Threads[master].activeSplitPoints++;
2748 // Initialize the split point object
2749 splitPoint->parent = Threads[master].splitPoint;
2750 splitPoint->finished = false;
2751 splitPoint->ply = ply;
2752 splitPoint->depth = depth;
2753 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2754 splitPoint->beta = *beta;
2755 splitPoint->pvNode = pvNode;
2756 splitPoint->dcCandidates = dcCandidates;
2757 splitPoint->bestValue = *bestValue;
2758 splitPoint->master = master;
2759 splitPoint->mp = mp;
2760 splitPoint->moves = *moves;
2761 splitPoint->cpus = 1;
2762 splitPoint->pos.copy(p);
2763 splitPoint->parentSstack = sstck;
2764 for(i = 0; i < ActiveThreads; i++)
2765 splitPoint->slaves[i] = 0;
2767 // Copy the current position and the search stack to the master thread
2768 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2769 Threads[master].splitPoint = splitPoint;
2771 // Make copies of the current position and search stack for each thread
2772 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2774 if(thread_is_available(i, master)) {
2775 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2776 Threads[i].splitPoint = splitPoint;
2777 splitPoint->slaves[i] = 1;
2781 // Tell the threads that they have work to do. This will make them leave
2783 for(i = 0; i < ActiveThreads; i++)
2784 if(i == master || splitPoint->slaves[i]) {
2785 Threads[i].workIsWaiting = true;
2786 Threads[i].idle = false;
2787 Threads[i].stop = false;
2790 lock_release(&MPLock);
2792 // Everything is set up. The master thread enters the idle loop, from
2793 // which it will instantly launch a search, because its workIsWaiting
2794 // slot is 'true'. We send the split point as a second parameter to the
2795 // idle loop, which means that the main thread will return from the idle
2796 // loop when all threads have finished their work at this split point
2797 // (i.e. when // splitPoint->cpus == 0).
2798 idle_loop(master, splitPoint);
2800 // We have returned from the idle loop, which means that all threads are
2801 // finished. Update alpha, beta and bestvalue, and return.
2803 if(pvNode) *alpha = splitPoint->alpha;
2804 *beta = splitPoint->beta;
2805 *bestValue = splitPoint->bestValue;
2806 Threads[master].stop = false;
2807 Threads[master].idle = false;
2808 Threads[master].activeSplitPoints--;
2809 Threads[master].splitPoint = splitPoint->parent;
2810 lock_release(&MPLock);
2816 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2817 // to start a new search from the root.
2819 void wake_sleeping_threads() {
2820 if(ActiveThreads > 1) {
2821 for(int i = 1; i < ActiveThreads; i++) {
2822 Threads[i].idle = true;
2823 Threads[i].workIsWaiting = false;
2825 #if !defined(_MSC_VER)
2826 pthread_mutex_lock(&WaitLock);
2827 pthread_cond_broadcast(&WaitCond);
2828 pthread_mutex_unlock(&WaitLock);
2830 for(int i = 1; i < THREAD_MAX; i++)
2831 SetEvent(SitIdleEvent[i]);
2837 // init_thread() is the function which is called when a new thread is
2838 // launched. It simply calls the idle_loop() function with the supplied
2839 // threadID. There are two versions of this function; one for POSIX threads
2840 // and one for Windows threads.
2842 #if !defined(_MSC_VER)
2844 void *init_thread(void *threadID) {
2845 idle_loop(*(int *)threadID, NULL);
2851 DWORD WINAPI init_thread(LPVOID threadID) {
2852 idle_loop(*(int *)threadID, NULL);