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 bool UseLSNFiltering;
206 bool looseOnTime = false;
207 int LSNTime; // In milliseconds
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;
234 bool StopOnPonderhit;
235 bool AbortSearch; // heavy SMP read access
240 bool PonderingEnabled;
243 // Show current line?
244 bool ShowCurrentLine;
248 std::ofstream LogFile;
250 // MP related variables
251 int ActiveThreads = 1;
252 Depth MinimumSplitDepth;
253 int MaxThreadsPerSplitPoint;
254 Thread Threads[THREAD_MAX];
257 bool AllThreadsShouldExit = false;
258 const int MaxActiveSplitPoints = 8;
259 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
262 #if !defined(_MSC_VER)
263 pthread_cond_t WaitCond;
264 pthread_mutex_t WaitLock;
266 HANDLE SitIdleEvent[THREAD_MAX];
269 // Node counters, used only by thread[0] but try to keep in different
270 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
272 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, const History& H);
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, History& H, 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 EasyMove = MOVE_NONE;
358 for (int i = 0; i < THREAD_MAX; i++)
360 Threads[i].nodes = 0ULL;
361 Threads[i].failHighPly1 = false;
364 InfiniteSearch = infinite;
365 PonderSearch = ponder;
366 StopOnPonderhit = false;
372 ExactMaxTime = maxTime;
374 // Read UCI option values
375 TT.set_size(get_option_value_int("Hash"));
376 if (button_was_pressed("Clear Hash"))
379 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 UseLSNFiltering = get_option_value_bool("LSN filtering");
411 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
412 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
414 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
415 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
417 read_weights(pos.side_to_move());
419 int newActiveThreads = get_option_value_int("Threads");
420 if (newActiveThreads != ActiveThreads)
422 ActiveThreads = newActiveThreads;
423 init_eval(ActiveThreads);
426 // Wake up sleeping threads
427 wake_sleeping_threads();
429 for (int i = 1; i < ActiveThreads; i++)
430 assert(thread_is_available(i, 0));
433 int myTime = time[side_to_move];
434 int myIncrement = increment[side_to_move];
436 if (!movesToGo) // Sudden death time control
440 MaxSearchTime = myTime / 30 + myIncrement;
441 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
442 } else { // Blitz game without increment
443 MaxSearchTime = myTime / 30;
444 AbsoluteMaxSearchTime = myTime / 8;
447 else // (x moves) / (y minutes)
451 MaxSearchTime = myTime / 2;
452 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
454 MaxSearchTime = myTime / Min(movesToGo, 20);
455 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
459 if (PonderingEnabled)
461 MaxSearchTime += MaxSearchTime / 4;
462 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
465 // Fixed depth or fixed number of nodes?
468 InfiniteSearch = true; // HACK
473 NodesBetweenPolls = Min(MaxNodes, 30000);
474 InfiniteSearch = true; // HACK
477 NodesBetweenPolls = 30000;
480 // Write information to search log file
482 LogFile << "Searching: " << pos.to_fen() << std::endl
483 << "infinite: " << infinite
484 << " ponder: " << ponder
485 << " time: " << myTime
486 << " increment: " << myIncrement
487 << " moves to go: " << movesToGo << std::endl;
490 // We're ready to start thinking. Call the iterative deepening loop function
493 Value v = id_loop(pos, searchMoves);
494 looseOnTime = ( UseLSNFiltering
501 looseOnTime = 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);
632 for (int i = 0; i < THREAD_MAX; i++)
633 Threads[i].H.clear();
635 for (int i = 0; i < 3; i++)
640 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
643 EasyMove = rml.scan_for_easy_move();
645 // Iterative deepening loop
646 while (Iteration < PLY_MAX)
648 // Initialize iteration
651 BestMoveChangesByIteration[Iteration] = 0;
655 std::cout << "info depth " << Iteration << std::endl;
657 // Calculate dynamic search window based on previous iterations
660 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
662 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
663 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
665 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
667 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
668 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
672 alpha = - VALUE_INFINITE;
673 beta = VALUE_INFINITE;
676 // Search to the current depth
677 Value value = root_search(p, ss, rml, alpha, beta);
679 // Write PV to transposition table, in case the relevant entries have
680 // been overwritten during the search.
681 TT.insert_pv(p, ss[0].pv);
684 break; // Value cannot be trusted. Break out immediately!
686 //Save info about search result
687 Value speculatedValue;
690 Value delta = value - IterationInfo[Iteration - 1].value;
697 speculatedValue = value + delta;
698 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
700 else if (value <= alpha)
702 assert(value == alpha);
706 speculatedValue = value + delta;
707 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
709 speculatedValue = value;
711 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
712 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
714 // Erase the easy move if it differs from the new best move
715 if (ss[0].pv[0] != EasyMove)
716 EasyMove = MOVE_NONE;
723 bool stopSearch = false;
725 // Stop search early if there is only a single legal move
726 if (Iteration >= 6 && rml.move_count() == 1)
729 // Stop search early when the last two iterations returned a mate score
731 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
732 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
735 // Stop search early if one move seems to be much better than the rest
736 int64_t nodes = nodes_searched();
740 && EasyMove == ss[0].pv[0]
741 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
742 && current_search_time() > MaxSearchTime / 16)
743 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
744 && current_search_time() > MaxSearchTime / 32)))
747 // Add some extra time if the best move has changed during the last two iterations
748 if (Iteration > 5 && Iteration <= 50)
749 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
750 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
752 // Stop search if most of MaxSearchTime is consumed at the end of the
753 // iteration. We probably don't have enough time to search the first
754 // move at the next iteration anyway.
755 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
760 //FIXME: Implement fail-low emergency measures
764 StopOnPonderhit = true;
768 if (MaxDepth && Iteration >= MaxDepth)
774 // If we are pondering, we shouldn't print the best move before we
777 wait_for_stop_or_ponderhit();
779 // Print final search statistics
780 std::cout << "info nodes " << nodes_searched()
782 << " time " << current_search_time()
783 << " hashfull " << TT.full() << std::endl;
785 // Print the best move and the ponder move to the standard output
786 if (ss[0].pv[0] == MOVE_NONE)
788 ss[0].pv[0] = rml.get_move(0);
789 ss[0].pv[1] = MOVE_NONE;
791 std::cout << "bestmove " << ss[0].pv[0];
792 if (ss[0].pv[1] != MOVE_NONE)
793 std::cout << " ponder " << ss[0].pv[1];
795 std::cout << std::endl;
800 dbg_print_mean(LogFile);
802 if (dbg_show_hit_rate)
803 dbg_print_hit_rate(LogFile);
806 LogFile << "Nodes: " << nodes_searched() << std::endl
807 << "Nodes/second: " << nps() << std::endl
808 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
810 p.do_move(ss[0].pv[0], st);
811 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
812 << std::endl << std::endl;
814 return rml.get_move_score(0);
818 // root_search() is the function which searches the root node. It is
819 // similar to search_pv except that it uses a different move ordering
820 // scheme (perhaps we should try to use this at internal PV nodes, too?)
821 // and prints some information to the standard output.
823 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
825 Value oldAlpha = alpha;
827 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
829 // Loop through all the moves in the root move list
830 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
834 // We failed high, invalidate and skip next moves, leave node-counters
835 // and beta-counters as they are and quickly return, we will try to do
836 // a research at the next iteration with a bigger aspiration window.
837 rml.set_move_score(i, -VALUE_INFINITE);
845 RootMoveNumber = i + 1;
848 // Remember the node count before the move is searched. The node counts
849 // are used to sort the root moves at the next iteration.
850 nodes = nodes_searched();
852 // Reset beta cut-off counters
855 // Pick the next root move, and print the move and the move number to
856 // the standard output.
857 move = ss[0].currentMove = rml.get_move(i);
858 if (current_search_time() >= 1000)
859 std::cout << "info currmove " << move
860 << " currmovenumber " << i + 1 << std::endl;
862 // Decide search depth for this move
864 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
865 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
867 // Make the move, and search it
868 pos.do_move(move, st, dcCandidates);
872 // Aspiration window is disabled in multi-pv case
874 alpha = -VALUE_INFINITE;
876 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
877 // If the value has dropped a lot compared to the last iteration,
878 // set the boolean variable Problem to true. This variable is used
879 // for time managment: When Problem is true, we try to complete the
880 // current iteration before playing a move.
881 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
883 if (Problem && StopOnPonderhit)
884 StopOnPonderhit = false;
888 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
891 // Fail high! Set the boolean variable FailHigh to true, and
892 // re-search the move with a big window. The variable FailHigh is
893 // used for time managment: We try to avoid aborting the search
894 // prematurely during a fail high research.
896 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
902 // Finished searching the move. If AbortSearch is true, the search
903 // was aborted because the user interrupted the search or because we
904 // ran out of time. In this case, the return value of the search cannot
905 // be trusted, and we break out of the loop without updating the best
910 // Remember the node count for this move. The node counts are used to
911 // sort the root moves at the next iteration.
912 rml.set_move_nodes(i, nodes_searched() - nodes);
914 // Remember the beta-cutoff statistics
916 BetaCounter.read(pos.side_to_move(), our, their);
917 rml.set_beta_counters(i, our, their);
919 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
921 if (value <= alpha && i >= MultiPV)
922 rml.set_move_score(i, -VALUE_INFINITE);
925 // PV move or new best move!
928 rml.set_move_score(i, value);
930 rml.set_move_pv(i, ss[0].pv);
934 // We record how often the best move has been changed in each
935 // iteration. This information is used for time managment: When
936 // the best move changes frequently, we allocate some more time.
938 BestMoveChangesByIteration[Iteration]++;
940 // Print search information to the standard output
941 std::cout << "info depth " << Iteration
942 << " score " << value_to_string(value)
943 << " time " << current_search_time()
944 << " nodes " << nodes_searched()
948 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
949 std::cout << ss[0].pv[j] << " ";
951 std::cout << std::endl;
954 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
960 // Reset the global variable Problem to false if the value isn't too
961 // far below the final value from the last iteration.
962 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
968 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
971 std::cout << "info multipv " << j + 1
972 << " score " << value_to_string(rml.get_move_score(j))
973 << " depth " << ((j <= i)? Iteration : Iteration - 1)
974 << " time " << current_search_time()
975 << " nodes " << nodes_searched()
979 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
980 std::cout << rml.get_move_pv(j, k) << " ";
982 std::cout << std::endl;
984 alpha = rml.get_move_score(Min(i, MultiPV-1));
986 } // New best move case
988 assert(alpha >= oldAlpha);
990 FailLow = (alpha == oldAlpha);
996 // search_pv() is the main search function for PV nodes.
998 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
999 Depth depth, int ply, int threadID) {
1001 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1002 assert(beta > alpha && beta <= VALUE_INFINITE);
1003 assert(ply >= 0 && ply < PLY_MAX);
1004 assert(threadID >= 0 && threadID < ActiveThreads);
1007 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1009 // Initialize, and make an early exit in case of an aborted search,
1010 // an instant draw, maximum ply reached, etc.
1011 init_node(ss, ply, threadID);
1013 // After init_node() that calls poll()
1014 if (AbortSearch || thread_should_stop(threadID))
1022 if (ply >= PLY_MAX - 1)
1023 return evaluate(pos, ei, threadID);
1025 // Mate distance pruning
1026 Value oldAlpha = alpha;
1027 alpha = Max(value_mated_in(ply), alpha);
1028 beta = Min(value_mate_in(ply+1), beta);
1032 // Transposition table lookup. At PV nodes, we don't use the TT for
1033 // pruning, but only for move ordering.
1034 const TTEntry* tte = TT.retrieve(pos.get_key());
1035 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1037 // Go with internal iterative deepening if we don't have a TT move
1038 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1040 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1041 ttMove = ss[ply].pv[ply];
1044 // Initialize a MovePicker object for the current position, and prepare
1045 // to search all moves
1046 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1048 Move move, movesSearched[256];
1050 Value value, bestValue = -VALUE_INFINITE;
1051 Bitboard dcCandidates = mp.discovered_check_candidates();
1052 Color us = pos.side_to_move();
1053 bool isCheck = pos.is_check();
1054 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1056 // Loop through all legal moves until no moves remain or a beta cutoff
1058 while ( alpha < beta
1059 && (move = mp.get_next_move()) != MOVE_NONE
1060 && !thread_should_stop(threadID))
1062 assert(move_is_ok(move));
1064 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1065 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1066 bool moveIsCapture = pos.move_is_capture(move);
1068 movesSearched[moveCount++] = ss[ply].currentMove = move;
1070 // Decide the new search depth
1072 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1073 Depth newDepth = depth - OnePly + ext;
1075 // Make and search the move
1077 pos.do_move(move, st, dcCandidates);
1079 if (moveCount == 1) // The first move in list is the PV
1080 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1083 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1084 // if the move fails high will be re-searched at full depth.
1085 if ( depth >= 2*OnePly
1086 && moveCount >= LMRPVMoves
1089 && !move_is_promotion(move)
1090 && !move_is_castle(move)
1091 && !move_is_killer(move, ss[ply]))
1093 ss[ply].reduction = OnePly;
1094 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1097 value = alpha + 1; // Just to trigger next condition
1099 if (value > alpha) // Go with full depth non-pv search
1101 ss[ply].reduction = Depth(0);
1102 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1103 if (value > alpha && value < beta)
1105 // When the search fails high at ply 1 while searching the first
1106 // move at the root, set the flag failHighPly1. This is used for
1107 // time managment: We don't want to stop the search early in
1108 // such cases, because resolving the fail high at ply 1 could
1109 // result in a big drop in score at the root.
1110 if (ply == 1 && RootMoveNumber == 1)
1111 Threads[threadID].failHighPly1 = true;
1113 // A fail high occurred. Re-search at full window (pv search)
1114 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1115 Threads[threadID].failHighPly1 = false;
1119 pos.undo_move(move);
1121 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1124 if (value > bestValue)
1131 if (value == value_mate_in(ply + 1))
1132 ss[ply].mateKiller = move;
1134 // If we are at ply 1, and we are searching the first root move at
1135 // ply 0, set the 'Problem' variable if the score has dropped a lot
1136 // (from the computer's point of view) since the previous iteration.
1139 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1144 if ( ActiveThreads > 1
1146 && depth >= MinimumSplitDepth
1148 && idle_thread_exists(threadID)
1150 && !thread_should_stop(threadID)
1151 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1152 &moveCount, &mp, dcCandidates, threadID, true))
1156 // All legal moves have been searched. A special case: If there were
1157 // no legal moves, it must be mate or stalemate.
1159 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1161 // If the search is not aborted, update the transposition table,
1162 // history counters, and killer moves.
1163 if (AbortSearch || thread_should_stop(threadID))
1166 if (bestValue <= oldAlpha)
1167 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1169 else if (bestValue >= beta)
1171 BetaCounter.add(pos.side_to_move(), depth, threadID);
1172 Move m = ss[ply].pv[ply];
1173 if (ok_to_history(pos, m)) // Only non capture moves are considered
1175 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1176 update_killers(m, ss[ply]);
1178 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1181 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1187 // search() is the search function for zero-width nodes.
1189 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1190 int ply, bool allowNullmove, int threadID) {
1192 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1193 assert(ply >= 0 && ply < PLY_MAX);
1194 assert(threadID >= 0 && threadID < ActiveThreads);
1197 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1199 // Initialize, and make an early exit in case of an aborted search,
1200 // an instant draw, maximum ply reached, etc.
1201 init_node(ss, ply, threadID);
1203 // After init_node() that calls poll()
1204 if (AbortSearch || thread_should_stop(threadID))
1212 if (ply >= PLY_MAX - 1)
1213 return evaluate(pos, ei, threadID);
1215 // Mate distance pruning
1216 if (value_mated_in(ply) >= beta)
1219 if (value_mate_in(ply + 1) < beta)
1222 // Transposition table lookup
1223 const TTEntry* tte = TT.retrieve(pos.get_key());
1224 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1226 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1228 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1229 return value_from_tt(tte->value(), ply);
1232 Value approximateEval = quick_evaluate(pos);
1233 bool mateThreat = false;
1234 bool isCheck = pos.is_check();
1240 && !value_is_mate(beta)
1241 && ok_to_do_nullmove(pos)
1242 && approximateEval >= beta - NullMoveMargin)
1244 ss[ply].currentMove = MOVE_NULL;
1247 pos.do_null_move(st);
1248 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1250 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1252 pos.undo_null_move();
1254 if (value_is_mate(nullValue))
1256 /* Do not return unproven mates */
1258 else if (nullValue >= beta)
1260 if (depth < 6 * OnePly)
1263 // Do zugzwang verification search
1264 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1268 // The null move failed low, which means that we may be faced with
1269 // some kind of threat. If the previous move was reduced, check if
1270 // the move that refuted the null move was somehow connected to the
1271 // move which was reduced. If a connection is found, return a fail
1272 // low score (which will cause the reduced move to fail high in the
1273 // parent node, which will trigger a re-search with full depth).
1274 if (nullValue == value_mated_in(ply + 2))
1277 ss[ply].threatMove = ss[ply + 1].currentMove;
1278 if ( depth < ThreatDepth
1279 && ss[ply - 1].reduction
1280 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1284 // Null move search not allowed, try razoring
1285 else if ( !value_is_mate(beta)
1286 && depth < RazorDepth
1287 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1288 && ss[ply - 1].currentMove != MOVE_NULL
1289 && ttMove == MOVE_NONE
1290 && !pos.has_pawn_on_7th(pos.side_to_move()))
1292 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1293 if (v < beta - RazorMargins[int(depth) - 2])
1297 // Go with internal iterative deepening if we don't have a TT move
1298 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1299 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1301 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1302 ttMove = ss[ply].pv[ply];
1305 // Initialize a MovePicker object for the current position, and prepare
1306 // to search all moves.
1307 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1309 Move move, movesSearched[256];
1311 Value value, bestValue = -VALUE_INFINITE;
1312 Bitboard dcCandidates = mp.discovered_check_candidates();
1313 Value futilityValue = VALUE_NONE;
1314 bool useFutilityPruning = depth < SelectiveDepth
1317 // Loop through all legal moves until no moves remain or a beta cutoff
1319 while ( bestValue < beta
1320 && (move = mp.get_next_move()) != MOVE_NONE
1321 && !thread_should_stop(threadID))
1323 assert(move_is_ok(move));
1325 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1326 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1327 bool moveIsCapture = pos.move_is_capture(move);
1329 movesSearched[moveCount++] = ss[ply].currentMove = move;
1331 // Decide the new search depth
1333 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1334 Depth newDepth = depth - OnePly + ext;
1337 if ( useFutilityPruning
1340 && !move_is_promotion(move))
1342 // History pruning. See ok_to_prune() definition
1343 if ( moveCount >= 2 + int(depth)
1344 && ok_to_prune(pos, move, ss[ply].threatMove, depth, Threads[threadID].H))
1347 // Value based pruning
1348 if (approximateEval < beta)
1350 if (futilityValue == VALUE_NONE)
1351 futilityValue = evaluate(pos, ei, threadID)
1352 + FutilityMargins[int(depth) - 2];
1354 if (futilityValue < beta)
1356 if (futilityValue > bestValue)
1357 bestValue = futilityValue;
1363 // Make and search the move
1365 pos.do_move(move, st, dcCandidates);
1367 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1368 // if the move fails high will be re-searched at full depth.
1369 if ( depth >= 2*OnePly
1370 && moveCount >= LMRNonPVMoves
1373 && !move_is_promotion(move)
1374 && !move_is_castle(move)
1375 && !move_is_killer(move, ss[ply]))
1377 ss[ply].reduction = OnePly;
1378 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1381 value = beta; // Just to trigger next condition
1383 if (value >= beta) // Go with full depth non-pv search
1385 ss[ply].reduction = Depth(0);
1386 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1388 pos.undo_move(move);
1390 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1393 if (value > bestValue)
1399 if (value == value_mate_in(ply + 1))
1400 ss[ply].mateKiller = move;
1404 if ( ActiveThreads > 1
1406 && depth >= MinimumSplitDepth
1408 && idle_thread_exists(threadID)
1410 && !thread_should_stop(threadID)
1411 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1412 &mp, dcCandidates, threadID, false))
1416 // All legal moves have been searched. A special case: If there were
1417 // no legal moves, it must be mate or stalemate.
1419 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1421 // If the search is not aborted, update the transposition table,
1422 // history counters, and killer moves.
1423 if (AbortSearch || thread_should_stop(threadID))
1426 if (bestValue < beta)
1427 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1430 BetaCounter.add(pos.side_to_move(), depth, threadID);
1431 Move m = ss[ply].pv[ply];
1432 if (ok_to_history(pos, m)) // Only non capture moves are considered
1434 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1435 update_killers(m, ss[ply]);
1437 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1440 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1446 // qsearch() is the quiescence search function, which is called by the main
1447 // search function when the remaining depth is zero (or, to be more precise,
1448 // less than OnePly).
1450 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1451 Depth depth, int ply, int threadID) {
1453 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1454 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1456 assert(ply >= 0 && ply < PLY_MAX);
1457 assert(threadID >= 0 && threadID < ActiveThreads);
1459 // Initialize, and make an early exit in case of an aborted search,
1460 // an instant draw, maximum ply reached, etc.
1461 init_node(ss, ply, threadID);
1463 // After init_node() that calls poll()
1464 if (AbortSearch || thread_should_stop(threadID))
1470 // Transposition table lookup, only when not in PV
1471 TTEntry* tte = NULL;
1472 bool pvNode = (beta - alpha != 1);
1475 tte = TT.retrieve(pos.get_key());
1476 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1478 assert(tte->type() != VALUE_TYPE_EVAL);
1480 return value_from_tt(tte->value(), ply);
1483 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1485 // Evaluate the position statically
1488 bool isCheck = pos.is_check();
1489 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1492 staticValue = -VALUE_INFINITE;
1494 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1496 // Use the cached evaluation score if possible
1497 assert(tte->value() == evaluate(pos, ei, threadID));
1498 assert(ei.futilityMargin == Value(0));
1500 staticValue = tte->value();
1503 staticValue = evaluate(pos, ei, threadID);
1505 if (ply == PLY_MAX - 1)
1506 return evaluate(pos, ei, threadID);
1508 // Initialize "stand pat score", and return it immediately if it is
1510 Value bestValue = staticValue;
1512 if (bestValue >= beta)
1514 // Store the score to avoid a future costly evaluation() call
1515 if (!isCheck && !tte && ei.futilityMargin == 0)
1516 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1521 if (bestValue > alpha)
1524 // Initialize a MovePicker object for the current position, and prepare
1525 // to search the moves. Because the depth is <= 0 here, only captures,
1526 // queen promotions and checks (only if depth == 0) will be generated.
1527 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H);
1530 Bitboard dcCandidates = mp.discovered_check_candidates();
1531 Color us = pos.side_to_move();
1532 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1534 // Loop through the moves until no moves remain or a beta cutoff
1536 while ( alpha < beta
1537 && (move = mp.get_next_move()) != MOVE_NONE)
1539 assert(move_is_ok(move));
1542 ss[ply].currentMove = move;
1548 && !move_is_promotion(move)
1549 && !pos.move_is_check(move, dcCandidates)
1550 && !pos.move_is_passed_pawn_push(move))
1552 Value futilityValue = staticValue
1553 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1554 pos.endgame_value_of_piece_on(move_to(move)))
1555 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1557 + ei.futilityMargin;
1559 if (futilityValue < alpha)
1561 if (futilityValue > bestValue)
1562 bestValue = futilityValue;
1567 // Don't search captures and checks with negative SEE values
1569 && !move_is_promotion(move)
1570 && (pos.midgame_value_of_piece_on(move_from(move)) >
1571 pos.midgame_value_of_piece_on(move_to(move)))
1572 && pos.see(move) < 0)
1575 // Make and search the move.
1577 pos.do_move(move, st, dcCandidates);
1578 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1579 pos.undo_move(move);
1581 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1584 if (value > bestValue)
1595 // All legal moves have been searched. A special case: If we're in check
1596 // and no legal moves were found, it is checkmate.
1597 if (pos.is_check() && moveCount == 0) // Mate!
1598 return value_mated_in(ply);
1600 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1602 // Update transposition table
1603 Move m = ss[ply].pv[ply];
1606 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1607 if (bestValue < beta)
1608 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1610 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1613 // Update killers only for good check moves
1614 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1615 update_killers(m, ss[ply]);
1621 // sp_search() is used to search from a split point. This function is called
1622 // by each thread working at the split point. It is similar to the normal
1623 // search() function, but simpler. Because we have already probed the hash
1624 // table, done a null move search, and searched the first move before
1625 // splitting, we don't have to repeat all this work in sp_search(). We
1626 // also don't need to store anything to the hash table here: This is taken
1627 // care of after we return from the split point.
1629 void sp_search(SplitPoint* sp, int threadID) {
1631 assert(threadID >= 0 && threadID < ActiveThreads);
1632 assert(ActiveThreads > 1);
1634 Position pos = Position(sp->pos);
1635 SearchStack* ss = sp->sstack[threadID];
1638 bool isCheck = pos.is_check();
1639 bool useFutilityPruning = sp->depth < SelectiveDepth
1642 while ( sp->bestValue < sp->beta
1643 && !thread_should_stop(threadID)
1644 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1646 assert(move_is_ok(move));
1648 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1649 bool moveIsCapture = pos.move_is_capture(move);
1651 lock_grab(&(sp->lock));
1652 int moveCount = ++sp->moves;
1653 lock_release(&(sp->lock));
1655 ss[sp->ply].currentMove = move;
1657 // Decide the new search depth.
1659 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1660 Depth newDepth = sp->depth - OnePly + ext;
1663 if ( useFutilityPruning
1666 && !move_is_promotion(move)
1667 && moveCount >= 2 + int(sp->depth)
1668 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth, Threads[threadID].H))
1671 // Make and search the move.
1673 pos.do_move(move, st, sp->dcCandidates);
1675 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1676 // if the move fails high will be re-searched at full depth.
1678 && moveCount >= LMRNonPVMoves
1680 && !move_is_promotion(move)
1681 && !move_is_castle(move)
1682 && !move_is_killer(move, ss[sp->ply]))
1684 ss[sp->ply].reduction = OnePly;
1685 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1688 value = sp->beta; // Just to trigger next condition
1690 if (value >= sp->beta) // Go with full depth non-pv search
1692 ss[sp->ply].reduction = Depth(0);
1693 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1695 pos.undo_move(move);
1697 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1699 if (thread_should_stop(threadID))
1703 lock_grab(&(sp->lock));
1704 if (value > sp->bestValue && !thread_should_stop(threadID))
1706 sp->bestValue = value;
1707 if (sp->bestValue >= sp->beta)
1709 sp_update_pv(sp->parentSstack, ss, sp->ply);
1710 for (int i = 0; i < ActiveThreads; i++)
1711 if (i != threadID && (i == sp->master || sp->slaves[i]))
1712 Threads[i].stop = true;
1714 sp->finished = true;
1717 lock_release(&(sp->lock));
1720 lock_grab(&(sp->lock));
1722 // If this is the master thread and we have been asked to stop because of
1723 // a beta cutoff higher up in the tree, stop all slave threads.
1724 if (sp->master == threadID && thread_should_stop(threadID))
1725 for (int i = 0; i < ActiveThreads; i++)
1727 Threads[i].stop = true;
1730 sp->slaves[threadID] = 0;
1732 lock_release(&(sp->lock));
1736 // sp_search_pv() is used to search from a PV split point. This function
1737 // is called by each thread working at the split point. It is similar to
1738 // the normal search_pv() function, but simpler. Because we have already
1739 // probed the hash table and searched the first move before splitting, we
1740 // don't have to repeat all this work in sp_search_pv(). We also don't
1741 // need to store anything to the hash table here: This is taken care of
1742 // after we return from the split point.
1744 void sp_search_pv(SplitPoint* sp, int threadID) {
1746 assert(threadID >= 0 && threadID < ActiveThreads);
1747 assert(ActiveThreads > 1);
1749 Position pos = Position(sp->pos);
1750 SearchStack* ss = sp->sstack[threadID];
1754 while ( sp->alpha < sp->beta
1755 && !thread_should_stop(threadID)
1756 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1758 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1759 bool moveIsCapture = pos.move_is_capture(move);
1761 assert(move_is_ok(move));
1763 lock_grab(&(sp->lock));
1764 int moveCount = ++sp->moves;
1765 lock_release(&(sp->lock));
1767 ss[sp->ply].currentMove = move;
1769 // Decide the new search depth.
1771 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1772 Depth newDepth = sp->depth - OnePly + ext;
1774 // Make and search the move.
1776 pos.do_move(move, st, sp->dcCandidates);
1778 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1779 // if the move fails high will be re-searched at full depth.
1781 && moveCount >= LMRPVMoves
1783 && !move_is_promotion(move)
1784 && !move_is_castle(move)
1785 && !move_is_killer(move, ss[sp->ply]))
1787 ss[sp->ply].reduction = OnePly;
1788 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1791 value = sp->alpha + 1; // Just to trigger next condition
1793 if (value > sp->alpha) // Go with full depth non-pv search
1795 ss[sp->ply].reduction = Depth(0);
1796 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1798 if (value > sp->alpha && value < sp->beta)
1800 // When the search fails high at ply 1 while searching the first
1801 // move at the root, set the flag failHighPly1. This is used for
1802 // time managment: We don't want to stop the search early in
1803 // such cases, because resolving the fail high at ply 1 could
1804 // result in a big drop in score at the root.
1805 if (sp->ply == 1 && RootMoveNumber == 1)
1806 Threads[threadID].failHighPly1 = true;
1808 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1809 Threads[threadID].failHighPly1 = false;
1812 pos.undo_move(move);
1814 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1816 if (thread_should_stop(threadID))
1820 lock_grab(&(sp->lock));
1821 if (value > sp->bestValue && !thread_should_stop(threadID))
1823 sp->bestValue = value;
1824 if (value > sp->alpha)
1827 sp_update_pv(sp->parentSstack, ss, sp->ply);
1828 if (value == value_mate_in(sp->ply + 1))
1829 ss[sp->ply].mateKiller = move;
1831 if (value >= sp->beta)
1833 for (int i = 0; i < ActiveThreads; i++)
1834 if (i != threadID && (i == sp->master || sp->slaves[i]))
1835 Threads[i].stop = true;
1837 sp->finished = true;
1840 // If we are at ply 1, and we are searching the first root move at
1841 // ply 0, set the 'Problem' variable if the score has dropped a lot
1842 // (from the computer's point of view) since the previous iteration.
1845 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1848 lock_release(&(sp->lock));
1851 lock_grab(&(sp->lock));
1853 // If this is the master thread and we have been asked to stop because of
1854 // a beta cutoff higher up in the tree, stop all slave threads.
1855 if (sp->master == threadID && thread_should_stop(threadID))
1856 for (int i = 0; i < ActiveThreads; i++)
1858 Threads[i].stop = true;
1861 sp->slaves[threadID] = 0;
1863 lock_release(&(sp->lock));
1866 /// The BetaCounterType class
1868 BetaCounterType::BetaCounterType() { clear(); }
1870 void BetaCounterType::clear() {
1872 for (int i = 0; i < THREAD_MAX; i++)
1873 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1876 void BetaCounterType::add(Color us, Depth d, int threadID) {
1878 // Weighted count based on depth
1879 Threads[threadID].betaCutOffs[us] += unsigned(d);
1882 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1885 for (int i = 0; i < THREAD_MAX; i++)
1887 our += Threads[i].betaCutOffs[us];
1888 their += Threads[i].betaCutOffs[opposite_color(us)];
1893 /// The RootMove class
1897 RootMove::RootMove() {
1898 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1901 // RootMove::operator<() is the comparison function used when
1902 // sorting the moves. A move m1 is considered to be better
1903 // than a move m2 if it has a higher score, or if the moves
1904 // have equal score but m1 has the higher node count.
1906 bool RootMove::operator<(const RootMove& m) {
1908 if (score != m.score)
1909 return (score < m.score);
1911 return theirBeta <= m.theirBeta;
1914 /// The RootMoveList class
1918 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1920 MoveStack mlist[MaxRootMoves];
1921 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1923 // Generate all legal moves
1924 int lm_count = generate_legal_moves(pos, mlist);
1926 // Add each move to the moves[] array
1927 for (int i = 0; i < lm_count; i++)
1929 bool includeMove = includeAllMoves;
1931 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1932 includeMove = (searchMoves[k] == mlist[i].move);
1937 // Find a quick score for the move
1939 SearchStack ss[PLY_MAX_PLUS_2];
1941 moves[count].move = mlist[i].move;
1942 pos.do_move(moves[count].move, st);
1943 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1944 pos.undo_move(moves[count].move);
1945 moves[count].pv[0] = moves[count].move;
1946 moves[count].pv[1] = MOVE_NONE; // FIXME
1953 // Simple accessor methods for the RootMoveList class
1955 inline Move RootMoveList::get_move(int moveNum) const {
1956 return moves[moveNum].move;
1959 inline Value RootMoveList::get_move_score(int moveNum) const {
1960 return moves[moveNum].score;
1963 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1964 moves[moveNum].score = score;
1967 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1968 moves[moveNum].nodes = nodes;
1969 moves[moveNum].cumulativeNodes += nodes;
1972 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1973 moves[moveNum].ourBeta = our;
1974 moves[moveNum].theirBeta = their;
1977 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1979 for(j = 0; pv[j] != MOVE_NONE; j++)
1980 moves[moveNum].pv[j] = pv[j];
1981 moves[moveNum].pv[j] = MOVE_NONE;
1984 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1985 return moves[moveNum].pv[i];
1988 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1989 return moves[moveNum].cumulativeNodes;
1992 inline int RootMoveList::move_count() const {
1997 // RootMoveList::scan_for_easy_move() is called at the end of the first
1998 // iteration, and is used to detect an "easy move", i.e. a move which appears
1999 // to be much bester than all the rest. If an easy move is found, the move
2000 // is returned, otherwise the function returns MOVE_NONE. It is very
2001 // important that this function is called at the right moment: The code
2002 // assumes that the first iteration has been completed and the moves have
2003 // been sorted. This is done in RootMoveList c'tor.
2005 Move RootMoveList::scan_for_easy_move() const {
2012 // moves are sorted so just consider the best and the second one
2013 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2019 // RootMoveList::sort() sorts the root move list at the beginning of a new
2022 inline void RootMoveList::sort() {
2024 sort_multipv(count - 1); // all items
2028 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2029 // list by their scores and depths. It is used to order the different PVs
2030 // correctly in MultiPV mode.
2032 void RootMoveList::sort_multipv(int n) {
2034 for (int i = 1; i <= n; i++)
2036 RootMove rm = moves[i];
2038 for (j = i; j > 0 && moves[j-1] < rm; j--)
2039 moves[j] = moves[j-1];
2045 // init_node() is called at the beginning of all the search functions
2046 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2047 // stack object corresponding to the current node. Once every
2048 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2049 // for user input and checks whether it is time to stop the search.
2051 void init_node(SearchStack ss[], int ply, int threadID) {
2053 assert(ply >= 0 && ply < PLY_MAX);
2054 assert(threadID >= 0 && threadID < ActiveThreads);
2056 Threads[threadID].nodes++;
2061 if (NodesSincePoll >= NodesBetweenPolls)
2068 ss[ply+2].initKillers();
2070 if (Threads[threadID].printCurrentLine)
2071 print_current_line(ss, ply, threadID);
2075 // update_pv() is called whenever a search returns a value > alpha. It
2076 // updates the PV in the SearchStack object corresponding to the current
2079 void update_pv(SearchStack ss[], int ply) {
2080 assert(ply >= 0 && ply < PLY_MAX);
2082 ss[ply].pv[ply] = ss[ply].currentMove;
2084 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2085 ss[ply].pv[p] = ss[ply+1].pv[p];
2086 ss[ply].pv[p] = MOVE_NONE;
2090 // sp_update_pv() is a variant of update_pv for use at split points. The
2091 // difference between the two functions is that sp_update_pv also updates
2092 // the PV at the parent node.
2094 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2095 assert(ply >= 0 && ply < PLY_MAX);
2097 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2099 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2100 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2101 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2105 // connected_moves() tests whether two moves are 'connected' in the sense
2106 // that the first move somehow made the second move possible (for instance
2107 // if the moving piece is the same in both moves). The first move is
2108 // assumed to be the move that was made to reach the current position, while
2109 // the second move is assumed to be a move from the current position.
2111 bool connected_moves(const Position& pos, Move m1, Move m2) {
2112 Square f1, t1, f2, t2;
2114 assert(move_is_ok(m1));
2115 assert(move_is_ok(m2));
2117 if (m2 == MOVE_NONE)
2120 // Case 1: The moving piece is the same in both moves
2126 // Case 2: The destination square for m2 was vacated by m1
2132 // Case 3: Moving through the vacated square
2133 if ( piece_is_slider(pos.piece_on(f2))
2134 && bit_is_set(squares_between(f2, t2), f1))
2137 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2138 if (pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2141 // Case 5: Discovered check, checking piece is the piece moved in m1
2142 if ( piece_is_slider(pos.piece_on(t1))
2143 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2144 && !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())), t2))
2146 Bitboard occ = pos.occupied_squares();
2147 Color us = pos.side_to_move();
2148 Square ksq = pos.king_square(us);
2149 clear_bit(&occ, f2);
2150 if (pos.type_of_piece_on(t1) == BISHOP)
2152 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2155 else if (pos.type_of_piece_on(t1) == ROOK)
2157 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2162 assert(pos.type_of_piece_on(t1) == QUEEN);
2163 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2171 // value_is_mate() checks if the given value is a mate one
2172 // eventually compensated for the ply.
2174 bool value_is_mate(Value value) {
2176 assert(abs(value) <= VALUE_INFINITE);
2178 return value <= value_mated_in(PLY_MAX)
2179 || value >= value_mate_in(PLY_MAX);
2183 // move_is_killer() checks if the given move is among the
2184 // killer moves of that ply.
2186 bool move_is_killer(Move m, const SearchStack& ss) {
2188 const Move* k = ss.killers;
2189 for (int i = 0; i < KILLER_MAX; i++, k++)
2197 // extension() decides whether a move should be searched with normal depth,
2198 // or with extended depth. Certain classes of moves (checking moves, in
2199 // particular) are searched with bigger depth than ordinary moves and in
2200 // any case are marked as 'dangerous'. Note that also if a move is not
2201 // extended, as example because the corresponding UCI option is set to zero,
2202 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2204 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2205 bool singleReply, bool mateThreat, bool* dangerous) {
2207 assert(m != MOVE_NONE);
2209 Depth result = Depth(0);
2210 *dangerous = check || singleReply || mateThreat;
2213 result += CheckExtension[pvNode];
2216 result += SingleReplyExtension[pvNode];
2219 result += MateThreatExtension[pvNode];
2221 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2223 if (pos.move_is_pawn_push_to_7th(m))
2225 result += PawnPushTo7thExtension[pvNode];
2228 if (pos.move_is_passed_pawn_push(m))
2230 result += PassedPawnExtension[pvNode];
2236 && pos.type_of_piece_on(move_to(m)) != PAWN
2237 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2238 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2239 && !move_is_promotion(m)
2242 result += PawnEndgameExtension[pvNode];
2248 && pos.type_of_piece_on(move_to(m)) != PAWN
2255 return Min(result, OnePly);
2259 // ok_to_do_nullmove() looks at the current position and decides whether
2260 // doing a 'null move' should be allowed. In order to avoid zugzwang
2261 // problems, null moves are not allowed when the side to move has very
2262 // little material left. Currently, the test is a bit too simple: Null
2263 // moves are avoided only when the side to move has only pawns left. It's
2264 // probably a good idea to avoid null moves in at least some more
2265 // complicated endgames, e.g. KQ vs KR. FIXME
2267 bool ok_to_do_nullmove(const Position& pos) {
2269 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2273 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2274 // non-tactical moves late in the move list close to the leaves are
2275 // candidates for pruning.
2277 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d, const History& H) {
2279 assert(move_is_ok(m));
2280 assert(threat == MOVE_NONE || move_is_ok(threat));
2281 assert(!move_is_promotion(m));
2282 assert(!pos.move_is_check(m));
2283 assert(!pos.move_is_capture(m));
2284 assert(!pos.move_is_passed_pawn_push(m));
2285 assert(d >= OnePly);
2287 Square mfrom, mto, tfrom, tto;
2289 mfrom = move_from(m);
2291 tfrom = move_from(threat);
2292 tto = move_to(threat);
2294 // Case 1: Castling moves are never pruned
2295 if (move_is_castle(m))
2298 // Case 2: Don't prune moves which move the threatened piece
2299 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2302 // Case 3: If the threatened piece has value less than or equal to the
2303 // value of the threatening piece, don't prune move which defend it.
2304 if ( !PruneDefendingMoves
2305 && threat != MOVE_NONE
2306 && pos.move_is_capture(threat)
2307 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2308 || pos.type_of_piece_on(tfrom) == KING)
2309 && pos.move_attacks_square(m, tto))
2312 // Case 4: Don't prune moves with good history
2313 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2316 // Case 5: If the moving piece in the threatened move is a slider, don't
2317 // prune safe moves which block its ray.
2318 if ( !PruneBlockingMoves
2319 && threat != MOVE_NONE
2320 && piece_is_slider(pos.piece_on(tfrom))
2321 && bit_is_set(squares_between(tfrom, tto), mto)
2329 // ok_to_use_TT() returns true if a transposition table score
2330 // can be used at a given point in search.
2332 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2334 Value v = value_from_tt(tte->value(), ply);
2336 return ( tte->depth() >= depth
2337 || v >= Max(value_mate_in(100), beta)
2338 || v < Min(value_mated_in(100), beta))
2340 && ( (is_lower_bound(tte->type()) && v >= beta)
2341 || (is_upper_bound(tte->type()) && v < beta));
2345 // ok_to_history() returns true if a move m can be stored
2346 // in history. Should be a non capturing move nor a promotion.
2348 bool ok_to_history(const Position& pos, Move m) {
2350 return !pos.move_is_capture(m) && !move_is_promotion(m);
2354 // update_history() registers a good move that produced a beta-cutoff
2355 // in history and marks as failures all the other moves of that ply.
2357 void update_history(const Position& pos, Move m, Depth depth, History& H,
2358 Move movesSearched[], int moveCount) {
2360 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2362 for (int i = 0; i < moveCount - 1; i++)
2364 assert(m != movesSearched[i]);
2365 if (ok_to_history(pos, movesSearched[i]))
2366 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2371 // update_killers() add a good move that produced a beta-cutoff
2372 // among the killer moves of that ply.
2374 void update_killers(Move m, SearchStack& ss) {
2376 if (m == ss.killers[0])
2379 for (int i = KILLER_MAX - 1; i > 0; i--)
2380 ss.killers[i] = ss.killers[i - 1];
2385 // fail_high_ply_1() checks if some thread is currently resolving a fail
2386 // high at ply 1 at the node below the first root node. This information
2387 // is used for time managment.
2389 bool fail_high_ply_1() {
2391 for(int i = 0; i < ActiveThreads; i++)
2392 if (Threads[i].failHighPly1)
2399 // current_search_time() returns the number of milliseconds which have passed
2400 // since the beginning of the current search.
2402 int current_search_time() {
2403 return get_system_time() - SearchStartTime;
2407 // nps() computes the current nodes/second count.
2410 int t = current_search_time();
2411 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2415 // poll() performs two different functions: It polls for user input, and it
2416 // looks at the time consumed so far and decides if it's time to abort the
2421 static int lastInfoTime;
2422 int t = current_search_time();
2427 // We are line oriented, don't read single chars
2428 std::string command;
2429 if (!std::getline(std::cin, command))
2432 if (command == "quit")
2435 PonderSearch = false;
2439 else if (command == "stop")
2442 PonderSearch = false;
2444 else if (command == "ponderhit")
2447 // Print search information
2451 else if (lastInfoTime > t)
2452 // HACK: Must be a new search where we searched less than
2453 // NodesBetweenPolls nodes during the first second of search.
2456 else if (t - lastInfoTime >= 1000)
2463 if (dbg_show_hit_rate)
2464 dbg_print_hit_rate();
2466 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2467 << " time " << t << " hashfull " << TT.full() << std::endl;
2468 lock_release(&IOLock);
2469 if (ShowCurrentLine)
2470 Threads[0].printCurrentLine = true;
2472 // Should we stop the search?
2476 bool overTime = t > AbsoluteMaxSearchTime
2477 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2478 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2479 && t > 6*(MaxSearchTime + ExtraSearchTime));
2481 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2482 || (ExactMaxTime && t >= ExactMaxTime)
2483 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2488 // ponderhit() is called when the program is pondering (i.e. thinking while
2489 // it's the opponent's turn to move) in order to let the engine know that
2490 // it correctly predicted the opponent's move.
2494 int t = current_search_time();
2495 PonderSearch = false;
2496 if (Iteration >= 3 &&
2497 (!InfiniteSearch && (StopOnPonderhit ||
2498 t > AbsoluteMaxSearchTime ||
2499 (RootMoveNumber == 1 &&
2500 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2501 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2502 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2507 // print_current_line() prints the current line of search for a given
2508 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2510 void print_current_line(SearchStack ss[], int ply, int threadID) {
2512 assert(ply >= 0 && ply < PLY_MAX);
2513 assert(threadID >= 0 && threadID < ActiveThreads);
2515 if (!Threads[threadID].idle)
2518 std::cout << "info currline " << (threadID + 1);
2519 for (int p = 0; p < ply; p++)
2520 std::cout << " " << ss[p].currentMove;
2522 std::cout << std::endl;
2523 lock_release(&IOLock);
2525 Threads[threadID].printCurrentLine = false;
2526 if (threadID + 1 < ActiveThreads)
2527 Threads[threadID + 1].printCurrentLine = true;
2531 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2532 // while the program is pondering. The point is to work around a wrinkle in
2533 // the UCI protocol: When pondering, the engine is not allowed to give a
2534 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2535 // We simply wait here until one of these commands is sent, and return,
2536 // after which the bestmove and pondermove will be printed (in id_loop()).
2538 void wait_for_stop_or_ponderhit() {
2540 std::string command;
2544 if (!std::getline(std::cin, command))
2547 if (command == "quit")
2552 else if (command == "ponderhit" || command == "stop")
2558 // idle_loop() is where the threads are parked when they have no work to do.
2559 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2560 // object for which the current thread is the master.
2562 void idle_loop(int threadID, SplitPoint* waitSp) {
2563 assert(threadID >= 0 && threadID < THREAD_MAX);
2565 Threads[threadID].running = true;
2568 if(AllThreadsShouldExit && threadID != 0)
2571 // If we are not thinking, wait for a condition to be signaled instead
2572 // of wasting CPU time polling for work:
2573 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2574 #if !defined(_MSC_VER)
2575 pthread_mutex_lock(&WaitLock);
2576 if(Idle || threadID >= ActiveThreads)
2577 pthread_cond_wait(&WaitCond, &WaitLock);
2578 pthread_mutex_unlock(&WaitLock);
2580 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2584 // If this thread has been assigned work, launch a search
2585 if(Threads[threadID].workIsWaiting) {
2586 Threads[threadID].workIsWaiting = false;
2587 if(Threads[threadID].splitPoint->pvNode)
2588 sp_search_pv(Threads[threadID].splitPoint, threadID);
2590 sp_search(Threads[threadID].splitPoint, threadID);
2591 Threads[threadID].idle = true;
2594 // If this thread is the master of a split point and all threads have
2595 // finished their work at this split point, return from the idle loop.
2596 if(waitSp != NULL && waitSp->cpus == 0)
2600 Threads[threadID].running = false;
2604 // init_split_point_stack() is called during program initialization, and
2605 // initializes all split point objects.
2607 void init_split_point_stack() {
2608 for(int i = 0; i < THREAD_MAX; i++)
2609 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2610 SplitPointStack[i][j].parent = NULL;
2611 lock_init(&(SplitPointStack[i][j].lock), NULL);
2616 // destroy_split_point_stack() is called when the program exits, and
2617 // destroys all locks in the precomputed split point objects.
2619 void destroy_split_point_stack() {
2620 for(int i = 0; i < THREAD_MAX; i++)
2621 for(int j = 0; j < MaxActiveSplitPoints; j++)
2622 lock_destroy(&(SplitPointStack[i][j].lock));
2626 // thread_should_stop() checks whether the thread with a given threadID has
2627 // been asked to stop, directly or indirectly. This can happen if a beta
2628 // cutoff has occured in thre thread's currently active split point, or in
2629 // some ancestor of the current split point.
2631 bool thread_should_stop(int threadID) {
2632 assert(threadID >= 0 && threadID < ActiveThreads);
2636 if(Threads[threadID].stop)
2638 if(ActiveThreads <= 2)
2640 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2642 Threads[threadID].stop = true;
2649 // thread_is_available() checks whether the thread with threadID "slave" is
2650 // available to help the thread with threadID "master" at a split point. An
2651 // obvious requirement is that "slave" must be idle. With more than two
2652 // threads, this is not by itself sufficient: If "slave" is the master of
2653 // some active split point, it is only available as a slave to the other
2654 // threads which are busy searching the split point at the top of "slave"'s
2655 // split point stack (the "helpful master concept" in YBWC terminology).
2657 bool thread_is_available(int slave, int master) {
2658 assert(slave >= 0 && slave < ActiveThreads);
2659 assert(master >= 0 && master < ActiveThreads);
2660 assert(ActiveThreads > 1);
2662 if(!Threads[slave].idle || slave == master)
2665 if(Threads[slave].activeSplitPoints == 0)
2666 // No active split points means that the thread is available as a slave
2667 // for any other thread.
2670 if(ActiveThreads == 2)
2673 // Apply the "helpful master" concept if possible.
2674 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2681 // idle_thread_exists() tries to find an idle thread which is available as
2682 // a slave for the thread with threadID "master".
2684 bool idle_thread_exists(int master) {
2685 assert(master >= 0 && master < ActiveThreads);
2686 assert(ActiveThreads > 1);
2688 for(int i = 0; i < ActiveThreads; i++)
2689 if(thread_is_available(i, master))
2695 // split() does the actual work of distributing the work at a node between
2696 // several threads at PV nodes. If it does not succeed in splitting the
2697 // node (because no idle threads are available, or because we have no unused
2698 // split point objects), the function immediately returns false. If
2699 // splitting is possible, a SplitPoint object is initialized with all the
2700 // data that must be copied to the helper threads (the current position and
2701 // search stack, alpha, beta, the search depth, etc.), and we tell our
2702 // helper threads that they have been assigned work. This will cause them
2703 // to instantly leave their idle loops and call sp_search_pv(). When all
2704 // threads have returned from sp_search_pv (or, equivalently, when
2705 // splitPoint->cpus becomes 0), split() returns true.
2707 bool split(const Position& p, SearchStack* sstck, int ply,
2708 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2709 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2712 assert(sstck != NULL);
2713 assert(ply >= 0 && ply < PLY_MAX);
2714 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2715 assert(!pvNode || *alpha < *beta);
2716 assert(*beta <= VALUE_INFINITE);
2717 assert(depth > Depth(0));
2718 assert(master >= 0 && master < ActiveThreads);
2719 assert(ActiveThreads > 1);
2721 SplitPoint* splitPoint;
2726 // If no other thread is available to help us, or if we have too many
2727 // active split points, don't split.
2728 if(!idle_thread_exists(master) ||
2729 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2730 lock_release(&MPLock);
2734 // Pick the next available split point object from the split point stack
2735 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2736 Threads[master].activeSplitPoints++;
2738 // Initialize the split point object
2739 splitPoint->parent = Threads[master].splitPoint;
2740 splitPoint->finished = false;
2741 splitPoint->ply = ply;
2742 splitPoint->depth = depth;
2743 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2744 splitPoint->beta = *beta;
2745 splitPoint->pvNode = pvNode;
2746 splitPoint->dcCandidates = dcCandidates;
2747 splitPoint->bestValue = *bestValue;
2748 splitPoint->master = master;
2749 splitPoint->mp = mp;
2750 splitPoint->moves = *moves;
2751 splitPoint->cpus = 1;
2752 splitPoint->pos.copy(p);
2753 splitPoint->parentSstack = sstck;
2754 for(i = 0; i < ActiveThreads; i++)
2755 splitPoint->slaves[i] = 0;
2757 // Copy the current position and the search stack to the master thread
2758 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2759 Threads[master].splitPoint = splitPoint;
2761 // Make copies of the current position and search stack for each thread
2762 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2764 if(thread_is_available(i, master)) {
2765 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2766 Threads[i].splitPoint = splitPoint;
2767 splitPoint->slaves[i] = 1;
2771 // Tell the threads that they have work to do. This will make them leave
2773 for(i = 0; i < ActiveThreads; i++)
2774 if(i == master || splitPoint->slaves[i]) {
2775 Threads[i].workIsWaiting = true;
2776 Threads[i].idle = false;
2777 Threads[i].stop = false;
2780 lock_release(&MPLock);
2782 // Everything is set up. The master thread enters the idle loop, from
2783 // which it will instantly launch a search, because its workIsWaiting
2784 // slot is 'true'. We send the split point as a second parameter to the
2785 // idle loop, which means that the main thread will return from the idle
2786 // loop when all threads have finished their work at this split point
2787 // (i.e. when // splitPoint->cpus == 0).
2788 idle_loop(master, splitPoint);
2790 // We have returned from the idle loop, which means that all threads are
2791 // finished. Update alpha, beta and bestvalue, and return.
2793 if(pvNode) *alpha = splitPoint->alpha;
2794 *beta = splitPoint->beta;
2795 *bestValue = splitPoint->bestValue;
2796 Threads[master].stop = false;
2797 Threads[master].idle = false;
2798 Threads[master].activeSplitPoints--;
2799 Threads[master].splitPoint = splitPoint->parent;
2800 lock_release(&MPLock);
2806 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2807 // to start a new search from the root.
2809 void wake_sleeping_threads() {
2810 if(ActiveThreads > 1) {
2811 for(int i = 1; i < ActiveThreads; i++) {
2812 Threads[i].idle = true;
2813 Threads[i].workIsWaiting = false;
2815 #if !defined(_MSC_VER)
2816 pthread_mutex_lock(&WaitLock);
2817 pthread_cond_broadcast(&WaitCond);
2818 pthread_mutex_unlock(&WaitLock);
2820 for(int i = 1; i < THREAD_MAX; i++)
2821 SetEvent(SitIdleEvent[i]);
2827 // init_thread() is the function which is called when a new thread is
2828 // launched. It simply calls the idle_loop() function with the supplied
2829 // threadID. There are two versions of this function; one for POSIX threads
2830 // and one for Windows threads.
2832 #if !defined(_MSC_VER)
2834 void *init_thread(void *threadID) {
2835 idle_loop(*(int *)threadID, NULL);
2841 DWORD WINAPI init_thread(LPVOID threadID) {
2842 idle_loop(*(int *)threadID, NULL);