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/>.
40 #include "ucioption.h"
44 //// Local definitions
51 // IterationInfoType stores search results for each iteration
53 // Because we use relatively small (dynamic) aspiration window,
54 // there happens many fail highs and fail lows in root. And
55 // because we don't do researches in those cases, "value" stored
56 // here is not necessarily exact. Instead in case of fail high/low
57 // we guess what the right value might be and store our guess
58 // as a "speculated value" and then move on. Speculated values are
59 // used just to calculate aspiration window width, so also if are
60 // not exact is not big a problem.
62 struct IterationInfoType {
64 IterationInfoType(Value v = Value(0), Value sv = Value(0))
65 : value(v), speculatedValue(sv) {}
67 Value value, speculatedValue;
71 // The BetaCounterType class is used to order moves at ply one.
72 // Apart for the first one that has its score, following moves
73 // normally have score -VALUE_INFINITE, so are ordered according
74 // to the number of beta cutoffs occurred under their subtree during
75 // the last iteration. The counters are per thread variables to avoid
76 // concurrent accessing under SMP case.
78 struct BetaCounterType {
82 void add(Color us, Depth d, int threadID);
83 void read(Color us, int64_t& our, int64_t& their);
87 // The RootMove class is used for moves at the root at the tree. For each
88 // root move, we store a score, a node count, and a PV (really a refutation
89 // in the case of moves which fail low).
94 bool operator<(const RootMove&); // used to sort
98 int64_t nodes, cumulativeNodes;
99 Move pv[PLY_MAX_PLUS_2];
100 int64_t ourBeta, theirBeta;
104 // The RootMoveList class is essentially an array of RootMove objects, with
105 // a handful of methods for accessing the data in the individual moves.
110 RootMoveList(Position &pos, Move searchMoves[]);
111 inline Move get_move(int moveNum) const;
112 inline Value get_move_score(int moveNum) const;
113 inline void set_move_score(int moveNum, Value score);
114 inline void set_move_nodes(int moveNum, int64_t nodes);
115 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
116 void set_move_pv(int moveNum, const Move pv[]);
117 inline Move get_move_pv(int moveNum, int i) const;
118 inline int64_t get_move_cumulative_nodes(int moveNum) const;
119 inline int move_count() const;
120 Move scan_for_easy_move() const;
122 void sort_multipv(int n);
125 static const int MaxRootMoves = 500;
126 RootMove moves[MaxRootMoves];
131 /// Constants and variables initialized from UCI options
133 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
135 int LMRPVMoves, LMRNonPVMoves;
137 // Depth limit for use of dynamic threat detection
140 // Depth limit for selective search
141 const Depth SelectiveDepth = 7*OnePly;
143 // Use internal iterative deepening?
144 const bool UseIIDAtPVNodes = true;
145 const bool UseIIDAtNonPVNodes = false;
147 // Internal iterative deepening margin. At Non-PV moves, when
148 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
149 // when the static evaluation is at most IIDMargin below beta.
150 const Value IIDMargin = Value(0x100);
152 // Easy move margin. An easy move candidate must be at least this much
153 // better than the second best move.
154 const Value EasyMoveMargin = Value(0x200);
156 // Problem margin. If the score of the first move at iteration N+1 has
157 // dropped by more than this since iteration N, the boolean variable
158 // "Problem" is set to true, which will make the program spend some extra
159 // time looking for a better move.
160 const Value ProblemMargin = Value(0x28);
162 // No problem margin. If the boolean "Problem" is true, and a new move
163 // is found at the root which is less than NoProblemMargin worse than the
164 // best move from the previous iteration, Problem is set back to false.
165 const Value NoProblemMargin = Value(0x14);
167 // Null move margin. A null move search will not be done if the approximate
168 // evaluation of the position is more than NullMoveMargin below beta.
169 const Value NullMoveMargin = Value(0x300);
171 // Pruning criterions. See the code and comments in ok_to_prune() to
172 // understand their precise meaning.
173 const bool PruneEscapeMoves = false;
174 const bool PruneDefendingMoves = false;
175 const bool PruneBlockingMoves = false;
177 // Use futility pruning?
178 bool UseQSearchFutilityPruning, UseFutilityPruning;
180 // Margins for futility pruning in the quiescence search, and at frontier
181 // and near frontier nodes
182 const Value FutilityMarginQS = Value(0x80);
184 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
185 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
186 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
187 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
189 const Depth RazorDepth = 4*OnePly;
191 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
192 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
194 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
195 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
197 // Last seconds noise filtering (LSN)
198 bool UseLSNFiltering;
199 bool looseOnTime = false;
200 int LSNTime; // In milliseconds
203 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
204 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
205 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
207 // Search depth at iteration 1
208 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
212 int NodesBetweenPolls = 30000;
214 // Iteration counters
216 BetaCounterType BetaCounter;
218 // Scores and number of times the best move changed for each iteration:
219 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
220 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
225 // Time managment variables
227 int MaxNodes, MaxDepth;
228 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
233 bool StopOnPonderhit;
239 bool PonderingEnabled;
242 // Show current line?
243 bool ShowCurrentLine;
247 std::ofstream LogFile;
249 // MP related variables
250 Depth MinimumSplitDepth;
251 int MaxThreadsPerSplitPoint;
252 Thread Threads[THREAD_MAX];
254 bool AllThreadsShouldExit = false;
255 const int MaxActiveSplitPoints = 8;
256 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
259 #if !defined(_MSC_VER)
260 pthread_cond_t WaitCond;
261 pthread_mutex_t WaitLock;
263 HANDLE SitIdleEvent[THREAD_MAX];
269 Value id_loop(const Position &pos, Move searchMoves[]);
270 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta);
271 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
272 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
273 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
274 void sp_search(SplitPoint *sp, int threadID);
275 void sp_search_pv(SplitPoint *sp, int threadID);
276 void init_node(SearchStack ss[], int ply, int threadID);
277 void update_pv(SearchStack ss[], int ply);
278 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
279 bool connected_moves(const Position &pos, Move m1, Move m2);
280 bool value_is_mate(Value value);
281 bool move_is_killer(Move m, const SearchStack& ss);
282 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
283 bool ok_to_do_nullmove(const Position &pos);
284 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
285 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
286 bool ok_to_history(const Position &pos, Move m);
287 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
288 void update_killers(Move m, SearchStack& ss);
290 bool fail_high_ply_1();
291 int current_search_time();
295 void print_current_line(SearchStack ss[], int ply, int threadID);
296 void wait_for_stop_or_ponderhit();
298 void idle_loop(int threadID, SplitPoint *waitSp);
299 void init_split_point_stack();
300 void destroy_split_point_stack();
301 bool thread_should_stop(int threadID);
302 bool thread_is_available(int slave, int master);
303 bool idle_thread_exists(int master);
304 bool split(const Position &pos, SearchStack *ss, int ply,
305 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
306 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
307 void wake_sleeping_threads();
309 #if !defined(_MSC_VER)
310 void *init_thread(void *threadID);
312 DWORD WINAPI init_thread(LPVOID threadID);
319 //// Global variables
322 // The main transposition table
323 TranspositionTable TT;
326 // Number of active threads:
327 int ActiveThreads = 1;
329 // Locks. In principle, there is no need for IOLock to be a global variable,
330 // but it could turn out to be useful for debugging.
333 History H; // Should be made local?
336 // SearchStack::init() initializes a search stack. Used at the beginning of a
337 // new search from the root.
338 void SearchStack::init(int ply) {
340 pv[ply] = pv[ply + 1] = MOVE_NONE;
341 currentMove = threatMove = MOVE_NONE;
342 reduction = Depth(0);
345 void SearchStack::initKillers() {
347 mateKiller = MOVE_NONE;
348 for (int i = 0; i < KILLER_MAX; i++)
349 killers[i] = MOVE_NONE;
357 /// think() is the external interface to Stockfish's search, and is called when
358 /// the program receives the UCI 'go' command. It initializes various
359 /// search-related global variables, and calls root_search(). It returns false
360 /// when a quit command is received during the search.
362 bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
363 int time[], int increment[], int movesToGo, int maxDepth,
364 int maxNodes, int maxTime, Move searchMoves[]) {
366 // Look for a book move
367 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
370 if (get_option_value_string("Book File") != OpeningBook.file_name())
371 OpeningBook.open("book.bin");
373 bookMove = OpeningBook.get_move(pos);
374 if (bookMove != MOVE_NONE)
376 std::cout << "bestmove " << bookMove << std::endl;
381 // Initialize global search variables
383 SearchStartTime = get_system_time();
384 EasyMove = MOVE_NONE;
385 for (int i = 0; i < THREAD_MAX; i++)
387 Threads[i].nodes = 0ULL;
388 Threads[i].failHighPly1 = false;
391 InfiniteSearch = infinite;
392 PonderSearch = ponder;
393 StopOnPonderhit = false;
399 ExactMaxTime = maxTime;
401 // Read UCI option values
402 TT.set_size(get_option_value_int("Hash"));
403 if (button_was_pressed("Clear Hash"))
406 PonderingEnabled = get_option_value_bool("Ponder");
407 MultiPV = get_option_value_int("MultiPV");
409 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
410 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
412 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
413 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
415 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
416 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
418 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
419 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
421 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
422 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
424 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
425 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
427 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
428 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
429 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
431 Chess960 = get_option_value_bool("UCI_Chess960");
432 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
433 UseLogFile = get_option_value_bool("Use Search Log");
435 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
437 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
438 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
440 UseLSNFiltering = get_option_value_bool("LSN filtering");
441 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
442 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
444 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
445 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
447 read_weights(pos.side_to_move());
449 int newActiveThreads = get_option_value_int("Threads");
450 if (newActiveThreads != ActiveThreads)
452 ActiveThreads = newActiveThreads;
453 init_eval(ActiveThreads);
456 // Wake up sleeping threads:
457 wake_sleeping_threads();
459 for (int i = 1; i < ActiveThreads; i++)
460 assert(thread_is_available(i, 0));
462 // Set thinking time:
463 int myTime = time[side_to_move];
464 int myIncrement = increment[side_to_move];
466 if (!movesToGo) // Sudden death time control
470 MaxSearchTime = myTime / 30 + myIncrement;
471 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
472 } else { // Blitz game without increment
473 MaxSearchTime = myTime / 30;
474 AbsoluteMaxSearchTime = myTime / 8;
477 else // (x moves) / (y minutes)
481 MaxSearchTime = myTime / 2;
482 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
484 MaxSearchTime = myTime / Min(movesToGo, 20);
485 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
489 if (PonderingEnabled)
491 MaxSearchTime += MaxSearchTime / 4;
492 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
495 // Fixed depth or fixed number of nodes?
498 InfiniteSearch = true; // HACK
503 NodesBetweenPolls = Min(MaxNodes, 30000);
504 InfiniteSearch = true; // HACK
507 NodesBetweenPolls = 30000;
510 // Write information to search log file:
512 LogFile << "Searching: " << pos.to_fen() << std::endl
513 << "infinite: " << infinite
514 << " ponder: " << ponder
515 << " time: " << myTime
516 << " increment: " << myIncrement
517 << " moves to go: " << movesToGo << std::endl;
520 // We're ready to start thinking. Call the iterative deepening loop
524 Value v = id_loop(pos, searchMoves);
525 looseOnTime = ( UseLSNFiltering
532 looseOnTime = false; // reset for next match
533 while (SearchStartTime + myTime + 1000 > get_system_time())
535 id_loop(pos, searchMoves); // to fail gracefully
546 /// init_threads() is called during startup. It launches all helper threads,
547 /// and initializes the split point stack and the global locks and condition
550 void init_threads() {
554 #if !defined(_MSC_VER)
555 pthread_t pthread[1];
558 for (i = 0; i < THREAD_MAX; i++)
559 Threads[i].activeSplitPoints = 0;
561 // Initialize global locks:
562 lock_init(&MPLock, NULL);
563 lock_init(&IOLock, NULL);
565 init_split_point_stack();
567 #if !defined(_MSC_VER)
568 pthread_mutex_init(&WaitLock, NULL);
569 pthread_cond_init(&WaitCond, NULL);
571 for (i = 0; i < THREAD_MAX; i++)
572 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
575 // All threads except the main thread should be initialized to idle state
576 for (i = 1; i < THREAD_MAX; i++)
578 Threads[i].stop = false;
579 Threads[i].workIsWaiting = false;
580 Threads[i].idle = true;
581 Threads[i].running = false;
584 // Launch the helper threads
585 for(i = 1; i < THREAD_MAX; i++)
587 #if !defined(_MSC_VER)
588 pthread_create(pthread, NULL, init_thread, (void*)(&i));
591 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
594 // Wait until the thread has finished launching:
595 while (!Threads[i].running);
600 /// stop_threads() is called when the program exits. It makes all the
601 /// helper threads exit cleanly.
603 void stop_threads() {
605 ActiveThreads = THREAD_MAX; // HACK
606 Idle = false; // HACK
607 wake_sleeping_threads();
608 AllThreadsShouldExit = true;
609 for (int i = 1; i < THREAD_MAX; i++)
611 Threads[i].stop = true;
612 while(Threads[i].running);
614 destroy_split_point_stack();
618 /// nodes_searched() returns the total number of nodes searched so far in
619 /// the current search.
621 int64_t nodes_searched() {
623 int64_t result = 0ULL;
624 for (int i = 0; i < ActiveThreads; i++)
625 result += Threads[i].nodes;
632 // id_loop() is the main iterative deepening loop. It calls root_search
633 // repeatedly with increasing depth until the allocated thinking time has
634 // been consumed, the user stops the search, or the maximum search depth is
637 Value id_loop(const Position &pos, Move searchMoves[]) {
640 SearchStack ss[PLY_MAX_PLUS_2];
642 // searchMoves are verified, copied, scored and sorted
643 RootMoveList rml(p, searchMoves);
648 for (int i = 0; i < 3; i++)
653 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
656 EasyMove = rml.scan_for_easy_move();
658 // Iterative deepening loop
659 while (Iteration < PLY_MAX)
661 // Initialize iteration
664 BestMoveChangesByIteration[Iteration] = 0;
668 std::cout << "info depth " << Iteration << std::endl;
670 // Calculate dynamic search window based on previous iterations
673 if (MultiPV == 1 && Iteration >= 6)
675 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
676 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
678 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
680 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
681 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
685 alpha = - VALUE_INFINITE;
686 beta = VALUE_INFINITE;
689 // Search to the current depth
690 Value value = root_search(p, ss, rml, alpha, beta);
692 // Write PV to transposition table, in case the relevant entries have
693 // been overwritten during the search.
694 TT.insert_pv(p, ss[0].pv);
697 break; // Value cannot be trusted. Break out immediately!
699 //Save info about search result
700 Value speculatedValue;
703 Value delta = value - IterationInfo[Iteration - 1].value;
710 speculatedValue = value + delta;
711 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
713 else if (value <= alpha)
715 assert(value == alpha);
719 speculatedValue = value + delta;
720 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
722 speculatedValue = value;
724 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
725 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
727 // Erase the easy move if it differs from the new best move
728 if (ss[0].pv[0] != EasyMove)
729 EasyMove = MOVE_NONE;
736 bool stopSearch = false;
738 // Stop search early if there is only a single legal move:
739 if (Iteration >= 6 && rml.move_count() == 1)
742 // Stop search early when the last two iterations returned a mate score
744 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
745 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
748 // Stop search early if one move seems to be much better than the rest
749 int64_t nodes = nodes_searched();
753 && EasyMove == ss[0].pv[0]
754 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
755 && current_search_time() > MaxSearchTime / 16)
756 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
757 && current_search_time() > MaxSearchTime / 32)))
760 // Add some extra time if the best move has changed during the last two iterations
761 if (Iteration > 5 && Iteration <= 50)
762 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
763 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
765 // Stop search if most of MaxSearchTime is consumed at the end of the
766 // iteration. We probably don't have enough time to search the first
767 // move at the next iteration anyway.
768 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
773 //FIXME: Implement fail-low emergency measures
777 StopOnPonderhit = true;
781 if (MaxDepth && Iteration >= MaxDepth)
787 // If we are pondering, we shouldn't print the best move before we
790 wait_for_stop_or_ponderhit();
792 // Print final search statistics
793 std::cout << "info nodes " << nodes_searched()
795 << " time " << current_search_time()
796 << " hashfull " << TT.full() << std::endl;
798 // Print the best move and the ponder move to the standard output
799 if (ss[0].pv[0] == MOVE_NONE)
801 ss[0].pv[0] = rml.get_move(0);
802 ss[0].pv[1] = MOVE_NONE;
804 std::cout << "bestmove " << ss[0].pv[0];
805 if (ss[0].pv[1] != MOVE_NONE)
806 std::cout << " ponder " << ss[0].pv[1];
808 std::cout << std::endl;
813 dbg_print_mean(LogFile);
815 if (dbg_show_hit_rate)
816 dbg_print_hit_rate(LogFile);
819 LogFile << "Nodes: " << nodes_searched() << std::endl
820 << "Nodes/second: " << nps() << std::endl
821 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
823 p.do_move(ss[0].pv[0], st);
824 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
825 << std::endl << std::endl;
827 return rml.get_move_score(0);
831 // root_search() is the function which searches the root node. It is
832 // similar to search_pv except that it uses a different move ordering
833 // scheme (perhaps we should try to use this at internal PV nodes, too?)
834 // and prints some information to the standard output.
836 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
838 Value oldAlpha = alpha;
840 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
842 // Loop through all the moves in the root move list
843 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
847 // We failed high, invalidate and skip next moves, leave node-counters
848 // and beta-counters as they are and quickly return, we will try to do
849 // a research at the next iteration with a bigger aspiration window.
850 rml.set_move_score(i, -VALUE_INFINITE);
858 RootMoveNumber = i + 1;
861 // Remember the node count before the move is searched. The node counts
862 // are used to sort the root moves at the next iteration.
863 nodes = nodes_searched();
865 // Reset beta cut-off counters
868 // Pick the next root move, and print the move and the move number to
869 // the standard output.
870 move = ss[0].currentMove = rml.get_move(i);
871 if (current_search_time() >= 1000)
872 std::cout << "info currmove " << move
873 << " currmovenumber " << i + 1 << std::endl;
875 // Decide search depth for this move
877 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
878 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
880 // Make the move, and search it
881 pos.do_move(move, st, dcCandidates);
885 // Aspiration window is disabled in multi-pv case
887 alpha = -VALUE_INFINITE;
889 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
890 // If the value has dropped a lot compared to the last iteration,
891 // set the boolean variable Problem to true. This variable is used
892 // for time managment: When Problem is true, we try to complete the
893 // current iteration before playing a move.
894 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
896 if (Problem && StopOnPonderhit)
897 StopOnPonderhit = false;
901 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
904 // Fail high! Set the boolean variable FailHigh to true, and
905 // re-search the move with a big window. The variable FailHigh is
906 // used for time managment: We try to avoid aborting the search
907 // prematurely during a fail high research.
909 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
915 // Finished searching the move. If AbortSearch is true, the search
916 // was aborted because the user interrupted the search or because we
917 // ran out of time. In this case, the return value of the search cannot
918 // be trusted, and we break out of the loop without updating the best
923 // Remember the node count for this move. The node counts are used to
924 // sort the root moves at the next iteration.
925 rml.set_move_nodes(i, nodes_searched() - nodes);
927 // Remember the beta-cutoff statistics
929 BetaCounter.read(pos.side_to_move(), our, their);
930 rml.set_beta_counters(i, our, their);
932 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
934 if (value <= alpha && i >= MultiPV)
935 rml.set_move_score(i, -VALUE_INFINITE);
938 // PV move or new best move!
941 rml.set_move_score(i, value);
943 rml.set_move_pv(i, ss[0].pv);
947 // We record how often the best move has been changed in each
948 // iteration. This information is used for time managment: When
949 // the best move changes frequently, we allocate some more time.
951 BestMoveChangesByIteration[Iteration]++;
953 // Print search information to the standard output:
954 std::cout << "info depth " << Iteration
955 << " score " << value_to_string(value)
956 << " time " << current_search_time()
957 << " nodes " << nodes_searched()
961 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
962 std::cout << ss[0].pv[j] << " ";
964 std::cout << std::endl;
967 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
973 // Reset the global variable Problem to false if the value isn't too
974 // far below the final value from the last iteration.
975 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
981 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
984 std::cout << "info multipv " << j + 1
985 << " score " << value_to_string(rml.get_move_score(j))
986 << " depth " << ((j <= i)? Iteration : Iteration - 1)
987 << " time " << current_search_time()
988 << " nodes " << nodes_searched()
992 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
993 std::cout << rml.get_move_pv(j, k) << " ";
995 std::cout << std::endl;
997 alpha = rml.get_move_score(Min(i, MultiPV-1));
999 } // New best move case
1001 assert(alpha >= oldAlpha);
1003 FailLow = (alpha == oldAlpha);
1009 // search_pv() is the main search function for PV nodes.
1011 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1012 Depth depth, int ply, int threadID) {
1014 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1015 assert(beta > alpha && beta <= VALUE_INFINITE);
1016 assert(ply >= 0 && ply < PLY_MAX);
1017 assert(threadID >= 0 && threadID < ActiveThreads);
1020 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1022 // Initialize, and make an early exit in case of an aborted search,
1023 // an instant draw, maximum ply reached, etc.
1024 init_node(ss, ply, threadID);
1026 // After init_node() that calls poll()
1027 if (AbortSearch || thread_should_stop(threadID))
1035 if (ply >= PLY_MAX - 1)
1036 return evaluate(pos, ei, threadID);
1038 // Mate distance pruning
1039 Value oldAlpha = alpha;
1040 alpha = Max(value_mated_in(ply), alpha);
1041 beta = Min(value_mate_in(ply+1), beta);
1045 // Transposition table lookup. At PV nodes, we don't use the TT for
1046 // pruning, but only for move ordering.
1047 const TTEntry* tte = TT.retrieve(pos.get_key());
1048 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1050 // Go with internal iterative deepening if we don't have a TT move
1051 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1053 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1054 ttMove = ss[ply].pv[ply];
1057 // Initialize a MovePicker object for the current position, and prepare
1058 // to search all moves
1059 MovePicker mp = MovePicker(pos, true, ttMove, depth, &ss[ply]);
1061 Move move, movesSearched[256];
1063 Value value, bestValue = -VALUE_INFINITE;
1064 Bitboard dcCandidates = mp.discovered_check_candidates();
1065 Color us = pos.side_to_move();
1066 bool isCheck = pos.is_check();
1067 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1069 // Loop through all legal moves until no moves remain or a beta cutoff
1071 while ( alpha < beta
1072 && (move = mp.get_next_move()) != MOVE_NONE
1073 && !thread_should_stop(threadID))
1075 assert(move_is_ok(move));
1077 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1078 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1079 bool moveIsCapture = pos.move_is_capture(move);
1081 movesSearched[moveCount++] = ss[ply].currentMove = move;
1083 // Decide the new search depth
1085 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1086 Depth newDepth = depth - OnePly + ext;
1088 // Make and search the move
1090 pos.do_move(move, st, dcCandidates);
1092 if (moveCount == 1) // The first move in list is the PV
1093 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1096 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1097 // if the move fails high will be re-searched at full depth.
1098 if ( depth >= 2*OnePly
1099 && moveCount >= LMRPVMoves
1102 && !move_promotion(move)
1103 && !move_is_castle(move)
1104 && !move_is_killer(move, ss[ply]))
1106 ss[ply].reduction = OnePly;
1107 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1110 value = alpha + 1; // Just to trigger next condition
1112 if (value > alpha) // Go with full depth non-pv search
1114 ss[ply].reduction = Depth(0);
1115 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1116 if (value > alpha && value < beta)
1118 // When the search fails high at ply 1 while searching the first
1119 // move at the root, set the flag failHighPly1. This is used for
1120 // time managment: We don't want to stop the search early in
1121 // such cases, because resolving the fail high at ply 1 could
1122 // result in a big drop in score at the root.
1123 if (ply == 1 && RootMoveNumber == 1)
1124 Threads[threadID].failHighPly1 = true;
1126 // A fail high occurred. Re-search at full window (pv search)
1127 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1128 Threads[threadID].failHighPly1 = false;
1132 pos.undo_move(move);
1134 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1137 if (value > bestValue)
1144 if (value == value_mate_in(ply + 1))
1145 ss[ply].mateKiller = move;
1147 // If we are at ply 1, and we are searching the first root move at
1148 // ply 0, set the 'Problem' variable if the score has dropped a lot
1149 // (from the computer's point of view) since the previous iteration:
1152 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1157 if ( ActiveThreads > 1
1159 && depth >= MinimumSplitDepth
1161 && idle_thread_exists(threadID)
1163 && !thread_should_stop(threadID)
1164 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1165 &moveCount, &mp, dcCandidates, threadID, true))
1169 // All legal moves have been searched. A special case: If there were
1170 // no legal moves, it must be mate or stalemate:
1172 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1174 // If the search is not aborted, update the transposition table,
1175 // history counters, and killer moves.
1176 if (AbortSearch || thread_should_stop(threadID))
1179 if (bestValue <= oldAlpha)
1180 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1182 else if (bestValue >= beta)
1184 BetaCounter.add(pos.side_to_move(), depth, threadID);
1185 Move m = ss[ply].pv[ply];
1186 if (ok_to_history(pos, m)) // Only non capture moves are considered
1188 update_history(pos, m, depth, movesSearched, moveCount);
1189 update_killers(m, ss[ply]);
1191 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1194 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1200 // search() is the search function for zero-width nodes.
1202 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1203 int ply, bool allowNullmove, int threadID) {
1205 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1206 assert(ply >= 0 && ply < PLY_MAX);
1207 assert(threadID >= 0 && threadID < ActiveThreads);
1210 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1212 // Initialize, and make an early exit in case of an aborted search,
1213 // an instant draw, maximum ply reached, etc.
1214 init_node(ss, ply, threadID);
1216 // After init_node() that calls poll()
1217 if (AbortSearch || thread_should_stop(threadID))
1225 if (ply >= PLY_MAX - 1)
1226 return evaluate(pos, ei, threadID);
1228 // Mate distance pruning
1229 if (value_mated_in(ply) >= beta)
1232 if (value_mate_in(ply + 1) < beta)
1235 // Transposition table lookup
1236 const TTEntry* tte = TT.retrieve(pos.get_key());
1237 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1239 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1241 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1242 return value_from_tt(tte->value(), ply);
1245 Value approximateEval = quick_evaluate(pos);
1246 bool mateThreat = false;
1247 bool isCheck = pos.is_check();
1253 && !value_is_mate(beta)
1254 && ok_to_do_nullmove(pos)
1255 && approximateEval >= beta - NullMoveMargin)
1257 ss[ply].currentMove = MOVE_NULL;
1260 pos.do_null_move(st);
1261 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1263 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1265 pos.undo_null_move();
1267 if (value_is_mate(nullValue))
1269 /* Do not return unproven mates */
1271 else if (nullValue >= beta)
1273 if (depth < 6 * OnePly)
1276 // Do zugzwang verification search
1277 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1281 // The null move failed low, which means that we may be faced with
1282 // some kind of threat. If the previous move was reduced, check if
1283 // the move that refuted the null move was somehow connected to the
1284 // move which was reduced. If a connection is found, return a fail
1285 // low score (which will cause the reduced move to fail high in the
1286 // parent node, which will trigger a re-search with full depth).
1287 if (nullValue == value_mated_in(ply + 2))
1290 ss[ply].threatMove = ss[ply + 1].currentMove;
1291 if ( depth < ThreatDepth
1292 && ss[ply - 1].reduction
1293 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1297 // Null move search not allowed, try razoring
1298 else if ( !value_is_mate(beta)
1299 && depth < RazorDepth
1300 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1301 && ss[ply - 1].currentMove != MOVE_NULL
1302 && ttMove == MOVE_NONE
1303 && !pos.has_pawn_on_7th(pos.side_to_move()))
1305 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1306 if (v < beta - RazorMargins[int(depth) - 2])
1310 // Go with internal iterative deepening if we don't have a TT move
1311 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1312 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1314 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1315 ttMove = ss[ply].pv[ply];
1318 // Initialize a MovePicker object for the current position, and prepare
1319 // to search all moves:
1320 MovePicker mp = MovePicker(pos, false, ttMove, depth, &ss[ply]);
1322 Move move, movesSearched[256];
1324 Value value, bestValue = -VALUE_INFINITE;
1325 Bitboard dcCandidates = mp.discovered_check_candidates();
1326 Value futilityValue = VALUE_NONE;
1327 bool useFutilityPruning = UseFutilityPruning
1328 && depth < SelectiveDepth
1331 // Loop through all legal moves until no moves remain or a beta cutoff
1333 while ( bestValue < beta
1334 && (move = mp.get_next_move()) != MOVE_NONE
1335 && !thread_should_stop(threadID))
1337 assert(move_is_ok(move));
1339 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1340 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1341 bool moveIsCapture = pos.move_is_capture(move);
1343 movesSearched[moveCount++] = ss[ply].currentMove = move;
1345 // Decide the new search depth
1347 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1348 Depth newDepth = depth - OnePly + ext;
1351 if ( useFutilityPruning
1354 && !move_promotion(move))
1356 // History pruning. See ok_to_prune() definition
1357 if ( moveCount >= 2 + int(depth)
1358 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1361 // Value based pruning
1362 if (approximateEval < beta)
1364 if (futilityValue == VALUE_NONE)
1365 futilityValue = evaluate(pos, ei, threadID)
1366 + FutilityMargins[int(depth) - 2];
1368 if (futilityValue < beta)
1370 if (futilityValue > bestValue)
1371 bestValue = futilityValue;
1377 // Make and search the move
1379 pos.do_move(move, st, dcCandidates);
1381 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1382 // if the move fails high will be re-searched at full depth.
1383 if ( depth >= 2*OnePly
1384 && moveCount >= LMRNonPVMoves
1387 && !move_promotion(move)
1388 && !move_is_castle(move)
1389 && !move_is_killer(move, ss[ply]))
1391 ss[ply].reduction = OnePly;
1392 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1395 value = beta; // Just to trigger next condition
1397 if (value >= beta) // Go with full depth non-pv search
1399 ss[ply].reduction = Depth(0);
1400 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1402 pos.undo_move(move);
1404 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1407 if (value > bestValue)
1413 if (value == value_mate_in(ply + 1))
1414 ss[ply].mateKiller = move;
1418 if ( ActiveThreads > 1
1420 && depth >= MinimumSplitDepth
1422 && idle_thread_exists(threadID)
1424 && !thread_should_stop(threadID)
1425 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1426 &mp, dcCandidates, threadID, false))
1430 // All legal moves have been searched. A special case: If there were
1431 // no legal moves, it must be mate or stalemate.
1433 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1435 // If the search is not aborted, update the transposition table,
1436 // history counters, and killer moves.
1437 if (AbortSearch || thread_should_stop(threadID))
1440 if (bestValue < beta)
1441 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1444 BetaCounter.add(pos.side_to_move(), depth, threadID);
1445 Move m = ss[ply].pv[ply];
1446 if (ok_to_history(pos, m)) // Only non capture moves are considered
1448 update_history(pos, m, depth, movesSearched, moveCount);
1449 update_killers(m, ss[ply]);
1451 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1454 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1460 // qsearch() is the quiescence search function, which is called by the main
1461 // search function when the remaining depth is zero (or, to be more precise,
1462 // less than OnePly).
1464 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1465 Depth depth, int ply, int threadID) {
1467 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1468 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1470 assert(ply >= 0 && ply < PLY_MAX);
1471 assert(threadID >= 0 && threadID < ActiveThreads);
1473 // Initialize, and make an early exit in case of an aborted search,
1474 // an instant draw, maximum ply reached, etc.
1475 init_node(ss, ply, threadID);
1477 // After init_node() that calls poll()
1478 if (AbortSearch || thread_should_stop(threadID))
1484 // Transposition table lookup, only when not in PV
1485 TTEntry* tte = NULL;
1486 bool pvNode = (beta - alpha != 1);
1489 tte = TT.retrieve(pos.get_key());
1490 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1492 assert(tte->type() != VALUE_TYPE_EVAL);
1494 return value_from_tt(tte->value(), ply);
1497 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1499 // Evaluate the position statically
1502 bool isCheck = pos.is_check();
1503 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1506 staticValue = -VALUE_INFINITE;
1508 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1510 // Use the cached evaluation score if possible
1511 assert(tte->value() == evaluate(pos, ei, threadID));
1512 assert(ei.futilityMargin == Value(0));
1514 staticValue = tte->value();
1517 staticValue = evaluate(pos, ei, threadID);
1519 if (ply == PLY_MAX - 1)
1520 return evaluate(pos, ei, threadID);
1522 // Initialize "stand pat score", and return it immediately if it is
1524 Value bestValue = staticValue;
1526 if (bestValue >= beta)
1528 // Store the score to avoid a future costly evaluation() call
1529 if (!isCheck && !tte && ei.futilityMargin == 0)
1530 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1535 if (bestValue > alpha)
1538 // Initialize a MovePicker object for the current position, and prepare
1539 // to search the moves. Because the depth is <= 0 here, only captures,
1540 // queen promotions and checks (only if depth == 0) will be generated.
1541 MovePicker mp = MovePicker(pos, pvNode, ttMove, depth);
1544 Bitboard dcCandidates = mp.discovered_check_candidates();
1545 Color us = pos.side_to_move();
1546 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1548 // Loop through the moves until no moves remain or a beta cutoff
1550 while ( alpha < beta
1551 && (move = mp.get_next_move()) != MOVE_NONE)
1553 assert(move_is_ok(move));
1556 ss[ply].currentMove = move;
1559 if ( UseQSearchFutilityPruning
1563 && !move_promotion(move)
1564 && !pos.move_is_check(move, dcCandidates)
1565 && !pos.move_is_passed_pawn_push(move))
1567 Value futilityValue = staticValue
1568 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1569 pos.endgame_value_of_piece_on(move_to(move)))
1570 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1572 + ei.futilityMargin;
1574 if (futilityValue < alpha)
1576 if (futilityValue > bestValue)
1577 bestValue = futilityValue;
1582 // Don't search captures and checks with negative SEE values
1584 && !move_promotion(move)
1585 && (pos.midgame_value_of_piece_on(move_from(move)) >
1586 pos.midgame_value_of_piece_on(move_to(move)))
1587 && pos.see(move) < 0)
1590 // Make and search the move.
1592 pos.do_move(move, st, dcCandidates);
1593 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1594 pos.undo_move(move);
1596 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1599 if (value > bestValue)
1610 // All legal moves have been searched. A special case: If we're in check
1611 // and no legal moves were found, it is checkmate:
1612 if (pos.is_check() && moveCount == 0) // Mate!
1613 return value_mated_in(ply);
1615 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1617 // Update transposition table
1618 Move m = ss[ply].pv[ply];
1621 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1622 if (bestValue < beta)
1623 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1625 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1628 // Update killers only for good check moves
1629 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1630 update_killers(m, ss[ply]);
1636 // sp_search() is used to search from a split point. This function is called
1637 // by each thread working at the split point. It is similar to the normal
1638 // search() function, but simpler. Because we have already probed the hash
1639 // table, done a null move search, and searched the first move before
1640 // splitting, we don't have to repeat all this work in sp_search(). We
1641 // also don't need to store anything to the hash table here: This is taken
1642 // care of after we return from the split point.
1644 void sp_search(SplitPoint *sp, int threadID) {
1646 assert(threadID >= 0 && threadID < ActiveThreads);
1647 assert(ActiveThreads > 1);
1649 Position pos = Position(sp->pos);
1650 SearchStack *ss = sp->sstack[threadID];
1653 bool isCheck = pos.is_check();
1654 bool useFutilityPruning = UseFutilityPruning
1655 && sp->depth < SelectiveDepth
1658 while ( sp->bestValue < sp->beta
1659 && !thread_should_stop(threadID)
1660 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1662 assert(move_is_ok(move));
1664 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1665 bool moveIsCapture = pos.move_is_capture(move);
1667 lock_grab(&(sp->lock));
1668 int moveCount = ++sp->moves;
1669 lock_release(&(sp->lock));
1671 ss[sp->ply].currentMove = move;
1673 // Decide the new search depth.
1675 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1676 Depth newDepth = sp->depth - OnePly + ext;
1679 if ( useFutilityPruning
1682 && !move_promotion(move)
1683 && moveCount >= 2 + int(sp->depth)
1684 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1687 // Make and search the move.
1689 pos.do_move(move, st, sp->dcCandidates);
1691 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1692 // if the move fails high will be re-searched at full depth.
1694 && moveCount >= LMRNonPVMoves
1696 && !move_promotion(move)
1697 && !move_is_castle(move)
1698 && !move_is_killer(move, ss[sp->ply]))
1700 ss[sp->ply].reduction = OnePly;
1701 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1704 value = sp->beta; // Just to trigger next condition
1706 if (value >= sp->beta) // Go with full depth non-pv search
1708 ss[sp->ply].reduction = Depth(0);
1709 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1711 pos.undo_move(move);
1713 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1715 if (thread_should_stop(threadID))
1719 lock_grab(&(sp->lock));
1720 if (value > sp->bestValue && !thread_should_stop(threadID))
1722 sp->bestValue = value;
1723 if (sp->bestValue >= sp->beta)
1725 sp_update_pv(sp->parentSstack, ss, sp->ply);
1726 for (int i = 0; i < ActiveThreads; i++)
1727 if (i != threadID && (i == sp->master || sp->slaves[i]))
1728 Threads[i].stop = true;
1730 sp->finished = true;
1733 lock_release(&(sp->lock));
1736 lock_grab(&(sp->lock));
1738 // If this is the master thread and we have been asked to stop because of
1739 // a beta cutoff higher up in the tree, stop all slave threads:
1740 if (sp->master == threadID && thread_should_stop(threadID))
1741 for (int i = 0; i < ActiveThreads; i++)
1743 Threads[i].stop = true;
1746 sp->slaves[threadID] = 0;
1748 lock_release(&(sp->lock));
1752 // sp_search_pv() is used to search from a PV split point. This function
1753 // is called by each thread working at the split point. It is similar to
1754 // the normal search_pv() function, but simpler. Because we have already
1755 // probed the hash table and searched the first move before splitting, we
1756 // don't have to repeat all this work in sp_search_pv(). We also don't
1757 // need to store anything to the hash table here: This is taken care of
1758 // after we return from the split point.
1760 void sp_search_pv(SplitPoint *sp, int threadID) {
1762 assert(threadID >= 0 && threadID < ActiveThreads);
1763 assert(ActiveThreads > 1);
1765 Position pos = Position(sp->pos);
1766 SearchStack *ss = sp->sstack[threadID];
1770 while ( sp->alpha < sp->beta
1771 && !thread_should_stop(threadID)
1772 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1774 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1775 bool moveIsCapture = pos.move_is_capture(move);
1777 assert(move_is_ok(move));
1779 lock_grab(&(sp->lock));
1780 int moveCount = ++sp->moves;
1781 lock_release(&(sp->lock));
1783 ss[sp->ply].currentMove = move;
1785 // Decide the new search depth.
1787 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1788 Depth newDepth = sp->depth - OnePly + ext;
1790 // Make and search the move.
1792 pos.do_move(move, st, sp->dcCandidates);
1794 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1795 // if the move fails high will be re-searched at full depth.
1797 && moveCount >= LMRPVMoves
1799 && !move_promotion(move)
1800 && !move_is_castle(move)
1801 && !move_is_killer(move, ss[sp->ply]))
1803 ss[sp->ply].reduction = OnePly;
1804 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1807 value = sp->alpha + 1; // Just to trigger next condition
1809 if (value > sp->alpha) // Go with full depth non-pv search
1811 ss[sp->ply].reduction = Depth(0);
1812 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1814 if (value > sp->alpha && value < sp->beta)
1816 // When the search fails high at ply 1 while searching the first
1817 // move at the root, set the flag failHighPly1. This is used for
1818 // time managment: We don't want to stop the search early in
1819 // such cases, because resolving the fail high at ply 1 could
1820 // result in a big drop in score at the root.
1821 if (sp->ply == 1 && RootMoveNumber == 1)
1822 Threads[threadID].failHighPly1 = true;
1824 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1825 Threads[threadID].failHighPly1 = false;
1828 pos.undo_move(move);
1830 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1832 if (thread_should_stop(threadID))
1836 lock_grab(&(sp->lock));
1837 if (value > sp->bestValue && !thread_should_stop(threadID))
1839 sp->bestValue = value;
1840 if (value > sp->alpha)
1843 sp_update_pv(sp->parentSstack, ss, sp->ply);
1844 if (value == value_mate_in(sp->ply + 1))
1845 ss[sp->ply].mateKiller = move;
1847 if(value >= sp->beta)
1849 for(int i = 0; i < ActiveThreads; i++)
1850 if(i != threadID && (i == sp->master || sp->slaves[i]))
1851 Threads[i].stop = true;
1853 sp->finished = true;
1856 // If we are at ply 1, and we are searching the first root move at
1857 // ply 0, set the 'Problem' variable if the score has dropped a lot
1858 // (from the computer's point of view) since the previous iteration.
1861 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1864 lock_release(&(sp->lock));
1867 lock_grab(&(sp->lock));
1869 // If this is the master thread and we have been asked to stop because of
1870 // a beta cutoff higher up in the tree, stop all slave threads.
1871 if (sp->master == threadID && thread_should_stop(threadID))
1872 for (int i = 0; i < ActiveThreads; i++)
1874 Threads[i].stop = true;
1877 sp->slaves[threadID] = 0;
1879 lock_release(&(sp->lock));
1882 /// The BetaCounterType class
1884 BetaCounterType::BetaCounterType() { clear(); }
1886 void BetaCounterType::clear() {
1888 for (int i = 0; i < THREAD_MAX; i++)
1889 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1892 void BetaCounterType::add(Color us, Depth d, int threadID) {
1894 // Weighted count based on depth
1895 Threads[threadID].betaCutOffs[us] += unsigned(d);
1898 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1901 for (int i = 0; i < THREAD_MAX; i++)
1903 our += Threads[i].betaCutOffs[us];
1904 their += Threads[i].betaCutOffs[opposite_color(us)];
1909 /// The RootMove class
1913 RootMove::RootMove() {
1914 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1917 // RootMove::operator<() is the comparison function used when
1918 // sorting the moves. A move m1 is considered to be better
1919 // than a move m2 if it has a higher score, or if the moves
1920 // have equal score but m1 has the higher node count.
1922 bool RootMove::operator<(const RootMove& m) {
1924 if (score != m.score)
1925 return (score < m.score);
1927 return theirBeta <= m.theirBeta;
1930 /// The RootMoveList class
1934 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1936 MoveStack mlist[MaxRootMoves];
1937 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1939 // Generate all legal moves
1940 int lm_count = generate_legal_moves(pos, mlist);
1942 // Add each move to the moves[] array
1943 for (int i = 0; i < lm_count; i++)
1945 bool includeMove = includeAllMoves;
1947 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1948 includeMove = (searchMoves[k] == mlist[i].move);
1953 // Find a quick score for the move
1955 SearchStack ss[PLY_MAX_PLUS_2];
1957 moves[count].move = mlist[i].move;
1958 pos.do_move(moves[count].move, st);
1959 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1960 pos.undo_move(moves[count].move);
1961 moves[count].pv[0] = moves[count].move;
1962 moves[count].pv[1] = MOVE_NONE; // FIXME
1969 // Simple accessor methods for the RootMoveList class
1971 inline Move RootMoveList::get_move(int moveNum) const {
1972 return moves[moveNum].move;
1975 inline Value RootMoveList::get_move_score(int moveNum) const {
1976 return moves[moveNum].score;
1979 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1980 moves[moveNum].score = score;
1983 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1984 moves[moveNum].nodes = nodes;
1985 moves[moveNum].cumulativeNodes += nodes;
1988 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1989 moves[moveNum].ourBeta = our;
1990 moves[moveNum].theirBeta = their;
1993 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1995 for(j = 0; pv[j] != MOVE_NONE; j++)
1996 moves[moveNum].pv[j] = pv[j];
1997 moves[moveNum].pv[j] = MOVE_NONE;
2000 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
2001 return moves[moveNum].pv[i];
2004 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
2005 return moves[moveNum].cumulativeNodes;
2008 inline int RootMoveList::move_count() const {
2013 // RootMoveList::scan_for_easy_move() is called at the end of the first
2014 // iteration, and is used to detect an "easy move", i.e. a move which appears
2015 // to be much bester than all the rest. If an easy move is found, the move
2016 // is returned, otherwise the function returns MOVE_NONE. It is very
2017 // important that this function is called at the right moment: The code
2018 // assumes that the first iteration has been completed and the moves have
2019 // been sorted. This is done in RootMoveList c'tor.
2021 Move RootMoveList::scan_for_easy_move() const {
2028 // moves are sorted so just consider the best and the second one
2029 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2035 // RootMoveList::sort() sorts the root move list at the beginning of a new
2038 inline void RootMoveList::sort() {
2040 sort_multipv(count - 1); // all items
2044 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2045 // list by their scores and depths. It is used to order the different PVs
2046 // correctly in MultiPV mode.
2048 void RootMoveList::sort_multipv(int n) {
2050 for (int i = 1; i <= n; i++)
2052 RootMove rm = moves[i];
2054 for (j = i; j > 0 && moves[j-1] < rm; j--)
2055 moves[j] = moves[j-1];
2061 // init_node() is called at the beginning of all the search functions
2062 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2063 // stack object corresponding to the current node. Once every
2064 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2065 // for user input and checks whether it is time to stop the search.
2067 void init_node(SearchStack ss[], int ply, int threadID) {
2068 assert(ply >= 0 && ply < PLY_MAX);
2069 assert(threadID >= 0 && threadID < ActiveThreads);
2071 Threads[threadID].nodes++;
2075 if(NodesSincePoll >= NodesBetweenPolls) {
2082 ss[ply+2].initKillers();
2084 if(Threads[threadID].printCurrentLine)
2085 print_current_line(ss, ply, threadID);
2089 // update_pv() is called whenever a search returns a value > alpha. It
2090 // updates the PV in the SearchStack object corresponding to the current
2093 void update_pv(SearchStack ss[], int ply) {
2094 assert(ply >= 0 && ply < PLY_MAX);
2096 ss[ply].pv[ply] = ss[ply].currentMove;
2098 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2099 ss[ply].pv[p] = ss[ply+1].pv[p];
2100 ss[ply].pv[p] = MOVE_NONE;
2104 // sp_update_pv() is a variant of update_pv for use at split points. The
2105 // difference between the two functions is that sp_update_pv also updates
2106 // the PV at the parent node.
2108 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2109 assert(ply >= 0 && ply < PLY_MAX);
2111 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2113 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2114 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2115 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2119 // connected_moves() tests whether two moves are 'connected' in the sense
2120 // that the first move somehow made the second move possible (for instance
2121 // if the moving piece is the same in both moves). The first move is
2122 // assumed to be the move that was made to reach the current position, while
2123 // the second move is assumed to be a move from the current position.
2125 bool connected_moves(const Position &pos, Move m1, Move m2) {
2126 Square f1, t1, f2, t2;
2128 assert(move_is_ok(m1));
2129 assert(move_is_ok(m2));
2134 // Case 1: The moving piece is the same in both moves.
2140 // Case 2: The destination square for m2 was vacated by m1.
2146 // Case 3: Moving through the vacated square:
2147 if(piece_is_slider(pos.piece_on(f2)) &&
2148 bit_is_set(squares_between(f2, t2), f1))
2151 // Case 4: The destination square for m2 is attacked by the moving piece
2153 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2156 // Case 5: Discovered check, checking piece is the piece moved in m1:
2157 if(piece_is_slider(pos.piece_on(t1)) &&
2158 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2160 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2162 Bitboard occ = pos.occupied_squares();
2163 Color us = pos.side_to_move();
2164 Square ksq = pos.king_square(us);
2165 clear_bit(&occ, f2);
2166 if(pos.type_of_piece_on(t1) == BISHOP) {
2167 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2170 else if(pos.type_of_piece_on(t1) == ROOK) {
2171 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2175 assert(pos.type_of_piece_on(t1) == QUEEN);
2176 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2185 // value_is_mate() checks if the given value is a mate one
2186 // eventually compensated for the ply.
2188 bool value_is_mate(Value value) {
2190 assert(abs(value) <= VALUE_INFINITE);
2192 return value <= value_mated_in(PLY_MAX)
2193 || value >= value_mate_in(PLY_MAX);
2197 // move_is_killer() checks if the given move is among the
2198 // killer moves of that ply.
2200 bool move_is_killer(Move m, const SearchStack& ss) {
2202 const Move* k = ss.killers;
2203 for (int i = 0; i < KILLER_MAX; i++, k++)
2211 // extension() decides whether a move should be searched with normal depth,
2212 // or with extended depth. Certain classes of moves (checking moves, in
2213 // particular) are searched with bigger depth than ordinary moves and in
2214 // any case are marked as 'dangerous'. Note that also if a move is not
2215 // extended, as example because the corresponding UCI option is set to zero,
2216 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2218 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2219 bool singleReply, bool mateThreat, bool* dangerous) {
2221 assert(m != MOVE_NONE);
2223 Depth result = Depth(0);
2224 *dangerous = check || singleReply || mateThreat;
2227 result += CheckExtension[pvNode];
2230 result += SingleReplyExtension[pvNode];
2233 result += MateThreatExtension[pvNode];
2235 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2237 if (pos.move_is_pawn_push_to_7th(m))
2239 result += PawnPushTo7thExtension[pvNode];
2242 if (pos.move_is_passed_pawn_push(m))
2244 result += PassedPawnExtension[pvNode];
2250 && pos.type_of_piece_on(move_to(m)) != PAWN
2251 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2252 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2253 && !move_promotion(m)
2256 result += PawnEndgameExtension[pvNode];
2262 && pos.type_of_piece_on(move_to(m)) != PAWN
2269 return Min(result, OnePly);
2273 // ok_to_do_nullmove() looks at the current position and decides whether
2274 // doing a 'null move' should be allowed. In order to avoid zugzwang
2275 // problems, null moves are not allowed when the side to move has very
2276 // little material left. Currently, the test is a bit too simple: Null
2277 // moves are avoided only when the side to move has only pawns left. It's
2278 // probably a good idea to avoid null moves in at least some more
2279 // complicated endgames, e.g. KQ vs KR. FIXME
2281 bool ok_to_do_nullmove(const Position &pos) {
2282 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2288 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2289 // non-tactical moves late in the move list close to the leaves are
2290 // candidates for pruning.
2292 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2293 Square mfrom, mto, tfrom, tto;
2295 assert(move_is_ok(m));
2296 assert(threat == MOVE_NONE || move_is_ok(threat));
2297 assert(!move_promotion(m));
2298 assert(!pos.move_is_check(m));
2299 assert(!pos.move_is_capture(m));
2300 assert(!pos.move_is_passed_pawn_push(m));
2301 assert(d >= OnePly);
2303 mfrom = move_from(m);
2305 tfrom = move_from(threat);
2306 tto = move_to(threat);
2308 // Case 1: Castling moves are never pruned.
2309 if (move_is_castle(m))
2312 // Case 2: Don't prune moves which move the threatened piece
2313 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2316 // Case 3: If the threatened piece has value less than or equal to the
2317 // value of the threatening piece, don't prune move which defend it.
2318 if ( !PruneDefendingMoves
2319 && threat != MOVE_NONE
2320 && pos.move_is_capture(threat)
2321 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2322 || pos.type_of_piece_on(tfrom) == KING)
2323 && pos.move_attacks_square(m, tto))
2326 // Case 4: Don't prune moves with good history.
2327 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2330 // Case 5: If the moving piece in the threatened move is a slider, don't
2331 // prune safe moves which block its ray.
2332 if ( !PruneBlockingMoves
2333 && threat != MOVE_NONE
2334 && piece_is_slider(pos.piece_on(tfrom))
2335 && bit_is_set(squares_between(tfrom, tto), mto)
2343 // ok_to_use_TT() returns true if a transposition table score
2344 // can be used at a given point in search.
2346 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2348 Value v = value_from_tt(tte->value(), ply);
2350 return ( tte->depth() >= depth
2351 || v >= Max(value_mate_in(100), beta)
2352 || v < Min(value_mated_in(100), beta))
2354 && ( (is_lower_bound(tte->type()) && v >= beta)
2355 || (is_upper_bound(tte->type()) && v < beta));
2359 // ok_to_history() returns true if a move m can be stored
2360 // in history. Should be a non capturing move nor a promotion.
2362 bool ok_to_history(const Position& pos, Move m) {
2364 return !pos.move_is_capture(m) && !move_promotion(m);
2368 // update_history() registers a good move that produced a beta-cutoff
2369 // in history and marks as failures all the other moves of that ply.
2371 void update_history(const Position& pos, Move m, Depth depth,
2372 Move movesSearched[], int moveCount) {
2374 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2376 for (int i = 0; i < moveCount - 1; i++)
2378 assert(m != movesSearched[i]);
2379 if (ok_to_history(pos, movesSearched[i]))
2380 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2385 // update_killers() add a good move that produced a beta-cutoff
2386 // among the killer moves of that ply.
2388 void update_killers(Move m, SearchStack& ss) {
2390 if (m == ss.killers[0])
2393 for (int i = KILLER_MAX - 1; i > 0; i--)
2394 ss.killers[i] = ss.killers[i - 1];
2399 // fail_high_ply_1() checks if some thread is currently resolving a fail
2400 // high at ply 1 at the node below the first root node. This information
2401 // is used for time managment.
2403 bool fail_high_ply_1() {
2404 for(int i = 0; i < ActiveThreads; i++)
2405 if(Threads[i].failHighPly1)
2411 // current_search_time() returns the number of milliseconds which have passed
2412 // since the beginning of the current search.
2414 int current_search_time() {
2415 return get_system_time() - SearchStartTime;
2419 // nps() computes the current nodes/second count.
2422 int t = current_search_time();
2423 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2427 // poll() performs two different functions: It polls for user input, and it
2428 // looks at the time consumed so far and decides if it's time to abort the
2433 static int lastInfoTime;
2434 int t = current_search_time();
2439 // We are line oriented, don't read single chars
2440 std::string command;
2441 if (!std::getline(std::cin, command))
2444 if (command == "quit")
2447 PonderSearch = false;
2451 else if(command == "stop")
2454 PonderSearch = false;
2456 else if(command == "ponderhit")
2459 // Print search information
2463 else if (lastInfoTime > t)
2464 // HACK: Must be a new search where we searched less than
2465 // NodesBetweenPolls nodes during the first second of search.
2468 else if (t - lastInfoTime >= 1000)
2475 if (dbg_show_hit_rate)
2476 dbg_print_hit_rate();
2478 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2479 << " time " << t << " hashfull " << TT.full() << std::endl;
2480 lock_release(&IOLock);
2481 if (ShowCurrentLine)
2482 Threads[0].printCurrentLine = true;
2484 // Should we stop the search?
2488 bool overTime = t > AbsoluteMaxSearchTime
2489 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2490 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2491 && t > 6*(MaxSearchTime + ExtraSearchTime));
2493 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2494 || (ExactMaxTime && t >= ExactMaxTime)
2495 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2500 // ponderhit() is called when the program is pondering (i.e. thinking while
2501 // it's the opponent's turn to move) in order to let the engine know that
2502 // it correctly predicted the opponent's move.
2505 int t = current_search_time();
2506 PonderSearch = false;
2507 if(Iteration >= 3 &&
2508 (!InfiniteSearch && (StopOnPonderhit ||
2509 t > AbsoluteMaxSearchTime ||
2510 (RootMoveNumber == 1 &&
2511 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2512 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2513 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2518 // print_current_line() prints the current line of search for a given
2519 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2521 void print_current_line(SearchStack ss[], int ply, int threadID) {
2522 assert(ply >= 0 && ply < PLY_MAX);
2523 assert(threadID >= 0 && threadID < ActiveThreads);
2525 if(!Threads[threadID].idle) {
2527 std::cout << "info currline " << (threadID + 1);
2528 for(int p = 0; p < ply; p++)
2529 std::cout << " " << ss[p].currentMove;
2530 std::cout << std::endl;
2531 lock_release(&IOLock);
2533 Threads[threadID].printCurrentLine = false;
2534 if(threadID + 1 < ActiveThreads)
2535 Threads[threadID + 1].printCurrentLine = true;
2539 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2540 // while the program is pondering. The point is to work around a wrinkle in
2541 // the UCI protocol: When pondering, the engine is not allowed to give a
2542 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2543 // We simply wait here until one of these commands is sent, and return,
2544 // after which the bestmove and pondermove will be printed (in id_loop()).
2546 void wait_for_stop_or_ponderhit() {
2548 std::string command;
2552 if (!std::getline(std::cin, command))
2555 if (command == "quit")
2560 else if(command == "ponderhit" || command == "stop")
2566 // idle_loop() is where the threads are parked when they have no work to do.
2567 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2568 // object for which the current thread is the master.
2570 void idle_loop(int threadID, SplitPoint *waitSp) {
2571 assert(threadID >= 0 && threadID < THREAD_MAX);
2573 Threads[threadID].running = true;
2576 if(AllThreadsShouldExit && threadID != 0)
2579 // If we are not thinking, wait for a condition to be signaled instead
2580 // of wasting CPU time polling for work:
2581 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2582 #if !defined(_MSC_VER)
2583 pthread_mutex_lock(&WaitLock);
2584 if(Idle || threadID >= ActiveThreads)
2585 pthread_cond_wait(&WaitCond, &WaitLock);
2586 pthread_mutex_unlock(&WaitLock);
2588 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2592 // If this thread has been assigned work, launch a search:
2593 if(Threads[threadID].workIsWaiting) {
2594 Threads[threadID].workIsWaiting = false;
2595 if(Threads[threadID].splitPoint->pvNode)
2596 sp_search_pv(Threads[threadID].splitPoint, threadID);
2598 sp_search(Threads[threadID].splitPoint, threadID);
2599 Threads[threadID].idle = true;
2602 // If this thread is the master of a split point and all threads have
2603 // finished their work at this split point, return from the idle loop:
2604 if(waitSp != NULL && waitSp->cpus == 0)
2608 Threads[threadID].running = false;
2612 // init_split_point_stack() is called during program initialization, and
2613 // initializes all split point objects.
2615 void init_split_point_stack() {
2616 for(int i = 0; i < THREAD_MAX; i++)
2617 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2618 SplitPointStack[i][j].parent = NULL;
2619 lock_init(&(SplitPointStack[i][j].lock), NULL);
2624 // destroy_split_point_stack() is called when the program exits, and
2625 // destroys all locks in the precomputed split point objects.
2627 void destroy_split_point_stack() {
2628 for(int i = 0; i < THREAD_MAX; i++)
2629 for(int j = 0; j < MaxActiveSplitPoints; j++)
2630 lock_destroy(&(SplitPointStack[i][j].lock));
2634 // thread_should_stop() checks whether the thread with a given threadID has
2635 // been asked to stop, directly or indirectly. This can happen if a beta
2636 // cutoff has occured in thre thread's currently active split point, or in
2637 // some ancestor of the current split point.
2639 bool thread_should_stop(int threadID) {
2640 assert(threadID >= 0 && threadID < ActiveThreads);
2644 if(Threads[threadID].stop)
2646 if(ActiveThreads <= 2)
2648 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2650 Threads[threadID].stop = true;
2657 // thread_is_available() checks whether the thread with threadID "slave" is
2658 // available to help the thread with threadID "master" at a split point. An
2659 // obvious requirement is that "slave" must be idle. With more than two
2660 // threads, this is not by itself sufficient: If "slave" is the master of
2661 // some active split point, it is only available as a slave to the other
2662 // threads which are busy searching the split point at the top of "slave"'s
2663 // split point stack (the "helpful master concept" in YBWC terminology).
2665 bool thread_is_available(int slave, int master) {
2666 assert(slave >= 0 && slave < ActiveThreads);
2667 assert(master >= 0 && master < ActiveThreads);
2668 assert(ActiveThreads > 1);
2670 if(!Threads[slave].idle || slave == master)
2673 if(Threads[slave].activeSplitPoints == 0)
2674 // No active split points means that the thread is available as a slave
2675 // for any other thread.
2678 if(ActiveThreads == 2)
2681 // Apply the "helpful master" concept if possible.
2682 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2689 // idle_thread_exists() tries to find an idle thread which is available as
2690 // a slave for the thread with threadID "master".
2692 bool idle_thread_exists(int master) {
2693 assert(master >= 0 && master < ActiveThreads);
2694 assert(ActiveThreads > 1);
2696 for(int i = 0; i < ActiveThreads; i++)
2697 if(thread_is_available(i, master))
2703 // split() does the actual work of distributing the work at a node between
2704 // several threads at PV nodes. If it does not succeed in splitting the
2705 // node (because no idle threads are available, or because we have no unused
2706 // split point objects), the function immediately returns false. If
2707 // splitting is possible, a SplitPoint object is initialized with all the
2708 // data that must be copied to the helper threads (the current position and
2709 // search stack, alpha, beta, the search depth, etc.), and we tell our
2710 // helper threads that they have been assigned work. This will cause them
2711 // to instantly leave their idle loops and call sp_search_pv(). When all
2712 // threads have returned from sp_search_pv (or, equivalently, when
2713 // splitPoint->cpus becomes 0), split() returns true.
2715 bool split(const Position &p, SearchStack *sstck, int ply,
2716 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2717 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2720 assert(sstck != NULL);
2721 assert(ply >= 0 && ply < PLY_MAX);
2722 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2723 assert(!pvNode || *alpha < *beta);
2724 assert(*beta <= VALUE_INFINITE);
2725 assert(depth > Depth(0));
2726 assert(master >= 0 && master < ActiveThreads);
2727 assert(ActiveThreads > 1);
2729 SplitPoint *splitPoint;
2734 // If no other thread is available to help us, or if we have too many
2735 // active split points, don't split:
2736 if(!idle_thread_exists(master) ||
2737 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2738 lock_release(&MPLock);
2742 // Pick the next available split point object from the split point stack:
2743 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2744 Threads[master].activeSplitPoints++;
2746 // Initialize the split point object:
2747 splitPoint->parent = Threads[master].splitPoint;
2748 splitPoint->finished = false;
2749 splitPoint->ply = ply;
2750 splitPoint->depth = depth;
2751 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2752 splitPoint->beta = *beta;
2753 splitPoint->pvNode = pvNode;
2754 splitPoint->dcCandidates = dcCandidates;
2755 splitPoint->bestValue = *bestValue;
2756 splitPoint->master = master;
2757 splitPoint->mp = mp;
2758 splitPoint->moves = *moves;
2759 splitPoint->cpus = 1;
2760 splitPoint->pos.copy(p);
2761 splitPoint->parentSstack = sstck;
2762 for(i = 0; i < ActiveThreads; i++)
2763 splitPoint->slaves[i] = 0;
2765 // Copy the current position and the search stack to the master thread:
2766 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2767 Threads[master].splitPoint = splitPoint;
2769 // Make copies of the current position and search stack for each thread:
2770 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2772 if(thread_is_available(i, master)) {
2773 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2774 Threads[i].splitPoint = splitPoint;
2775 splitPoint->slaves[i] = 1;
2779 // Tell the threads that they have work to do. This will make them leave
2781 for(i = 0; i < ActiveThreads; i++)
2782 if(i == master || splitPoint->slaves[i]) {
2783 Threads[i].workIsWaiting = true;
2784 Threads[i].idle = false;
2785 Threads[i].stop = false;
2788 lock_release(&MPLock);
2790 // Everything is set up. The master thread enters the idle loop, from
2791 // which it will instantly launch a search, because its workIsWaiting
2792 // slot is 'true'. We send the split point as a second parameter to the
2793 // idle loop, which means that the main thread will return from the idle
2794 // loop when all threads have finished their work at this split point
2795 // (i.e. when // splitPoint->cpus == 0).
2796 idle_loop(master, splitPoint);
2798 // We have returned from the idle loop, which means that all threads are
2799 // finished. Update alpha, beta and bestvalue, and return:
2801 if(pvNode) *alpha = splitPoint->alpha;
2802 *beta = splitPoint->beta;
2803 *bestValue = splitPoint->bestValue;
2804 Threads[master].stop = false;
2805 Threads[master].idle = false;
2806 Threads[master].activeSplitPoints--;
2807 Threads[master].splitPoint = splitPoint->parent;
2808 lock_release(&MPLock);
2814 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2815 // to start a new search from the root.
2817 void wake_sleeping_threads() {
2818 if(ActiveThreads > 1) {
2819 for(int i = 1; i < ActiveThreads; i++) {
2820 Threads[i].idle = true;
2821 Threads[i].workIsWaiting = false;
2823 #if !defined(_MSC_VER)
2824 pthread_mutex_lock(&WaitLock);
2825 pthread_cond_broadcast(&WaitCond);
2826 pthread_mutex_unlock(&WaitLock);
2828 for(int i = 1; i < THREAD_MAX; i++)
2829 SetEvent(SitIdleEvent[i]);
2835 // init_thread() is the function which is called when a new thread is
2836 // launched. It simply calls the idle_loop() function with the supplied
2837 // threadID. There are two versions of this function; one for POSIX threads
2838 // and one for Windows threads.
2840 #if !defined(_MSC_VER)
2842 void *init_thread(void *threadID) {
2843 idle_loop(*(int *)threadID, NULL);
2849 DWORD WINAPI init_thread(LPVOID threadID) {
2850 idle_loop(*(int *)threadID, NULL);