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/>.
43 #include "ucioption.h"
47 //// Local definitions
54 // IterationInfoType stores search results for each iteration
56 // Because we use relatively small (dynamic) aspiration window,
57 // there happens many fail highs and fail lows in root. And
58 // because we don't do researches in those cases, "value" stored
59 // here is not necessarily exact. Instead in case of fail high/low
60 // we guess what the right value might be and store our guess
61 // as a "speculated value" and then move on. Speculated values are
62 // used just to calculate aspiration window width, so also if are
63 // not exact is not big a problem.
65 struct IterationInfoType {
67 IterationInfoType(Value v = Value(0), Value sv = Value(0))
68 : value(v), speculatedValue(sv) {}
70 Value value, speculatedValue;
74 // The BetaCounterType class is used to order moves at ply one.
75 // Apart for the first one that has its score, following moves
76 // normally have score -VALUE_INFINITE, so are ordered according
77 // to the number of beta cutoffs occurred under their subtree during
78 // the last iteration. The counters are per thread variables to avoid
79 // concurrent accessing under SMP case.
81 struct BetaCounterType {
85 void add(Color us, Depth d, int threadID);
86 void read(Color us, int64_t& our, int64_t& their);
90 // The RootMove class is used for moves at the root at the tree. For each
91 // root move, we store a score, a node count, and a PV (really a refutation
92 // in the case of moves which fail low).
97 bool operator<(const RootMove&); // used to sort
101 int64_t nodes, cumulativeNodes;
102 Move pv[PLY_MAX_PLUS_2];
103 int64_t ourBeta, theirBeta;
107 // The RootMoveList class is essentially an array of RootMove objects, with
108 // a handful of methods for accessing the data in the individual moves.
113 RootMoveList(Position& pos, Move searchMoves[]);
114 inline Move get_move(int moveNum) const;
115 inline Value get_move_score(int moveNum) const;
116 inline void set_move_score(int moveNum, Value score);
117 inline void set_move_nodes(int moveNum, int64_t nodes);
118 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
119 void set_move_pv(int moveNum, const Move pv[]);
120 inline Move get_move_pv(int moveNum, int i) const;
121 inline int64_t get_move_cumulative_nodes(int moveNum) const;
122 inline int move_count() const;
123 Move scan_for_easy_move() const;
125 void sort_multipv(int n);
128 static const int MaxRootMoves = 500;
129 RootMove moves[MaxRootMoves];
136 // Search depth at iteration 1
137 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
139 // Depth limit for selective search
140 const Depth SelectiveDepth = 7 * OnePly;
142 // Use internal iterative deepening?
143 const bool UseIIDAtPVNodes = true;
144 const bool UseIIDAtNonPVNodes = false;
146 // Internal iterative deepening margin. At Non-PV moves, when
147 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening
148 // search when the static evaluation is at most IIDMargin below beta.
149 const Value IIDMargin = Value(0x100);
151 // Easy move margin. An easy move candidate must be at least this much
152 // better than the second best move.
153 const Value EasyMoveMargin = Value(0x200);
155 // Problem margin. If the score of the first move at iteration N+1 has
156 // dropped by more than this since iteration N, the boolean variable
157 // "Problem" is set to true, which will make the program spend some extra
158 // time looking for a better move.
159 const Value ProblemMargin = Value(0x28);
161 // No problem margin. If the boolean "Problem" is true, and a new move
162 // is found at the root which is less than NoProblemMargin worse than the
163 // best move from the previous iteration, Problem is set back to false.
164 const Value NoProblemMargin = Value(0x14);
166 // Null move margin. A null move search will not be done if the approximate
167 // evaluation of the position is more than NullMoveMargin below beta.
168 const Value NullMoveMargin = Value(0x300);
170 // Pruning criterions. See the code and comments in ok_to_prune() to
171 // understand their precise meaning.
172 const bool PruneEscapeMoves = false;
173 const bool PruneDefendingMoves = false;
174 const bool PruneBlockingMoves = false;
176 // Margins for futility pruning in the quiescence search, and at frontier
177 // and near frontier nodes.
178 const Value FutilityMarginQS = Value(0x80);
180 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
181 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
182 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
183 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
185 const Depth RazorDepth = 4*OnePly;
187 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
188 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
190 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
191 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
194 /// Variables initialized by UCI options
196 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
197 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
199 // Depth limit for use of dynamic threat detection
200 Depth ThreatDepth; // heavy SMP read access
202 // Last seconds noise filtering (LSN)
203 const bool UseLSNFiltering = true;
204 const int LSNTime = 4000; // In milliseconds
205 const Value LSNValue = value_from_centipawns(200);
206 bool loseOnTime = false;
208 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
209 // There is heavy SMP read access on these arrays
210 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
211 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
213 // Iteration counters
215 BetaCounterType BetaCounter; // has per-thread internal data
217 // Scores and number of times the best move changed for each iteration
218 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
219 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
224 // Time managment variables
226 int MaxNodes, MaxDepth;
227 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, ExactMaxTime;
231 bool StopOnPonderhit;
232 bool AbortSearch; // heavy SMP read access
238 // Show current line?
239 bool ShowCurrentLine;
243 std::ofstream LogFile;
245 // MP related variables
246 int ActiveThreads = 1;
247 Depth MinimumSplitDepth;
248 int MaxThreadsPerSplitPoint;
249 Thread Threads[THREAD_MAX];
252 bool AllThreadsShouldExit = false;
253 const int MaxActiveSplitPoints = 8;
254 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
257 #if !defined(_MSC_VER)
258 pthread_cond_t WaitCond;
259 pthread_mutex_t WaitLock;
261 HANDLE SitIdleEvent[THREAD_MAX];
264 // Node counters, used only by thread[0] but try to keep in different
265 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
267 int NodesBetweenPolls = 30000;
275 Value id_loop(const Position& pos, Move searchMoves[]);
276 Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta);
277 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
278 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
279 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
280 void sp_search(SplitPoint* sp, int threadID);
281 void sp_search_pv(SplitPoint* sp, int threadID);
282 void init_node(const Position& pos, SearchStack ss[], int ply, int threadID);
283 void update_pv(SearchStack ss[], int ply);
284 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply);
285 bool connected_moves(const Position& pos, Move m1, Move m2);
286 bool value_is_mate(Value value);
287 bool move_is_killer(Move m, const SearchStack& ss);
288 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
289 bool ok_to_do_nullmove(const Position& pos);
290 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d);
291 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
292 bool ok_to_history(const Position& pos, Move m);
293 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
294 void update_killers(Move m, SearchStack& ss);
296 bool fail_high_ply_1();
297 int current_search_time();
301 void print_current_line(SearchStack ss[], int ply, int threadID);
302 void wait_for_stop_or_ponderhit();
304 void idle_loop(int threadID, SplitPoint* waitSp);
305 void init_split_point_stack();
306 void destroy_split_point_stack();
307 bool thread_should_stop(int threadID);
308 bool thread_is_available(int slave, int master);
309 bool idle_thread_exists(int master);
310 bool split(const Position& pos, SearchStack* ss, int ply,
311 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
312 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
313 void wake_sleeping_threads();
315 #if !defined(_MSC_VER)
316 void *init_thread(void *threadID);
318 DWORD WINAPI init_thread(LPVOID threadID);
328 /// think() is the external interface to Stockfish's search, and is called when
329 /// the program receives the UCI 'go' command. It initializes various
330 /// search-related global variables, and calls root_search(). It returns false
331 /// when a quit command is received during the search.
333 bool think(const Position& pos, bool infinite, bool ponder, int side_to_move,
334 int time[], int increment[], int movesToGo, int maxDepth,
335 int maxNodes, int maxTime, Move searchMoves[]) {
337 // Look for a book move
338 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
341 if (get_option_value_string("Book File") != OpeningBook.file_name())
342 OpeningBook.open("book.bin");
344 bookMove = OpeningBook.get_move(pos);
345 if (bookMove != MOVE_NONE)
347 std::cout << "bestmove " << bookMove << std::endl;
352 // Initialize global search variables
354 SearchStartTime = get_system_time();
355 for (int i = 0; i < THREAD_MAX; i++)
357 Threads[i].nodes = 0ULL;
358 Threads[i].failHighPly1 = false;
361 InfiniteSearch = infinite;
362 PonderSearch = ponder;
363 StopOnPonderhit = false;
369 ExactMaxTime = maxTime;
371 // Read UCI option values
372 TT.set_size(get_option_value_int("Hash"));
373 if (button_was_pressed("Clear Hash"))
376 loseOnTime = false; // reset at the beginning of a new game
379 bool PonderingEnabled = get_option_value_bool("Ponder");
380 MultiPV = get_option_value_int("MultiPV");
382 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
383 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
385 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
386 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
388 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
389 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
391 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
392 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
394 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
395 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
397 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
398 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
400 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
401 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
402 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
404 Chess960 = get_option_value_bool("UCI_Chess960");
405 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
406 UseLogFile = get_option_value_bool("Use Search Log");
408 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
410 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
411 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
413 read_weights(pos.side_to_move());
415 // Set the number of active threads.
416 int newActiveThreads = get_option_value_int("Threads");
417 if (newActiveThreads != ActiveThreads)
419 ActiveThreads = newActiveThreads;
420 init_eval(ActiveThreads);
423 // Wake up sleeping threads
424 wake_sleeping_threads();
426 for (int i = 1; i < ActiveThreads; i++)
427 assert(thread_is_available(i, 0));
430 int myTime = time[side_to_move];
431 int myIncrement = increment[side_to_move];
433 if (!movesToGo) // Sudden death time control
437 MaxSearchTime = myTime / 30 + myIncrement;
438 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
439 } else { // Blitz game without increment
440 MaxSearchTime = myTime / 30;
441 AbsoluteMaxSearchTime = myTime / 8;
444 else // (x moves) / (y minutes)
448 MaxSearchTime = myTime / 2;
449 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
451 MaxSearchTime = myTime / Min(movesToGo, 20);
452 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
456 if (PonderingEnabled)
458 MaxSearchTime += MaxSearchTime / 4;
459 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
462 // Fixed depth or fixed number of nodes?
465 InfiniteSearch = true; // HACK
470 NodesBetweenPolls = Min(MaxNodes, 30000);
471 InfiniteSearch = true; // HACK
474 NodesBetweenPolls = 30000;
476 // Write information to search log file
478 LogFile << "Searching: " << pos.to_fen() << std::endl
479 << "infinite: " << infinite
480 << " ponder: " << ponder
481 << " time: " << myTime
482 << " increment: " << myIncrement
483 << " moves to go: " << movesToGo << std::endl;
486 // We're ready to start thinking. Call the iterative deepening loop function
488 // FIXME we really need to cleanup all this LSN ugliness
491 Value v = id_loop(pos, searchMoves);
492 loseOnTime = ( UseLSNFiltering
499 loseOnTime = false; // reset for next match
500 while (SearchStartTime + myTime + 1000 > get_system_time())
502 id_loop(pos, searchMoves); // to fail gracefully
513 /// init_threads() is called during startup. It launches all helper threads,
514 /// and initializes the split point stack and the global locks and condition
517 void init_threads() {
521 #if !defined(_MSC_VER)
522 pthread_t pthread[1];
525 for (i = 0; i < THREAD_MAX; i++)
526 Threads[i].activeSplitPoints = 0;
528 // Initialize global locks
529 lock_init(&MPLock, NULL);
530 lock_init(&IOLock, NULL);
532 init_split_point_stack();
534 #if !defined(_MSC_VER)
535 pthread_mutex_init(&WaitLock, NULL);
536 pthread_cond_init(&WaitCond, NULL);
538 for (i = 0; i < THREAD_MAX; i++)
539 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
542 // All threads except the main thread should be initialized to idle state
543 for (i = 1; i < THREAD_MAX; i++)
545 Threads[i].stop = false;
546 Threads[i].workIsWaiting = false;
547 Threads[i].idle = true;
548 Threads[i].running = false;
551 // Launch the helper threads
552 for(i = 1; i < THREAD_MAX; i++)
554 #if !defined(_MSC_VER)
555 pthread_create(pthread, NULL, init_thread, (void*)(&i));
558 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
561 // Wait until the thread has finished launching
562 while (!Threads[i].running);
567 /// stop_threads() is called when the program exits. It makes all the
568 /// helper threads exit cleanly.
570 void stop_threads() {
572 ActiveThreads = THREAD_MAX; // HACK
573 Idle = false; // HACK
574 wake_sleeping_threads();
575 AllThreadsShouldExit = true;
576 for (int i = 1; i < THREAD_MAX; i++)
578 Threads[i].stop = true;
579 while(Threads[i].running);
581 destroy_split_point_stack();
585 /// nodes_searched() returns the total number of nodes searched so far in
586 /// the current search.
588 int64_t nodes_searched() {
590 int64_t result = 0ULL;
591 for (int i = 0; i < ActiveThreads; i++)
592 result += Threads[i].nodes;
597 // SearchStack::init() initializes a search stack. Used at the beginning of a
598 // new search from the root.
599 void SearchStack::init(int ply) {
601 pv[ply] = pv[ply + 1] = MOVE_NONE;
602 currentMove = threatMove = MOVE_NONE;
603 reduction = Depth(0);
606 void SearchStack::initKillers() {
608 mateKiller = MOVE_NONE;
609 for (int i = 0; i < KILLER_MAX; i++)
610 killers[i] = MOVE_NONE;
615 // id_loop() is the main iterative deepening loop. It calls root_search
616 // repeatedly with increasing depth until the allocated thinking time has
617 // been consumed, the user stops the search, or the maximum search depth is
620 Value id_loop(const Position& pos, Move searchMoves[]) {
623 SearchStack ss[PLY_MAX_PLUS_2];
625 // searchMoves are verified, copied, scored and sorted
626 RootMoveList rml(p, searchMoves);
628 // Print RootMoveList c'tor startup scoring to the standard output,
629 // so that we print information also for iteration 1.
630 std::cout << "info depth " << 1 << "\ninfo depth " << 1
631 << " score " << value_to_string(rml.get_move_score(0))
632 << " time " << current_search_time()
633 << " nodes " << nodes_searched()
635 << " pv " << rml.get_move(0) << "\n";
640 for (int i = 0; i < 3; i++)
645 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
648 Move EasyMove = rml.scan_for_easy_move();
650 // Iterative deepening loop
651 while (Iteration < PLY_MAX)
653 // Initialize iteration
656 BestMoveChangesByIteration[Iteration] = 0;
660 std::cout << "info depth " << Iteration << std::endl;
662 // Calculate dynamic search window based on previous iterations
665 if (MultiPV == 1 && Iteration >= 6 && abs(IterationInfo[Iteration - 1].value) < VALUE_KNOWN_WIN)
667 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
668 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
670 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
672 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
673 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
677 alpha = - VALUE_INFINITE;
678 beta = VALUE_INFINITE;
681 // Search to the current depth
682 Value value = root_search(p, ss, rml, alpha, beta);
684 // Write PV to transposition table, in case the relevant entries have
685 // been overwritten during the search.
686 TT.insert_pv(p, ss[0].pv);
689 break; // Value cannot be trusted. Break out immediately!
691 //Save info about search result
692 Value speculatedValue;
695 Value delta = value - IterationInfo[Iteration - 1].value;
702 speculatedValue = value + delta;
703 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
705 else if (value <= alpha)
707 assert(value == alpha);
711 speculatedValue = value + delta;
712 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
714 speculatedValue = value;
716 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
717 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
719 // Erase the easy move if it differs from the new best move
720 if (ss[0].pv[0] != EasyMove)
721 EasyMove = MOVE_NONE;
728 bool stopSearch = false;
730 // Stop search early if there is only a single legal move
731 if (Iteration >= 6 && rml.move_count() == 1)
734 // Stop search early when the last two iterations returned a mate score
736 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
737 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
740 // Stop search early if one move seems to be much better than the rest
741 int64_t nodes = nodes_searched();
745 && EasyMove == ss[0].pv[0]
746 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
747 && current_search_time() > MaxSearchTime / 16)
748 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
749 && current_search_time() > MaxSearchTime / 32)))
752 // Add some extra time if the best move has changed during the last two iterations
753 if (Iteration > 5 && Iteration <= 50)
754 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
755 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
757 // Stop search if most of MaxSearchTime is consumed at the end of the
758 // iteration. We probably don't have enough time to search the first
759 // move at the next iteration anyway.
760 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
765 //FIXME: Implement fail-low emergency measures
769 StopOnPonderhit = true;
773 if (MaxDepth && Iteration >= MaxDepth)
779 // If we are pondering, we shouldn't print the best move before we
782 wait_for_stop_or_ponderhit();
784 // Print final search statistics
785 std::cout << "info nodes " << nodes_searched()
787 << " time " << current_search_time()
788 << " hashfull " << TT.full() << std::endl;
790 // Print the best move and the ponder move to the standard output
791 if (ss[0].pv[0] == MOVE_NONE)
793 ss[0].pv[0] = rml.get_move(0);
794 ss[0].pv[1] = MOVE_NONE;
796 std::cout << "bestmove " << ss[0].pv[0];
797 if (ss[0].pv[1] != MOVE_NONE)
798 std::cout << " ponder " << ss[0].pv[1];
800 std::cout << std::endl;
805 dbg_print_mean(LogFile);
807 if (dbg_show_hit_rate)
808 dbg_print_hit_rate(LogFile);
811 LogFile << "Nodes: " << nodes_searched() << std::endl
812 << "Nodes/second: " << nps() << std::endl
813 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
815 p.do_move(ss[0].pv[0], st);
816 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
817 << std::endl << std::endl;
819 return rml.get_move_score(0);
823 // root_search() is the function which searches the root node. It is
824 // similar to search_pv except that it uses a different move ordering
825 // scheme (perhaps we should try to use this at internal PV nodes, too?)
826 // and prints some information to the standard output.
828 Value root_search(Position& pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
830 Value oldAlpha = alpha;
832 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
834 // Loop through all the moves in the root move list
835 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
839 // We failed high, invalidate and skip next moves, leave node-counters
840 // and beta-counters as they are and quickly return, we will try to do
841 // a research at the next iteration with a bigger aspiration window.
842 rml.set_move_score(i, -VALUE_INFINITE);
850 RootMoveNumber = i + 1;
853 // Remember the node count before the move is searched. The node counts
854 // are used to sort the root moves at the next iteration.
855 nodes = nodes_searched();
857 // Reset beta cut-off counters
860 // Pick the next root move, and print the move and the move number to
861 // the standard output.
862 move = ss[0].currentMove = rml.get_move(i);
863 if (current_search_time() >= 1000)
864 std::cout << "info currmove " << move
865 << " currmovenumber " << i + 1 << std::endl;
867 // Decide search depth for this move
868 bool moveIsCapture = pos.move_is_capture(move);
870 ext = extension(pos, move, true, moveIsCapture, pos.move_is_check(move), false, false, &dangerous);
871 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
873 // Make the move, and search it
874 pos.do_move(move, st, dcCandidates);
878 // Aspiration window is disabled in multi-pv case
880 alpha = -VALUE_INFINITE;
882 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
883 // If the value has dropped a lot compared to the last iteration,
884 // set the boolean variable Problem to true. This variable is used
885 // for time managment: When Problem is true, we try to complete the
886 // current iteration before playing a move.
887 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
889 if (Problem && StopOnPonderhit)
890 StopOnPonderhit = false;
894 if ( newDepth >= 3*OnePly
895 && i >= MultiPV + LMRPVMoves
898 && !move_is_promotion(move)
899 && !move_is_castle(move))
901 ss[0].reduction = OnePly;
902 value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0);
904 value = alpha + 1; // Just to trigger next condition
908 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
911 // Fail high! Set the boolean variable FailHigh to true, and
912 // re-search the move with a big window. The variable FailHigh is
913 // used for time managment: We try to avoid aborting the search
914 // prematurely during a fail high research.
916 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
923 // Finished searching the move. If AbortSearch is true, the search
924 // was aborted because the user interrupted the search or because we
925 // ran out of time. In this case, the return value of the search cannot
926 // be trusted, and we break out of the loop without updating the best
931 // Remember the node count for this move. The node counts are used to
932 // sort the root moves at the next iteration.
933 rml.set_move_nodes(i, nodes_searched() - nodes);
935 // Remember the beta-cutoff statistics
937 BetaCounter.read(pos.side_to_move(), our, their);
938 rml.set_beta_counters(i, our, their);
940 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
942 if (value <= alpha && i >= MultiPV)
943 rml.set_move_score(i, -VALUE_INFINITE);
946 // PV move or new best move!
949 rml.set_move_score(i, value);
951 TT.extract_pv(pos, ss[0].pv);
952 rml.set_move_pv(i, ss[0].pv);
956 // We record how often the best move has been changed in each
957 // iteration. This information is used for time managment: When
958 // the best move changes frequently, we allocate some more time.
960 BestMoveChangesByIteration[Iteration]++;
962 // Print search information to the standard output
963 std::cout << "info depth " << Iteration
964 << " score " << value_to_string(value)
966 " lowerbound" : ((value <= alpha)? " upperbound" : ""))
967 << " time " << current_search_time()
968 << " nodes " << nodes_searched()
972 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
973 std::cout << ss[0].pv[j] << " ";
975 std::cout << std::endl;
978 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
984 // Reset the global variable Problem to false if the value isn't too
985 // far below the final value from the last iteration.
986 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
992 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
995 std::cout << "info multipv " << j + 1
996 << " score " << value_to_string(rml.get_move_score(j))
997 << " depth " << ((j <= i)? Iteration : Iteration - 1)
998 << " time " << current_search_time()
999 << " nodes " << nodes_searched()
1003 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
1004 std::cout << rml.get_move_pv(j, k) << " ";
1006 std::cout << std::endl;
1008 alpha = rml.get_move_score(Min(i, MultiPV-1));
1010 } // New best move case
1012 assert(alpha >= oldAlpha);
1014 FailLow = (alpha == oldAlpha);
1020 // search_pv() is the main search function for PV nodes.
1022 Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta,
1023 Depth depth, int ply, int threadID) {
1025 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1026 assert(beta > alpha && beta <= VALUE_INFINITE);
1027 assert(ply >= 0 && ply < PLY_MAX);
1028 assert(threadID >= 0 && threadID < ActiveThreads);
1031 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1033 // Initialize, and make an early exit in case of an aborted search,
1034 // an instant draw, maximum ply reached, etc.
1035 init_node(pos, ss, ply, threadID);
1037 // After init_node() that calls poll()
1038 if (AbortSearch || thread_should_stop(threadID))
1046 if (ply >= PLY_MAX - 1)
1047 return evaluate(pos, ei, threadID);
1049 // Mate distance pruning
1050 Value oldAlpha = alpha;
1051 alpha = Max(value_mated_in(ply), alpha);
1052 beta = Min(value_mate_in(ply+1), beta);
1056 // Transposition table lookup. At PV nodes, we don't use the TT for
1057 // pruning, but only for move ordering.
1058 const TTEntry* tte = TT.retrieve(pos.get_key());
1059 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1061 // Go with internal iterative deepening if we don't have a TT move
1062 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1064 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1065 ttMove = ss[ply].pv[ply];
1068 // Initialize a MovePicker object for the current position, and prepare
1069 // to search all moves
1070 Move move, movesSearched[256];
1072 Value value, bestValue = -VALUE_INFINITE;
1073 Color us = pos.side_to_move();
1074 bool isCheck = pos.is_check();
1075 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1077 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1078 Bitboard dcCandidates = mp.discovered_check_candidates();
1080 // Loop through all legal moves until no moves remain or a beta cutoff
1082 while ( alpha < beta
1083 && (move = mp.get_next_move()) != MOVE_NONE
1084 && !thread_should_stop(threadID))
1086 assert(move_is_ok(move));
1088 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1089 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1090 bool moveIsCapture = pos.move_is_capture(move);
1092 movesSearched[moveCount++] = ss[ply].currentMove = move;
1094 // Decide the new search depth
1096 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1097 Depth newDepth = depth - OnePly + ext;
1099 // Make and search the move
1101 pos.do_move(move, st, dcCandidates);
1103 if (moveCount == 1) // The first move in list is the PV
1104 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1107 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1108 // if the move fails high will be re-searched at full depth.
1109 if ( depth >= 3*OnePly
1110 && moveCount >= LMRPVMoves
1113 && !move_is_promotion(move)
1114 && !move_is_castle(move)
1115 && !move_is_killer(move, ss[ply]))
1117 ss[ply].reduction = OnePly;
1118 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1121 value = alpha + 1; // Just to trigger next condition
1123 if (value > alpha) // Go with full depth non-pv search
1125 ss[ply].reduction = Depth(0);
1126 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1127 if (value > alpha && value < beta)
1129 // When the search fails high at ply 1 while searching the first
1130 // move at the root, set the flag failHighPly1. This is used for
1131 // time managment: We don't want to stop the search early in
1132 // such cases, because resolving the fail high at ply 1 could
1133 // result in a big drop in score at the root.
1134 if (ply == 1 && RootMoveNumber == 1)
1135 Threads[threadID].failHighPly1 = true;
1137 // A fail high occurred. Re-search at full window (pv search)
1138 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1139 Threads[threadID].failHighPly1 = false;
1143 pos.undo_move(move);
1145 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1148 if (value > bestValue)
1155 if (value == value_mate_in(ply + 1))
1156 ss[ply].mateKiller = move;
1158 // If we are at ply 1, and we are searching the first root move at
1159 // ply 0, set the 'Problem' variable if the score has dropped a lot
1160 // (from the computer's point of view) since the previous iteration.
1163 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1168 if ( ActiveThreads > 1
1170 && depth >= MinimumSplitDepth
1172 && idle_thread_exists(threadID)
1174 && !thread_should_stop(threadID)
1175 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1176 &moveCount, &mp, dcCandidates, threadID, true))
1180 // All legal moves have been searched. A special case: If there were
1181 // no legal moves, it must be mate or stalemate.
1183 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1185 // If the search is not aborted, update the transposition table,
1186 // history counters, and killer moves.
1187 if (AbortSearch || thread_should_stop(threadID))
1190 if (bestValue <= oldAlpha)
1191 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1193 else if (bestValue >= beta)
1195 BetaCounter.add(pos.side_to_move(), depth, threadID);
1196 Move m = ss[ply].pv[ply];
1197 if (ok_to_history(pos, m)) // Only non capture moves are considered
1199 update_history(pos, m, depth, movesSearched, moveCount);
1200 update_killers(m, ss[ply]);
1202 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1205 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1211 // search() is the search function for zero-width nodes.
1213 Value search(Position& pos, SearchStack ss[], Value beta, Depth depth,
1214 int ply, bool allowNullmove, int threadID) {
1216 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1217 assert(ply >= 0 && ply < PLY_MAX);
1218 assert(threadID >= 0 && threadID < ActiveThreads);
1221 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1223 // Initialize, and make an early exit in case of an aborted search,
1224 // an instant draw, maximum ply reached, etc.
1225 init_node(pos, ss, ply, threadID);
1227 // After init_node() that calls poll()
1228 if (AbortSearch || thread_should_stop(threadID))
1236 if (ply >= PLY_MAX - 1)
1237 return evaluate(pos, ei, threadID);
1239 // Mate distance pruning
1240 if (value_mated_in(ply) >= beta)
1243 if (value_mate_in(ply + 1) < beta)
1246 // Transposition table lookup
1247 const TTEntry* tte = TT.retrieve(pos.get_key());
1248 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1250 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1252 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1253 return value_from_tt(tte->value(), ply);
1256 Value approximateEval = quick_evaluate(pos);
1257 bool mateThreat = false;
1258 bool isCheck = pos.is_check();
1264 && !value_is_mate(beta)
1265 && ok_to_do_nullmove(pos)
1266 && approximateEval >= beta - NullMoveMargin)
1268 ss[ply].currentMove = MOVE_NULL;
1271 pos.do_null_move(st);
1272 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1274 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1276 pos.undo_null_move();
1278 if (nullValue >= beta)
1280 if (depth < 6 * OnePly)
1283 // Do zugzwang verification search
1284 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1288 // The null move failed low, which means that we may be faced with
1289 // some kind of threat. If the previous move was reduced, check if
1290 // the move that refuted the null move was somehow connected to the
1291 // move which was reduced. If a connection is found, return a fail
1292 // low score (which will cause the reduced move to fail high in the
1293 // parent node, which will trigger a re-search with full depth).
1294 if (nullValue == value_mated_in(ply + 2))
1297 ss[ply].threatMove = ss[ply + 1].currentMove;
1298 if ( depth < ThreatDepth
1299 && ss[ply - 1].reduction
1300 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1304 // Null move search not allowed, try razoring
1305 else if ( !value_is_mate(beta)
1306 && depth < RazorDepth
1307 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1308 && ss[ply - 1].currentMove != MOVE_NULL
1309 && ttMove == MOVE_NONE
1310 && !pos.has_pawn_on_7th(pos.side_to_move()))
1312 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1313 if (v < beta - RazorMargins[int(depth) - 2])
1317 // Go with internal iterative deepening if we don't have a TT move
1318 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1319 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1321 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1322 ttMove = ss[ply].pv[ply];
1325 // Initialize a MovePicker object for the current position, and prepare
1326 // to search all moves.
1327 MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]);
1329 Move move, movesSearched[256];
1331 Value value, bestValue = -VALUE_INFINITE;
1332 Bitboard dcCandidates = mp.discovered_check_candidates();
1333 Value futilityValue = VALUE_NONE;
1334 bool useFutilityPruning = depth < SelectiveDepth
1337 // Loop through all legal moves until no moves remain or a beta cutoff
1339 while ( bestValue < beta
1340 && (move = mp.get_next_move()) != MOVE_NONE
1341 && !thread_should_stop(threadID))
1343 assert(move_is_ok(move));
1345 bool singleReply = (isCheck && mp.number_of_evasions() == 1);
1346 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1347 bool moveIsCapture = pos.move_is_capture(move);
1349 movesSearched[moveCount++] = ss[ply].currentMove = move;
1351 // Decide the new search depth
1353 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1354 Depth newDepth = depth - OnePly + ext;
1357 if ( useFutilityPruning
1360 && !move_is_promotion(move))
1362 // History pruning. See ok_to_prune() definition
1363 if ( moveCount >= 2 + int(depth)
1364 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1367 // Value based pruning
1368 if (approximateEval < beta)
1370 if (futilityValue == VALUE_NONE)
1371 futilityValue = evaluate(pos, ei, threadID)
1372 + FutilityMargins[int(depth) - 2];
1374 if (futilityValue < beta)
1376 if (futilityValue > bestValue)
1377 bestValue = futilityValue;
1383 // Make and search the move
1385 pos.do_move(move, st, dcCandidates);
1387 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1388 // if the move fails high will be re-searched at full depth.
1389 if ( depth >= 3*OnePly
1390 && moveCount >= LMRNonPVMoves
1393 && !move_is_promotion(move)
1394 && !move_is_castle(move)
1395 && !move_is_killer(move, ss[ply]))
1397 ss[ply].reduction = OnePly;
1398 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1401 value = beta; // Just to trigger next condition
1403 if (value >= beta) // Go with full depth non-pv search
1405 ss[ply].reduction = Depth(0);
1406 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1408 pos.undo_move(move);
1410 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1413 if (value > bestValue)
1419 if (value == value_mate_in(ply + 1))
1420 ss[ply].mateKiller = move;
1424 if ( ActiveThreads > 1
1426 && depth >= MinimumSplitDepth
1428 && idle_thread_exists(threadID)
1430 && !thread_should_stop(threadID)
1431 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1432 &mp, dcCandidates, threadID, false))
1436 // All legal moves have been searched. A special case: If there were
1437 // no legal moves, it must be mate or stalemate.
1439 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1441 // If the search is not aborted, update the transposition table,
1442 // history counters, and killer moves.
1443 if (AbortSearch || thread_should_stop(threadID))
1446 if (bestValue < beta)
1447 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1450 BetaCounter.add(pos.side_to_move(), depth, threadID);
1451 Move m = ss[ply].pv[ply];
1452 if (ok_to_history(pos, m)) // Only non capture moves are considered
1454 update_history(pos, m, depth, movesSearched, moveCount);
1455 update_killers(m, ss[ply]);
1457 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1460 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1466 // qsearch() is the quiescence search function, which is called by the main
1467 // search function when the remaining depth is zero (or, to be more precise,
1468 // less than OnePly).
1470 Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta,
1471 Depth depth, int ply, int threadID) {
1473 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1474 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1476 assert(ply >= 0 && ply < PLY_MAX);
1477 assert(threadID >= 0 && threadID < ActiveThreads);
1479 // Initialize, and make an early exit in case of an aborted search,
1480 // an instant draw, maximum ply reached, etc.
1481 init_node(pos, ss, ply, threadID);
1483 // After init_node() that calls poll()
1484 if (AbortSearch || thread_should_stop(threadID))
1490 // Transposition table lookup, only when not in PV
1491 TTEntry* tte = NULL;
1492 bool pvNode = (beta - alpha != 1);
1495 tte = TT.retrieve(pos.get_key());
1496 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1498 assert(tte->type() != VALUE_TYPE_EVAL);
1500 return value_from_tt(tte->value(), ply);
1503 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1505 // Evaluate the position statically
1508 bool isCheck = pos.is_check();
1509 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1512 staticValue = -VALUE_INFINITE;
1514 else if (tte && (tte->type() & VALUE_TYPE_EVAL))
1516 // Use the cached evaluation score if possible
1517 assert(ei.futilityMargin == Value(0));
1519 staticValue = tte->value();
1522 staticValue = evaluate(pos, ei, threadID);
1524 if (ply == PLY_MAX - 1)
1525 return evaluate(pos, ei, threadID);
1527 // Initialize "stand pat score", and return it immediately if it is
1529 Value bestValue = staticValue;
1531 if (bestValue >= beta)
1533 // Store the score to avoid a future costly evaluation() call
1534 if (!isCheck && !tte && ei.futilityMargin == 0)
1535 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE);
1540 if (bestValue > alpha)
1543 // Initialize a MovePicker object for the current position, and prepare
1544 // to search the moves. Because the depth is <= 0 here, only captures,
1545 // queen promotions and checks (only if depth == 0) will be generated.
1546 MovePicker mp = MovePicker(pos, ttMove, depth, H);
1549 Bitboard dcCandidates = mp.discovered_check_candidates();
1550 Color us = pos.side_to_move();
1551 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1553 // Loop through the moves until no moves remain or a beta cutoff
1555 while ( alpha < beta
1556 && (move = mp.get_next_move()) != MOVE_NONE)
1558 assert(move_is_ok(move));
1561 ss[ply].currentMove = move;
1567 && !move_is_promotion(move)
1568 && !pos.move_is_check(move, dcCandidates)
1569 && !pos.move_is_passed_pawn_push(move))
1571 Value futilityValue = staticValue
1572 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1573 pos.endgame_value_of_piece_on(move_to(move)))
1574 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1576 + ei.futilityMargin;
1578 if (futilityValue < alpha)
1580 if (futilityValue > bestValue)
1581 bestValue = futilityValue;
1586 // Don't search captures and checks with negative SEE values
1588 && !move_is_promotion(move)
1589 && pos.see_sign(move) < 0)
1592 // Make and search the move.
1594 pos.do_move(move, st, dcCandidates);
1595 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1596 pos.undo_move(move);
1598 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1601 if (value > bestValue)
1612 // All legal moves have been searched. A special case: If we're in check
1613 // and no legal moves were found, it is checkmate.
1614 if (pos.is_check() && moveCount == 0) // Mate!
1615 return value_mated_in(ply);
1617 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1619 // Update transposition table
1620 Move m = ss[ply].pv[ply];
1623 // If bestValue isn't changed it means it is still the static evaluation of
1624 // the node, so keep this info to avoid a future costly evaluation() call.
1625 ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER);
1626 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1628 if (bestValue < beta)
1629 TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE);
1631 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1634 // Update killers only for good check moves
1635 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1636 update_killers(m, ss[ply]);
1642 // sp_search() is used to search from a split point. This function is called
1643 // by each thread working at the split point. It is similar to the normal
1644 // search() function, but simpler. Because we have already probed the hash
1645 // table, done a null move search, and searched the first move before
1646 // splitting, we don't have to repeat all this work in sp_search(). We
1647 // also don't need to store anything to the hash table here: This is taken
1648 // care of after we return from the split point.
1650 void sp_search(SplitPoint* sp, int threadID) {
1652 assert(threadID >= 0 && threadID < ActiveThreads);
1653 assert(ActiveThreads > 1);
1655 Position pos = Position(sp->pos);
1656 SearchStack* ss = sp->sstack[threadID];
1659 bool isCheck = pos.is_check();
1660 bool useFutilityPruning = sp->depth < SelectiveDepth
1663 while ( sp->bestValue < sp->beta
1664 && !thread_should_stop(threadID)
1665 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1667 assert(move_is_ok(move));
1669 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1670 bool moveIsCapture = pos.move_is_capture(move);
1672 lock_grab(&(sp->lock));
1673 int moveCount = ++sp->moves;
1674 lock_release(&(sp->lock));
1676 ss[sp->ply].currentMove = move;
1678 // Decide the new search depth.
1680 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1681 Depth newDepth = sp->depth - OnePly + ext;
1684 if ( useFutilityPruning
1687 && !move_is_promotion(move)
1688 && moveCount >= 2 + int(sp->depth)
1689 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1692 // Make and search the move.
1694 pos.do_move(move, st, sp->dcCandidates);
1696 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1697 // if the move fails high will be re-searched at full depth.
1699 && moveCount >= LMRNonPVMoves
1701 && !move_is_promotion(move)
1702 && !move_is_castle(move)
1703 && !move_is_killer(move, ss[sp->ply]))
1705 ss[sp->ply].reduction = OnePly;
1706 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1709 value = sp->beta; // Just to trigger next condition
1711 if (value >= sp->beta) // Go with full depth non-pv search
1713 ss[sp->ply].reduction = Depth(0);
1714 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1716 pos.undo_move(move);
1718 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1720 if (thread_should_stop(threadID))
1724 lock_grab(&(sp->lock));
1725 if (value > sp->bestValue && !thread_should_stop(threadID))
1727 sp->bestValue = value;
1728 if (sp->bestValue >= sp->beta)
1730 sp_update_pv(sp->parentSstack, ss, sp->ply);
1731 for (int i = 0; i < ActiveThreads; i++)
1732 if (i != threadID && (i == sp->master || sp->slaves[i]))
1733 Threads[i].stop = true;
1735 sp->finished = true;
1738 lock_release(&(sp->lock));
1741 lock_grab(&(sp->lock));
1743 // If this is the master thread and we have been asked to stop because of
1744 // a beta cutoff higher up in the tree, stop all slave threads.
1745 if (sp->master == threadID && thread_should_stop(threadID))
1746 for (int i = 0; i < ActiveThreads; i++)
1748 Threads[i].stop = true;
1751 sp->slaves[threadID] = 0;
1753 lock_release(&(sp->lock));
1757 // sp_search_pv() is used to search from a PV split point. This function
1758 // is called by each thread working at the split point. It is similar to
1759 // the normal search_pv() function, but simpler. Because we have already
1760 // probed the hash table and searched the first move before splitting, we
1761 // don't have to repeat all this work in sp_search_pv(). We also don't
1762 // need to store anything to the hash table here: This is taken care of
1763 // after we return from the split point.
1765 void sp_search_pv(SplitPoint* sp, int threadID) {
1767 assert(threadID >= 0 && threadID < ActiveThreads);
1768 assert(ActiveThreads > 1);
1770 Position pos = Position(sp->pos);
1771 SearchStack* ss = sp->sstack[threadID];
1775 while ( sp->alpha < sp->beta
1776 && !thread_should_stop(threadID)
1777 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1779 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1780 bool moveIsCapture = pos.move_is_capture(move);
1782 assert(move_is_ok(move));
1784 lock_grab(&(sp->lock));
1785 int moveCount = ++sp->moves;
1786 lock_release(&(sp->lock));
1788 ss[sp->ply].currentMove = move;
1790 // Decide the new search depth.
1792 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1793 Depth newDepth = sp->depth - OnePly + ext;
1795 // Make and search the move.
1797 pos.do_move(move, st, sp->dcCandidates);
1799 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1800 // if the move fails high will be re-searched at full depth.
1802 && moveCount >= LMRPVMoves
1804 && !move_is_promotion(move)
1805 && !move_is_castle(move)
1806 && !move_is_killer(move, ss[sp->ply]))
1808 ss[sp->ply].reduction = OnePly;
1809 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1812 value = sp->alpha + 1; // Just to trigger next condition
1814 if (value > sp->alpha) // Go with full depth non-pv search
1816 ss[sp->ply].reduction = Depth(0);
1817 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1819 if (value > sp->alpha && value < sp->beta)
1821 // When the search fails high at ply 1 while searching the first
1822 // move at the root, set the flag failHighPly1. This is used for
1823 // time managment: We don't want to stop the search early in
1824 // such cases, because resolving the fail high at ply 1 could
1825 // result in a big drop in score at the root.
1826 if (sp->ply == 1 && RootMoveNumber == 1)
1827 Threads[threadID].failHighPly1 = true;
1829 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1830 Threads[threadID].failHighPly1 = false;
1833 pos.undo_move(move);
1835 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1837 if (thread_should_stop(threadID))
1841 lock_grab(&(sp->lock));
1842 if (value > sp->bestValue && !thread_should_stop(threadID))
1844 sp->bestValue = value;
1845 if (value > sp->alpha)
1848 sp_update_pv(sp->parentSstack, ss, sp->ply);
1849 if (value == value_mate_in(sp->ply + 1))
1850 ss[sp->ply].mateKiller = move;
1852 if (value >= sp->beta)
1854 for (int i = 0; i < ActiveThreads; i++)
1855 if (i != threadID && (i == sp->master || sp->slaves[i]))
1856 Threads[i].stop = true;
1858 sp->finished = true;
1861 // If we are at ply 1, and we are searching the first root move at
1862 // ply 0, set the 'Problem' variable if the score has dropped a lot
1863 // (from the computer's point of view) since the previous iteration.
1866 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1869 lock_release(&(sp->lock));
1872 lock_grab(&(sp->lock));
1874 // If this is the master thread and we have been asked to stop because of
1875 // a beta cutoff higher up in the tree, stop all slave threads.
1876 if (sp->master == threadID && thread_should_stop(threadID))
1877 for (int i = 0; i < ActiveThreads; i++)
1879 Threads[i].stop = true;
1882 sp->slaves[threadID] = 0;
1884 lock_release(&(sp->lock));
1887 /// The BetaCounterType class
1889 BetaCounterType::BetaCounterType() { clear(); }
1891 void BetaCounterType::clear() {
1893 for (int i = 0; i < THREAD_MAX; i++)
1894 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1897 void BetaCounterType::add(Color us, Depth d, int threadID) {
1899 // Weighted count based on depth
1900 Threads[threadID].betaCutOffs[us] += unsigned(d);
1903 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1906 for (int i = 0; i < THREAD_MAX; i++)
1908 our += Threads[i].betaCutOffs[us];
1909 their += Threads[i].betaCutOffs[opposite_color(us)];
1914 /// The RootMove class
1918 RootMove::RootMove() {
1919 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1922 // RootMove::operator<() is the comparison function used when
1923 // sorting the moves. A move m1 is considered to be better
1924 // than a move m2 if it has a higher score, or if the moves
1925 // have equal score but m1 has the higher node count.
1927 bool RootMove::operator<(const RootMove& m) {
1929 if (score != m.score)
1930 return (score < m.score);
1932 return theirBeta <= m.theirBeta;
1935 /// The RootMoveList class
1939 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1941 MoveStack mlist[MaxRootMoves];
1942 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1944 // Generate all legal moves
1945 MoveStack* last = generate_moves(pos, mlist);
1947 // Add each move to the moves[] array
1948 for (MoveStack* cur = mlist; cur != last; cur++)
1950 bool includeMove = includeAllMoves;
1952 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1953 includeMove = (searchMoves[k] == cur->move);
1958 // Find a quick score for the move
1960 SearchStack ss[PLY_MAX_PLUS_2];
1962 moves[count].move = cur->move;
1963 pos.do_move(moves[count].move, st);
1964 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1965 pos.undo_move(moves[count].move);
1966 moves[count].pv[0] = moves[count].move;
1967 moves[count].pv[1] = MOVE_NONE; // FIXME
1974 // Simple accessor methods for the RootMoveList class
1976 inline Move RootMoveList::get_move(int moveNum) const {
1977 return moves[moveNum].move;
1980 inline Value RootMoveList::get_move_score(int moveNum) const {
1981 return moves[moveNum].score;
1984 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1985 moves[moveNum].score = score;
1988 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1989 moves[moveNum].nodes = nodes;
1990 moves[moveNum].cumulativeNodes += nodes;
1993 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1994 moves[moveNum].ourBeta = our;
1995 moves[moveNum].theirBeta = their;
1998 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
2000 for(j = 0; pv[j] != MOVE_NONE; j++)
2001 moves[moveNum].pv[j] = pv[j];
2002 moves[moveNum].pv[j] = MOVE_NONE;
2005 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2006 return moves[moveNum].pv[i];
2009 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2010 return moves[moveNum].cumulativeNodes;
2013 inline int RootMoveList::move_count() const {
2018 // RootMoveList::scan_for_easy_move() is called at the end of the first
2019 // iteration, and is used to detect an "easy move", i.e. a move which appears
2020 // to be much bester than all the rest. If an easy move is found, the move
2021 // is returned, otherwise the function returns MOVE_NONE. It is very
2022 // important that this function is called at the right moment: The code
2023 // assumes that the first iteration has been completed and the moves have
2024 // been sorted. This is done in RootMoveList c'tor.
2026 Move RootMoveList::scan_for_easy_move() const {
2033 // moves are sorted so just consider the best and the second one
2034 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2040 // RootMoveList::sort() sorts the root move list at the beginning of a new
2043 inline void RootMoveList::sort() {
2045 sort_multipv(count - 1); // all items
2049 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2050 // list by their scores and depths. It is used to order the different PVs
2051 // correctly in MultiPV mode.
2053 void RootMoveList::sort_multipv(int n) {
2055 for (int i = 1; i <= n; i++)
2057 RootMove rm = moves[i];
2059 for (j = i; j > 0 && moves[j-1] < rm; j--)
2060 moves[j] = moves[j-1];
2066 // init_node() is called at the beginning of all the search functions
2067 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2068 // stack object corresponding to the current node. Once every
2069 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2070 // for user input and checks whether it is time to stop the search.
2072 void init_node(const Position& pos, SearchStack ss[], int ply, int threadID) {
2074 assert(ply >= 0 && ply < PLY_MAX);
2075 assert(threadID >= 0 && threadID < ActiveThreads);
2077 Threads[threadID].nodes++;
2082 if (NodesSincePoll >= NodesBetweenPolls)
2089 ss[ply+2].initKillers();
2091 if (Threads[threadID].printCurrentLine)
2092 print_current_line(ss, ply, threadID);
2096 // update_pv() is called whenever a search returns a value > alpha. It
2097 // updates the PV in the SearchStack object corresponding to the current
2100 void update_pv(SearchStack ss[], int ply) {
2101 assert(ply >= 0 && ply < PLY_MAX);
2103 ss[ply].pv[ply] = ss[ply].currentMove;
2105 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2106 ss[ply].pv[p] = ss[ply+1].pv[p];
2107 ss[ply].pv[p] = MOVE_NONE;
2111 // sp_update_pv() is a variant of update_pv for use at split points. The
2112 // difference between the two functions is that sp_update_pv also updates
2113 // the PV at the parent node.
2115 void sp_update_pv(SearchStack* pss, SearchStack ss[], int ply) {
2116 assert(ply >= 0 && ply < PLY_MAX);
2118 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2120 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2121 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2122 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2126 // connected_moves() tests whether two moves are 'connected' in the sense
2127 // that the first move somehow made the second move possible (for instance
2128 // if the moving piece is the same in both moves). The first move is
2129 // assumed to be the move that was made to reach the current position, while
2130 // the second move is assumed to be a move from the current position.
2132 bool connected_moves(const Position& pos, Move m1, Move m2) {
2134 Square f1, t1, f2, t2;
2137 assert(move_is_ok(m1));
2138 assert(move_is_ok(m2));
2140 if (m2 == MOVE_NONE)
2143 // Case 1: The moving piece is the same in both moves
2149 // Case 2: The destination square for m2 was vacated by m1
2155 // Case 3: Moving through the vacated square
2156 if ( piece_is_slider(pos.piece_on(f2))
2157 && bit_is_set(squares_between(f2, t2), f1))
2160 // Case 4: The destination square for m2 is attacked by the moving piece in m1
2161 p = pos.piece_on(t1);
2162 if (bit_is_set(pos.attacks_from(p, t1), t2))
2165 // Case 5: Discovered check, checking piece is the piece moved in m1
2166 if ( piece_is_slider(p)
2167 && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
2168 && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
2170 Bitboard occ = pos.occupied_squares();
2171 Color us = pos.side_to_move();
2172 Square ksq = pos.king_square(us);
2173 clear_bit(&occ, f2);
2174 if (type_of_piece(p) == BISHOP)
2176 if (bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2179 else if (type_of_piece(p) == ROOK)
2181 if (bit_is_set(rook_attacks_bb(ksq, occ), t1))
2186 assert(type_of_piece(p) == QUEEN);
2187 if (bit_is_set(queen_attacks_bb(ksq, occ), t1))
2195 // value_is_mate() checks if the given value is a mate one
2196 // eventually compensated for the ply.
2198 bool value_is_mate(Value value) {
2200 assert(abs(value) <= VALUE_INFINITE);
2202 return value <= value_mated_in(PLY_MAX)
2203 || value >= value_mate_in(PLY_MAX);
2207 // move_is_killer() checks if the given move is among the
2208 // killer moves of that ply.
2210 bool move_is_killer(Move m, const SearchStack& ss) {
2212 const Move* k = ss.killers;
2213 for (int i = 0; i < KILLER_MAX; i++, k++)
2221 // extension() decides whether a move should be searched with normal depth,
2222 // or with extended depth. Certain classes of moves (checking moves, in
2223 // particular) are searched with bigger depth than ordinary moves and in
2224 // any case are marked as 'dangerous'. Note that also if a move is not
2225 // extended, as example because the corresponding UCI option is set to zero,
2226 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2228 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2229 bool singleReply, bool mateThreat, bool* dangerous) {
2231 assert(m != MOVE_NONE);
2233 Depth result = Depth(0);
2234 *dangerous = check | singleReply | mateThreat;
2239 result += CheckExtension[pvNode];
2242 result += SingleReplyExtension[pvNode];
2245 result += MateThreatExtension[pvNode];
2248 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2250 Color c = pos.side_to_move();
2251 if (relative_rank(c, move_to(m)) == RANK_7)
2253 result += PawnPushTo7thExtension[pvNode];
2256 if (pos.pawn_is_passed(c, move_to(m)))
2258 result += PassedPawnExtension[pvNode];
2264 && pos.type_of_piece_on(move_to(m)) != PAWN
2265 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2266 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2267 && !move_is_promotion(m)
2270 result += PawnEndgameExtension[pvNode];
2276 && pos.type_of_piece_on(move_to(m)) != PAWN
2277 && pos.see_sign(m) >= 0)
2283 return Min(result, OnePly);
2287 // ok_to_do_nullmove() looks at the current position and decides whether
2288 // doing a 'null move' should be allowed. In order to avoid zugzwang
2289 // problems, null moves are not allowed when the side to move has very
2290 // little material left. Currently, the test is a bit too simple: Null
2291 // moves are avoided only when the side to move has only pawns left. It's
2292 // probably a good idea to avoid null moves in at least some more
2293 // complicated endgames, e.g. KQ vs KR. FIXME
2295 bool ok_to_do_nullmove(const Position& pos) {
2297 return pos.non_pawn_material(pos.side_to_move()) != Value(0);
2301 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2302 // non-tactical moves late in the move list close to the leaves are
2303 // candidates for pruning.
2305 bool ok_to_prune(const Position& pos, Move m, Move threat, Depth d) {
2307 assert(move_is_ok(m));
2308 assert(threat == MOVE_NONE || move_is_ok(threat));
2309 assert(!move_is_promotion(m));
2310 assert(!pos.move_is_check(m));
2311 assert(!pos.move_is_capture(m));
2312 assert(!pos.move_is_passed_pawn_push(m));
2313 assert(d >= OnePly);
2315 Square mfrom, mto, tfrom, tto;
2317 mfrom = move_from(m);
2319 tfrom = move_from(threat);
2320 tto = move_to(threat);
2322 // Case 1: Castling moves are never pruned
2323 if (move_is_castle(m))
2326 // Case 2: Don't prune moves which move the threatened piece
2327 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2330 // Case 3: If the threatened piece has value less than or equal to the
2331 // value of the threatening piece, don't prune move which defend it.
2332 if ( !PruneDefendingMoves
2333 && threat != MOVE_NONE
2334 && pos.move_is_capture(threat)
2335 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2336 || pos.type_of_piece_on(tfrom) == KING)
2337 && pos.move_attacks_square(m, tto))
2340 // Case 4: Don't prune moves with good history
2341 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2344 // Case 5: If the moving piece in the threatened move is a slider, don't
2345 // prune safe moves which block its ray.
2346 if ( !PruneBlockingMoves
2347 && threat != MOVE_NONE
2348 && piece_is_slider(pos.piece_on(tfrom))
2349 && bit_is_set(squares_between(tfrom, tto), mto)
2350 && pos.see_sign(m) >= 0)
2357 // ok_to_use_TT() returns true if a transposition table score
2358 // can be used at a given point in search.
2360 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2362 Value v = value_from_tt(tte->value(), ply);
2364 return ( tte->depth() >= depth
2365 || v >= Max(value_mate_in(100), beta)
2366 || v < Min(value_mated_in(100), beta))
2368 && ( (is_lower_bound(tte->type()) && v >= beta)
2369 || (is_upper_bound(tte->type()) && v < beta));
2373 // ok_to_history() returns true if a move m can be stored
2374 // in history. Should be a non capturing move nor a promotion.
2376 bool ok_to_history(const Position& pos, Move m) {
2378 return !pos.move_is_capture(m) && !move_is_promotion(m);
2382 // update_history() registers a good move that produced a beta-cutoff
2383 // in history and marks as failures all the other moves of that ply.
2385 void update_history(const Position& pos, Move m, Depth depth,
2386 Move movesSearched[], int moveCount) {
2388 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2390 for (int i = 0; i < moveCount - 1; i++)
2392 assert(m != movesSearched[i]);
2393 if (ok_to_history(pos, movesSearched[i]))
2394 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2399 // update_killers() add a good move that produced a beta-cutoff
2400 // among the killer moves of that ply.
2402 void update_killers(Move m, SearchStack& ss) {
2404 if (m == ss.killers[0])
2407 for (int i = KILLER_MAX - 1; i > 0; i--)
2408 ss.killers[i] = ss.killers[i - 1];
2414 // fail_high_ply_1() checks if some thread is currently resolving a fail
2415 // high at ply 1 at the node below the first root node. This information
2416 // is used for time managment.
2418 bool fail_high_ply_1() {
2420 for(int i = 0; i < ActiveThreads; i++)
2421 if (Threads[i].failHighPly1)
2428 // current_search_time() returns the number of milliseconds which have passed
2429 // since the beginning of the current search.
2431 int current_search_time() {
2432 return get_system_time() - SearchStartTime;
2436 // nps() computes the current nodes/second count.
2439 int t = current_search_time();
2440 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2444 // poll() performs two different functions: It polls for user input, and it
2445 // looks at the time consumed so far and decides if it's time to abort the
2450 static int lastInfoTime;
2451 int t = current_search_time();
2456 // We are line oriented, don't read single chars
2457 std::string command;
2458 if (!std::getline(std::cin, command))
2461 if (command == "quit")
2464 PonderSearch = false;
2468 else if (command == "stop")
2471 PonderSearch = false;
2473 else if (command == "ponderhit")
2476 // Print search information
2480 else if (lastInfoTime > t)
2481 // HACK: Must be a new search where we searched less than
2482 // NodesBetweenPolls nodes during the first second of search.
2485 else if (t - lastInfoTime >= 1000)
2492 if (dbg_show_hit_rate)
2493 dbg_print_hit_rate();
2495 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2496 << " time " << t << " hashfull " << TT.full() << std::endl;
2497 lock_release(&IOLock);
2498 if (ShowCurrentLine)
2499 Threads[0].printCurrentLine = true;
2501 // Should we stop the search?
2505 bool overTime = t > AbsoluteMaxSearchTime
2506 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2507 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2508 && t > 6*(MaxSearchTime + ExtraSearchTime));
2510 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2511 || (ExactMaxTime && t >= ExactMaxTime)
2512 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2517 // ponderhit() is called when the program is pondering (i.e. thinking while
2518 // it's the opponent's turn to move) in order to let the engine know that
2519 // it correctly predicted the opponent's move.
2523 int t = current_search_time();
2524 PonderSearch = false;
2525 if (Iteration >= 3 &&
2526 (!InfiniteSearch && (StopOnPonderhit ||
2527 t > AbsoluteMaxSearchTime ||
2528 (RootMoveNumber == 1 &&
2529 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2530 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2531 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2536 // print_current_line() prints the current line of search for a given
2537 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2539 void print_current_line(SearchStack ss[], int ply, int threadID) {
2541 assert(ply >= 0 && ply < PLY_MAX);
2542 assert(threadID >= 0 && threadID < ActiveThreads);
2544 if (!Threads[threadID].idle)
2547 std::cout << "info currline " << (threadID + 1);
2548 for (int p = 0; p < ply; p++)
2549 std::cout << " " << ss[p].currentMove;
2551 std::cout << std::endl;
2552 lock_release(&IOLock);
2554 Threads[threadID].printCurrentLine = false;
2555 if (threadID + 1 < ActiveThreads)
2556 Threads[threadID + 1].printCurrentLine = true;
2560 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2561 // while the program is pondering. The point is to work around a wrinkle in
2562 // the UCI protocol: When pondering, the engine is not allowed to give a
2563 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2564 // We simply wait here until one of these commands is sent, and return,
2565 // after which the bestmove and pondermove will be printed (in id_loop()).
2567 void wait_for_stop_or_ponderhit() {
2569 std::string command;
2573 if (!std::getline(std::cin, command))
2576 if (command == "quit")
2581 else if (command == "ponderhit" || command == "stop")
2587 // idle_loop() is where the threads are parked when they have no work to do.
2588 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2589 // object for which the current thread is the master.
2591 void idle_loop(int threadID, SplitPoint* waitSp) {
2592 assert(threadID >= 0 && threadID < THREAD_MAX);
2594 Threads[threadID].running = true;
2597 if(AllThreadsShouldExit && threadID != 0)
2600 // If we are not thinking, wait for a condition to be signaled instead
2601 // of wasting CPU time polling for work:
2602 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2603 #if !defined(_MSC_VER)
2604 pthread_mutex_lock(&WaitLock);
2605 if(Idle || threadID >= ActiveThreads)
2606 pthread_cond_wait(&WaitCond, &WaitLock);
2607 pthread_mutex_unlock(&WaitLock);
2609 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2613 // If this thread has been assigned work, launch a search
2614 if(Threads[threadID].workIsWaiting) {
2615 Threads[threadID].workIsWaiting = false;
2616 if(Threads[threadID].splitPoint->pvNode)
2617 sp_search_pv(Threads[threadID].splitPoint, threadID);
2619 sp_search(Threads[threadID].splitPoint, threadID);
2620 Threads[threadID].idle = true;
2623 // If this thread is the master of a split point and all threads have
2624 // finished their work at this split point, return from the idle loop.
2625 if(waitSp != NULL && waitSp->cpus == 0)
2629 Threads[threadID].running = false;
2633 // init_split_point_stack() is called during program initialization, and
2634 // initializes all split point objects.
2636 void init_split_point_stack() {
2637 for(int i = 0; i < THREAD_MAX; i++)
2638 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2639 SplitPointStack[i][j].parent = NULL;
2640 lock_init(&(SplitPointStack[i][j].lock), NULL);
2645 // destroy_split_point_stack() is called when the program exits, and
2646 // destroys all locks in the precomputed split point objects.
2648 void destroy_split_point_stack() {
2649 for(int i = 0; i < THREAD_MAX; i++)
2650 for(int j = 0; j < MaxActiveSplitPoints; j++)
2651 lock_destroy(&(SplitPointStack[i][j].lock));
2655 // thread_should_stop() checks whether the thread with a given threadID has
2656 // been asked to stop, directly or indirectly. This can happen if a beta
2657 // cutoff has occured in thre thread's currently active split point, or in
2658 // some ancestor of the current split point.
2660 bool thread_should_stop(int threadID) {
2661 assert(threadID >= 0 && threadID < ActiveThreads);
2665 if(Threads[threadID].stop)
2667 if(ActiveThreads <= 2)
2669 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2671 Threads[threadID].stop = true;
2678 // thread_is_available() checks whether the thread with threadID "slave" is
2679 // available to help the thread with threadID "master" at a split point. An
2680 // obvious requirement is that "slave" must be idle. With more than two
2681 // threads, this is not by itself sufficient: If "slave" is the master of
2682 // some active split point, it is only available as a slave to the other
2683 // threads which are busy searching the split point at the top of "slave"'s
2684 // split point stack (the "helpful master concept" in YBWC terminology).
2686 bool thread_is_available(int slave, int master) {
2687 assert(slave >= 0 && slave < ActiveThreads);
2688 assert(master >= 0 && master < ActiveThreads);
2689 assert(ActiveThreads > 1);
2691 if(!Threads[slave].idle || slave == master)
2694 if(Threads[slave].activeSplitPoints == 0)
2695 // No active split points means that the thread is available as a slave
2696 // for any other thread.
2699 if(ActiveThreads == 2)
2702 // Apply the "helpful master" concept if possible.
2703 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2710 // idle_thread_exists() tries to find an idle thread which is available as
2711 // a slave for the thread with threadID "master".
2713 bool idle_thread_exists(int master) {
2714 assert(master >= 0 && master < ActiveThreads);
2715 assert(ActiveThreads > 1);
2717 for(int i = 0; i < ActiveThreads; i++)
2718 if(thread_is_available(i, master))
2724 // split() does the actual work of distributing the work at a node between
2725 // several threads at PV nodes. If it does not succeed in splitting the
2726 // node (because no idle threads are available, or because we have no unused
2727 // split point objects), the function immediately returns false. If
2728 // splitting is possible, a SplitPoint object is initialized with all the
2729 // data that must be copied to the helper threads (the current position and
2730 // search stack, alpha, beta, the search depth, etc.), and we tell our
2731 // helper threads that they have been assigned work. This will cause them
2732 // to instantly leave their idle loops and call sp_search_pv(). When all
2733 // threads have returned from sp_search_pv (or, equivalently, when
2734 // splitPoint->cpus becomes 0), split() returns true.
2736 bool split(const Position& p, SearchStack* sstck, int ply,
2737 Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves,
2738 MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) {
2741 assert(sstck != NULL);
2742 assert(ply >= 0 && ply < PLY_MAX);
2743 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2744 assert(!pvNode || *alpha < *beta);
2745 assert(*beta <= VALUE_INFINITE);
2746 assert(depth > Depth(0));
2747 assert(master >= 0 && master < ActiveThreads);
2748 assert(ActiveThreads > 1);
2750 SplitPoint* splitPoint;
2755 // If no other thread is available to help us, or if we have too many
2756 // active split points, don't split.
2757 if(!idle_thread_exists(master) ||
2758 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2759 lock_release(&MPLock);
2763 // Pick the next available split point object from the split point stack
2764 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2765 Threads[master].activeSplitPoints++;
2767 // Initialize the split point object
2768 splitPoint->parent = Threads[master].splitPoint;
2769 splitPoint->finished = false;
2770 splitPoint->ply = ply;
2771 splitPoint->depth = depth;
2772 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2773 splitPoint->beta = *beta;
2774 splitPoint->pvNode = pvNode;
2775 splitPoint->dcCandidates = dcCandidates;
2776 splitPoint->bestValue = *bestValue;
2777 splitPoint->master = master;
2778 splitPoint->mp = mp;
2779 splitPoint->moves = *moves;
2780 splitPoint->cpus = 1;
2781 splitPoint->pos.copy(p);
2782 splitPoint->parentSstack = sstck;
2783 for(i = 0; i < ActiveThreads; i++)
2784 splitPoint->slaves[i] = 0;
2786 // Copy the current position and the search stack to the master thread
2787 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2788 Threads[master].splitPoint = splitPoint;
2790 // Make copies of the current position and search stack for each thread
2791 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2793 if(thread_is_available(i, master)) {
2794 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2795 Threads[i].splitPoint = splitPoint;
2796 splitPoint->slaves[i] = 1;
2800 // Tell the threads that they have work to do. This will make them leave
2802 for(i = 0; i < ActiveThreads; i++)
2803 if(i == master || splitPoint->slaves[i]) {
2804 Threads[i].workIsWaiting = true;
2805 Threads[i].idle = false;
2806 Threads[i].stop = false;
2809 lock_release(&MPLock);
2811 // Everything is set up. The master thread enters the idle loop, from
2812 // which it will instantly launch a search, because its workIsWaiting
2813 // slot is 'true'. We send the split point as a second parameter to the
2814 // idle loop, which means that the main thread will return from the idle
2815 // loop when all threads have finished their work at this split point
2816 // (i.e. when // splitPoint->cpus == 0).
2817 idle_loop(master, splitPoint);
2819 // We have returned from the idle loop, which means that all threads are
2820 // finished. Update alpha, beta and bestvalue, and return.
2822 if(pvNode) *alpha = splitPoint->alpha;
2823 *beta = splitPoint->beta;
2824 *bestValue = splitPoint->bestValue;
2825 Threads[master].stop = false;
2826 Threads[master].idle = false;
2827 Threads[master].activeSplitPoints--;
2828 Threads[master].splitPoint = splitPoint->parent;
2829 lock_release(&MPLock);
2835 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2836 // to start a new search from the root.
2838 void wake_sleeping_threads() {
2839 if(ActiveThreads > 1) {
2840 for(int i = 1; i < ActiveThreads; i++) {
2841 Threads[i].idle = true;
2842 Threads[i].workIsWaiting = false;
2844 #if !defined(_MSC_VER)
2845 pthread_mutex_lock(&WaitLock);
2846 pthread_cond_broadcast(&WaitCond);
2847 pthread_mutex_unlock(&WaitLock);
2849 for(int i = 1; i < THREAD_MAX; i++)
2850 SetEvent(SitIdleEvent[i]);
2856 // init_thread() is the function which is called when a new thread is
2857 // launched. It simply calls the idle_loop() function with the supplied
2858 // threadID. There are two versions of this function; one for POSIX threads
2859 // and one for Windows threads.
2861 #if !defined(_MSC_VER)
2863 void *init_thread(void *threadID) {
2864 idle_loop(*(int *)threadID, NULL);
2870 DWORD WINAPI init_thread(LPVOID threadID) {
2871 idle_loop(*(int *)threadID, NULL);