2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4 Copyright (C) 2008-2009 Marco Costalba
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
42 #include "ucioption.h"
46 //// Local definitions
53 // IterationInfoType stores search results for each iteration
55 // Because we use relatively small (dynamic) aspiration window,
56 // there happens many fail highs and fail lows in root. And
57 // because we don't do researches in those cases, "value" stored
58 // here is not necessarily exact. Instead in case of fail high/low
59 // we guess what the right value might be and store our guess
60 // as a "speculated value" and then move on. Speculated values are
61 // used just to calculate aspiration window width, so also if are
62 // not exact is not big a problem.
64 struct IterationInfoType {
66 IterationInfoType(Value v = Value(0), Value sv = Value(0))
67 : value(v), speculatedValue(sv) {}
69 Value value, speculatedValue;
73 // The BetaCounterType class is used to order moves at ply one.
74 // Apart for the first one that has its score, following moves
75 // normally have score -VALUE_INFINITE, so are ordered according
76 // to the number of beta cutoffs occurred under their subtree during
77 // the last iteration. The counters are per thread variables to avoid
78 // concurrent accessing under SMP case.
80 struct BetaCounterType {
84 void add(Color us, Depth d, int threadID);
85 void read(Color us, int64_t& our, int64_t& their);
89 // The RootMove class is used for moves at the root at the tree. For each
90 // root move, we store a score, a node count, and a PV (really a refutation
91 // in the case of moves which fail low).
96 bool operator<(const RootMove&); // used to sort
100 int64_t nodes, cumulativeNodes;
101 Move pv[PLY_MAX_PLUS_2];
102 int64_t ourBeta, theirBeta;
106 // The RootMoveList class is essentially an array of RootMove objects, with
107 // a handful of methods for accessing the data in the individual moves.
112 RootMoveList(Position &pos, Move searchMoves[]);
113 inline Move get_move(int moveNum) const;
114 inline Value get_move_score(int moveNum) const;
115 inline void set_move_score(int moveNum, Value score);
116 inline void set_move_nodes(int moveNum, int64_t nodes);
117 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
118 void set_move_pv(int moveNum, const Move pv[]);
119 inline Move get_move_pv(int moveNum, int i) const;
120 inline int64_t get_move_cumulative_nodes(int moveNum) const;
121 inline int move_count() const;
122 Move scan_for_easy_move() const;
124 void sort_multipv(int n);
127 static const int MaxRootMoves = 500;
128 RootMove moves[MaxRootMoves];
135 // Search depth at iteration 1
136 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
138 // Depth limit for selective search
139 const Depth SelectiveDepth = 7 * OnePly;
141 // Use internal iterative deepening?
142 const bool UseIIDAtPVNodes = true;
143 const bool UseIIDAtNonPVNodes = false;
145 // Internal iterative deepening margin. At Non-PV moves, when
146 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
147 // when the static evaluation is at most IIDMargin below beta.
148 const Value IIDMargin = Value(0x100);
150 // Easy move margin. An easy move candidate must be at least this much
151 // better than the second best move.
152 const Value EasyMoveMargin = Value(0x200);
154 // Problem margin. If the score of the first move at iteration N+1 has
155 // dropped by more than this since iteration N, the boolean variable
156 // "Problem" is set to true, which will make the program spend some extra
157 // time looking for a better move.
158 const Value ProblemMargin = Value(0x28);
160 // No problem margin. If the boolean "Problem" is true, and a new move
161 // is found at the root which is less than NoProblemMargin worse than the
162 // best move from the previous iteration, Problem is set back to false.
163 const Value NoProblemMargin = Value(0x14);
165 // Null move margin. A null move search will not be done if the approximate
166 // evaluation of the position is more than NullMoveMargin below beta.
167 const Value NullMoveMargin = Value(0x300);
169 // Pruning criterions. See the code and comments in ok_to_prune() to
170 // understand their precise meaning.
171 const bool PruneEscapeMoves = false;
172 const bool PruneDefendingMoves = false;
173 const bool PruneBlockingMoves = false;
175 // Margins for futility pruning in the quiescence search, and at frontier
176 // and near frontier nodes
177 const Value FutilityMarginQS = Value(0x80);
179 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
180 const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270),
181 // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply
182 Value(0x2A0), Value(0x2C0), Value(0x340), Value(0x360), Value(0x3A0), Value(0x3C0) };
184 const Depth RazorDepth = 4*OnePly;
186 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
187 const Value RazorMargins[6] = { Value(0x180), Value(0x300), Value(0x300), Value(0x3C0), Value(0x3C0), Value(0x3C0) };
189 // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply
190 const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) };
193 /// Variables initialized from UCI options
195 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV nodes
196 int LMRPVMoves, LMRNonPVMoves; // heavy SMP read access for the latter
198 // Depth limit for use of dynamic threat detection
199 Depth ThreatDepth; // heavy SMP read access
201 // Last seconds noise filtering (LSN)
202 bool UseLSNFiltering;
203 bool looseOnTime = false;
204 int LSNTime; // In milliseconds
207 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
208 // There is heavy SMP read access on these arrays
209 Depth CheckExtension[2], SingleReplyExtension[2], PawnPushTo7thExtension[2];
210 Depth PassedPawnExtension[2], PawnEndgameExtension[2], MateThreatExtension[2];
212 // Iteration counters
214 BetaCounterType BetaCounter; // has per-thread internal data
216 // Scores and number of times the best move changed for each iteration
217 IterationInfoType IterationInfo[PLY_MAX_PLUS_2];
218 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
223 // Time managment variables
225 int MaxNodes, MaxDepth;
226 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
231 bool StopOnPonderhit;
232 bool AbortSearch; // heavy SMP read access
237 bool PonderingEnabled;
240 // Show current line?
241 bool ShowCurrentLine;
245 std::ofstream LogFile;
247 // MP related variables
248 int ActiveThreads = 1;
249 Depth MinimumSplitDepth;
250 int MaxThreadsPerSplitPoint;
251 Thread Threads[THREAD_MAX];
254 bool AllThreadsShouldExit = false;
255 const int MaxActiveSplitPoints = 8;
256 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
259 #if !defined(_MSC_VER)
260 pthread_cond_t WaitCond;
261 pthread_mutex_t WaitLock;
263 HANDLE SitIdleEvent[THREAD_MAX];
266 // Node counters, used only by thread[0] but try to keep in different
267 // cache lines (64 bytes each) from the heavy SMP read accessed variables.
269 int NodesBetweenPolls = 30000;
271 // The main transposition table
272 TranspositionTable TT;
277 Value id_loop(const Position &pos, Move searchMoves[]);
278 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta);
279 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
280 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID);
281 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID);
282 void sp_search(SplitPoint *sp, int threadID);
283 void sp_search_pv(SplitPoint *sp, int threadID);
284 void init_node(SearchStack ss[], int ply, int threadID);
285 void update_pv(SearchStack ss[], int ply);
286 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
287 bool connected_moves(const Position &pos, Move m1, Move m2);
288 bool value_is_mate(Value value);
289 bool move_is_killer(Move m, const SearchStack& ss);
290 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
291 bool ok_to_do_nullmove(const Position &pos);
292 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d, const History& H);
293 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
294 bool ok_to_history(const Position &pos, Move m);
295 void update_history(const Position& pos, Move m, Depth depth, History& H, Move movesSearched[], int moveCount);
296 void update_killers(Move m, SearchStack& ss);
298 bool fail_high_ply_1();
299 int current_search_time();
303 void print_current_line(SearchStack ss[], int ply, int threadID);
304 void wait_for_stop_or_ponderhit();
306 void idle_loop(int threadID, SplitPoint *waitSp);
307 void init_split_point_stack();
308 void destroy_split_point_stack();
309 bool thread_should_stop(int threadID);
310 bool thread_is_available(int slave, int master);
311 bool idle_thread_exists(int master);
312 bool split(const Position &pos, SearchStack *ss, int ply,
313 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
314 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
315 void wake_sleeping_threads();
317 #if !defined(_MSC_VER)
318 void *init_thread(void *threadID);
320 DWORD WINAPI init_thread(LPVOID threadID);
330 /// think() is the external interface to Stockfish's search, and is called when
331 /// the program receives the UCI 'go' command. It initializes various
332 /// search-related global variables, and calls root_search(). It returns false
333 /// when a quit command is received during the search.
335 bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
336 int time[], int increment[], int movesToGo, int maxDepth,
337 int maxNodes, int maxTime, Move searchMoves[]) {
339 // Look for a book move
340 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
343 if (get_option_value_string("Book File") != OpeningBook.file_name())
344 OpeningBook.open("book.bin");
346 bookMove = OpeningBook.get_move(pos);
347 if (bookMove != MOVE_NONE)
349 std::cout << "bestmove " << bookMove << std::endl;
354 // Initialize global search variables
356 SearchStartTime = get_system_time();
357 EasyMove = MOVE_NONE;
358 for (int i = 0; i < THREAD_MAX; i++)
360 Threads[i].nodes = 0ULL;
361 Threads[i].failHighPly1 = false;
364 InfiniteSearch = infinite;
365 PonderSearch = ponder;
366 StopOnPonderhit = false;
372 ExactMaxTime = maxTime;
374 // Read UCI option values
375 TT.set_size(get_option_value_int("Hash"));
376 if (button_was_pressed("Clear Hash"))
379 PonderingEnabled = get_option_value_bool("Ponder");
380 MultiPV = get_option_value_int("MultiPV");
382 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
383 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
385 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
386 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
388 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
389 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
391 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
392 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
394 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
395 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
397 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
398 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
400 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
401 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
402 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
404 Chess960 = get_option_value_bool("UCI_Chess960");
405 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
406 UseLogFile = get_option_value_bool("Use Search Log");
408 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
410 UseLSNFiltering = get_option_value_bool("LSN filtering");
411 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
412 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
414 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
415 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
417 read_weights(pos.side_to_move());
419 int newActiveThreads = get_option_value_int("Threads");
420 if (newActiveThreads != ActiveThreads)
422 ActiveThreads = newActiveThreads;
423 init_eval(ActiveThreads);
426 // Wake up sleeping threads
427 wake_sleeping_threads();
429 for (int i = 1; i < ActiveThreads; i++)
430 assert(thread_is_available(i, 0));
432 // Set thinking time:
433 int myTime = time[side_to_move];
434 int myIncrement = increment[side_to_move];
436 if (!movesToGo) // Sudden death time control
440 MaxSearchTime = myTime / 30 + myIncrement;
441 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
442 } else { // Blitz game without increment
443 MaxSearchTime = myTime / 30;
444 AbsoluteMaxSearchTime = myTime / 8;
447 else // (x moves) / (y minutes)
451 MaxSearchTime = myTime / 2;
452 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
454 MaxSearchTime = myTime / Min(movesToGo, 20);
455 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
459 if (PonderingEnabled)
461 MaxSearchTime += MaxSearchTime / 4;
462 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
465 // Fixed depth or fixed number of nodes?
468 InfiniteSearch = true; // HACK
473 NodesBetweenPolls = Min(MaxNodes, 30000);
474 InfiniteSearch = true; // HACK
477 NodesBetweenPolls = 30000;
480 // Write information to search log file:
482 LogFile << "Searching: " << pos.to_fen() << std::endl
483 << "infinite: " << infinite
484 << " ponder: " << ponder
485 << " time: " << myTime
486 << " increment: " << myIncrement
487 << " moves to go: " << movesToGo << std::endl;
490 // We're ready to start thinking. Call the iterative deepening loop
494 Value v = id_loop(pos, searchMoves);
495 looseOnTime = ( UseLSNFiltering
502 looseOnTime = false; // reset for next match
503 while (SearchStartTime + myTime + 1000 > get_system_time())
505 id_loop(pos, searchMoves); // to fail gracefully
516 /// init_threads() is called during startup. It launches all helper threads,
517 /// and initializes the split point stack and the global locks and condition
520 void init_threads() {
524 #if !defined(_MSC_VER)
525 pthread_t pthread[1];
528 for (i = 0; i < THREAD_MAX; i++)
529 Threads[i].activeSplitPoints = 0;
531 // Initialize global locks:
532 lock_init(&MPLock, NULL);
533 lock_init(&IOLock, NULL);
535 init_split_point_stack();
537 #if !defined(_MSC_VER)
538 pthread_mutex_init(&WaitLock, NULL);
539 pthread_cond_init(&WaitCond, NULL);
541 for (i = 0; i < THREAD_MAX; i++)
542 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
545 // All threads except the main thread should be initialized to idle state
546 for (i = 1; i < THREAD_MAX; i++)
548 Threads[i].stop = false;
549 Threads[i].workIsWaiting = false;
550 Threads[i].idle = true;
551 Threads[i].running = false;
554 // Launch the helper threads
555 for(i = 1; i < THREAD_MAX; i++)
557 #if !defined(_MSC_VER)
558 pthread_create(pthread, NULL, init_thread, (void*)(&i));
561 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
564 // Wait until the thread has finished launching:
565 while (!Threads[i].running);
570 /// stop_threads() is called when the program exits. It makes all the
571 /// helper threads exit cleanly.
573 void stop_threads() {
575 ActiveThreads = THREAD_MAX; // HACK
576 Idle = false; // HACK
577 wake_sleeping_threads();
578 AllThreadsShouldExit = true;
579 for (int i = 1; i < THREAD_MAX; i++)
581 Threads[i].stop = true;
582 while(Threads[i].running);
584 destroy_split_point_stack();
588 /// nodes_searched() returns the total number of nodes searched so far in
589 /// the current search.
591 int64_t nodes_searched() {
593 int64_t result = 0ULL;
594 for (int i = 0; i < ActiveThreads; i++)
595 result += Threads[i].nodes;
600 // SearchStack::init() initializes a search stack. Used at the beginning of a
601 // new search from the root.
602 void SearchStack::init(int ply) {
604 pv[ply] = pv[ply + 1] = MOVE_NONE;
605 currentMove = threatMove = MOVE_NONE;
606 reduction = Depth(0);
609 void SearchStack::initKillers() {
611 mateKiller = MOVE_NONE;
612 for (int i = 0; i < KILLER_MAX; i++)
613 killers[i] = MOVE_NONE;
618 // id_loop() is the main iterative deepening loop. It calls root_search
619 // repeatedly with increasing depth until the allocated thinking time has
620 // been consumed, the user stops the search, or the maximum search depth is
623 Value id_loop(const Position &pos, Move searchMoves[]) {
626 SearchStack ss[PLY_MAX_PLUS_2];
628 // searchMoves are verified, copied, scored and sorted
629 RootMoveList rml(p, searchMoves);
633 for (int i = 0; i < THREAD_MAX; i++)
634 Threads[i].H.clear();
636 for (int i = 0; i < 3; i++)
641 IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0));
644 EasyMove = rml.scan_for_easy_move();
646 // Iterative deepening loop
647 while (Iteration < PLY_MAX)
649 // Initialize iteration
652 BestMoveChangesByIteration[Iteration] = 0;
656 std::cout << "info depth " << Iteration << std::endl;
658 // Calculate dynamic search window based on previous iterations
661 if (MultiPV == 1 && Iteration >= 6)
663 int prevDelta1 = IterationInfo[Iteration - 1].speculatedValue - IterationInfo[Iteration - 2].speculatedValue;
664 int prevDelta2 = IterationInfo[Iteration - 2].speculatedValue - IterationInfo[Iteration - 3].speculatedValue;
666 int delta = Max(2 * abs(prevDelta1) + abs(prevDelta2), ProblemMargin);
668 alpha = Max(IterationInfo[Iteration - 1].value - delta, -VALUE_INFINITE);
669 beta = Min(IterationInfo[Iteration - 1].value + delta, VALUE_INFINITE);
673 alpha = - VALUE_INFINITE;
674 beta = VALUE_INFINITE;
677 // Search to the current depth
678 Value value = root_search(p, ss, rml, alpha, beta);
680 // Write PV to transposition table, in case the relevant entries have
681 // been overwritten during the search.
682 TT.insert_pv(p, ss[0].pv);
685 break; // Value cannot be trusted. Break out immediately!
687 //Save info about search result
688 Value speculatedValue;
691 Value delta = value - IterationInfo[Iteration - 1].value;
698 speculatedValue = value + delta;
699 BestMoveChangesByIteration[Iteration] += 2; // Allocate more time
701 else if (value <= alpha)
703 assert(value == alpha);
707 speculatedValue = value + delta;
708 BestMoveChangesByIteration[Iteration] += 3; // Allocate more time
710 speculatedValue = value;
712 speculatedValue = Min(Max(speculatedValue, -VALUE_INFINITE), VALUE_INFINITE);
713 IterationInfo[Iteration] = IterationInfoType(value, speculatedValue);
715 // Erase the easy move if it differs from the new best move
716 if (ss[0].pv[0] != EasyMove)
717 EasyMove = MOVE_NONE;
724 bool stopSearch = false;
726 // Stop search early if there is only a single legal move:
727 if (Iteration >= 6 && rml.move_count() == 1)
730 // Stop search early when the last two iterations returned a mate score
732 && abs(IterationInfo[Iteration].value) >= abs(VALUE_MATE) - 100
733 && abs(IterationInfo[Iteration-1].value) >= abs(VALUE_MATE) - 100)
736 // Stop search early if one move seems to be much better than the rest
737 int64_t nodes = nodes_searched();
741 && EasyMove == ss[0].pv[0]
742 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
743 && current_search_time() > MaxSearchTime / 16)
744 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
745 && current_search_time() > MaxSearchTime / 32)))
748 // Add some extra time if the best move has changed during the last two iterations
749 if (Iteration > 5 && Iteration <= 50)
750 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
751 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
753 // Stop search if most of MaxSearchTime is consumed at the end of the
754 // iteration. We probably don't have enough time to search the first
755 // move at the next iteration anyway.
756 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
761 //FIXME: Implement fail-low emergency measures
765 StopOnPonderhit = true;
769 if (MaxDepth && Iteration >= MaxDepth)
775 // If we are pondering, we shouldn't print the best move before we
778 wait_for_stop_or_ponderhit();
780 // Print final search statistics
781 std::cout << "info nodes " << nodes_searched()
783 << " time " << current_search_time()
784 << " hashfull " << TT.full() << std::endl;
786 // Print the best move and the ponder move to the standard output
787 if (ss[0].pv[0] == MOVE_NONE)
789 ss[0].pv[0] = rml.get_move(0);
790 ss[0].pv[1] = MOVE_NONE;
792 std::cout << "bestmove " << ss[0].pv[0];
793 if (ss[0].pv[1] != MOVE_NONE)
794 std::cout << " ponder " << ss[0].pv[1];
796 std::cout << std::endl;
801 dbg_print_mean(LogFile);
803 if (dbg_show_hit_rate)
804 dbg_print_hit_rate(LogFile);
807 LogFile << "Nodes: " << nodes_searched() << std::endl
808 << "Nodes/second: " << nps() << std::endl
809 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
811 p.do_move(ss[0].pv[0], st);
812 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
813 << std::endl << std::endl;
815 return rml.get_move_score(0);
819 // root_search() is the function which searches the root node. It is
820 // similar to search_pv except that it uses a different move ordering
821 // scheme (perhaps we should try to use this at internal PV nodes, too?)
822 // and prints some information to the standard output.
824 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml, Value alpha, Value beta) {
826 Value oldAlpha = alpha;
828 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
830 // Loop through all the moves in the root move list
831 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
835 // We failed high, invalidate and skip next moves, leave node-counters
836 // and beta-counters as they are and quickly return, we will try to do
837 // a research at the next iteration with a bigger aspiration window.
838 rml.set_move_score(i, -VALUE_INFINITE);
846 RootMoveNumber = i + 1;
849 // Remember the node count before the move is searched. The node counts
850 // are used to sort the root moves at the next iteration.
851 nodes = nodes_searched();
853 // Reset beta cut-off counters
856 // Pick the next root move, and print the move and the move number to
857 // the standard output.
858 move = ss[0].currentMove = rml.get_move(i);
859 if (current_search_time() >= 1000)
860 std::cout << "info currmove " << move
861 << " currmovenumber " << i + 1 << std::endl;
863 // Decide search depth for this move
865 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
866 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
868 // Make the move, and search it
869 pos.do_move(move, st, dcCandidates);
873 // Aspiration window is disabled in multi-pv case
875 alpha = -VALUE_INFINITE;
877 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
878 // If the value has dropped a lot compared to the last iteration,
879 // set the boolean variable Problem to true. This variable is used
880 // for time managment: When Problem is true, we try to complete the
881 // current iteration before playing a move.
882 Problem = (Iteration >= 2 && value <= IterationInfo[Iteration-1].value - ProblemMargin);
884 if (Problem && StopOnPonderhit)
885 StopOnPonderhit = false;
889 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
892 // Fail high! Set the boolean variable FailHigh to true, and
893 // re-search the move with a big window. The variable FailHigh is
894 // used for time managment: We try to avoid aborting the search
895 // prematurely during a fail high research.
897 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
903 // Finished searching the move. If AbortSearch is true, the search
904 // was aborted because the user interrupted the search or because we
905 // ran out of time. In this case, the return value of the search cannot
906 // be trusted, and we break out of the loop without updating the best
911 // Remember the node count for this move. The node counts are used to
912 // sort the root moves at the next iteration.
913 rml.set_move_nodes(i, nodes_searched() - nodes);
915 // Remember the beta-cutoff statistics
917 BetaCounter.read(pos.side_to_move(), our, their);
918 rml.set_beta_counters(i, our, their);
920 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
922 if (value <= alpha && i >= MultiPV)
923 rml.set_move_score(i, -VALUE_INFINITE);
926 // PV move or new best move!
929 rml.set_move_score(i, value);
931 rml.set_move_pv(i, ss[0].pv);
935 // We record how often the best move has been changed in each
936 // iteration. This information is used for time managment: When
937 // the best move changes frequently, we allocate some more time.
939 BestMoveChangesByIteration[Iteration]++;
941 // Print search information to the standard output:
942 std::cout << "info depth " << Iteration
943 << " score " << value_to_string(value)
944 << " time " << current_search_time()
945 << " nodes " << nodes_searched()
949 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
950 std::cout << ss[0].pv[j] << " ";
952 std::cout << std::endl;
955 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
961 // Reset the global variable Problem to false if the value isn't too
962 // far below the final value from the last iteration.
963 if (value > IterationInfo[Iteration - 1].value - NoProblemMargin)
969 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
972 std::cout << "info multipv " << j + 1
973 << " score " << value_to_string(rml.get_move_score(j))
974 << " depth " << ((j <= i)? Iteration : Iteration - 1)
975 << " time " << current_search_time()
976 << " nodes " << nodes_searched()
980 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
981 std::cout << rml.get_move_pv(j, k) << " ";
983 std::cout << std::endl;
985 alpha = rml.get_move_score(Min(i, MultiPV-1));
987 } // New best move case
989 assert(alpha >= oldAlpha);
991 FailLow = (alpha == oldAlpha);
997 // search_pv() is the main search function for PV nodes.
999 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
1000 Depth depth, int ply, int threadID) {
1002 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1003 assert(beta > alpha && beta <= VALUE_INFINITE);
1004 assert(ply >= 0 && ply < PLY_MAX);
1005 assert(threadID >= 0 && threadID < ActiveThreads);
1008 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
1010 // Initialize, and make an early exit in case of an aborted search,
1011 // an instant draw, maximum ply reached, etc.
1012 init_node(ss, ply, threadID);
1014 // After init_node() that calls poll()
1015 if (AbortSearch || thread_should_stop(threadID))
1023 if (ply >= PLY_MAX - 1)
1024 return evaluate(pos, ei, threadID);
1026 // Mate distance pruning
1027 Value oldAlpha = alpha;
1028 alpha = Max(value_mated_in(ply), alpha);
1029 beta = Min(value_mate_in(ply+1), beta);
1033 // Transposition table lookup. At PV nodes, we don't use the TT for
1034 // pruning, but only for move ordering.
1035 const TTEntry* tte = TT.retrieve(pos.get_key());
1036 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1038 // Go with internal iterative deepening if we don't have a TT move
1039 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
1041 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
1042 ttMove = ss[ply].pv[ply];
1045 // Initialize a MovePicker object for the current position, and prepare
1046 // to search all moves
1047 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1049 Move move, movesSearched[256];
1051 Value value, bestValue = -VALUE_INFINITE;
1052 Bitboard dcCandidates = mp.discovered_check_candidates();
1053 Color us = pos.side_to_move();
1054 bool isCheck = pos.is_check();
1055 bool mateThreat = pos.has_mate_threat(opposite_color(us));
1057 // Loop through all legal moves until no moves remain or a beta cutoff
1059 while ( alpha < beta
1060 && (move = mp.get_next_move()) != MOVE_NONE
1061 && !thread_should_stop(threadID))
1063 assert(move_is_ok(move));
1065 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1066 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1067 bool moveIsCapture = pos.move_is_capture(move);
1069 movesSearched[moveCount++] = ss[ply].currentMove = move;
1071 // Decide the new search depth
1073 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1074 Depth newDepth = depth - OnePly + ext;
1076 // Make and search the move
1078 pos.do_move(move, st, dcCandidates);
1080 if (moveCount == 1) // The first move in list is the PV
1081 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1084 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1085 // if the move fails high will be re-searched at full depth.
1086 if ( depth >= 2*OnePly
1087 && moveCount >= LMRPVMoves
1090 && !move_promotion(move)
1091 && !move_is_castle(move)
1092 && !move_is_killer(move, ss[ply]))
1094 ss[ply].reduction = OnePly;
1095 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1098 value = alpha + 1; // Just to trigger next condition
1100 if (value > alpha) // Go with full depth non-pv search
1102 ss[ply].reduction = Depth(0);
1103 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1104 if (value > alpha && value < beta)
1106 // When the search fails high at ply 1 while searching the first
1107 // move at the root, set the flag failHighPly1. This is used for
1108 // time managment: We don't want to stop the search early in
1109 // such cases, because resolving the fail high at ply 1 could
1110 // result in a big drop in score at the root.
1111 if (ply == 1 && RootMoveNumber == 1)
1112 Threads[threadID].failHighPly1 = true;
1114 // A fail high occurred. Re-search at full window (pv search)
1115 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1116 Threads[threadID].failHighPly1 = false;
1120 pos.undo_move(move);
1122 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1125 if (value > bestValue)
1132 if (value == value_mate_in(ply + 1))
1133 ss[ply].mateKiller = move;
1135 // If we are at ply 1, and we are searching the first root move at
1136 // ply 0, set the 'Problem' variable if the score has dropped a lot
1137 // (from the computer's point of view) since the previous iteration:
1140 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1145 if ( ActiveThreads > 1
1147 && depth >= MinimumSplitDepth
1149 && idle_thread_exists(threadID)
1151 && !thread_should_stop(threadID)
1152 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1153 &moveCount, &mp, dcCandidates, threadID, true))
1157 // All legal moves have been searched. A special case: If there were
1158 // no legal moves, it must be mate or stalemate:
1160 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1162 // If the search is not aborted, update the transposition table,
1163 // history counters, and killer moves.
1164 if (AbortSearch || thread_should_stop(threadID))
1167 if (bestValue <= oldAlpha)
1168 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1170 else if (bestValue >= beta)
1172 BetaCounter.add(pos.side_to_move(), depth, threadID);
1173 Move m = ss[ply].pv[ply];
1174 if (ok_to_history(pos, m)) // Only non capture moves are considered
1176 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1177 update_killers(m, ss[ply]);
1179 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1182 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]);
1188 // search() is the search function for zero-width nodes.
1190 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1191 int ply, bool allowNullmove, int threadID) {
1193 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1194 assert(ply >= 0 && ply < PLY_MAX);
1195 assert(threadID >= 0 && threadID < ActiveThreads);
1198 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1200 // Initialize, and make an early exit in case of an aborted search,
1201 // an instant draw, maximum ply reached, etc.
1202 init_node(ss, ply, threadID);
1204 // After init_node() that calls poll()
1205 if (AbortSearch || thread_should_stop(threadID))
1213 if (ply >= PLY_MAX - 1)
1214 return evaluate(pos, ei, threadID);
1216 // Mate distance pruning
1217 if (value_mated_in(ply) >= beta)
1220 if (value_mate_in(ply + 1) < beta)
1223 // Transposition table lookup
1224 const TTEntry* tte = TT.retrieve(pos.get_key());
1225 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1227 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1229 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1230 return value_from_tt(tte->value(), ply);
1233 Value approximateEval = quick_evaluate(pos);
1234 bool mateThreat = false;
1235 bool isCheck = pos.is_check();
1241 && !value_is_mate(beta)
1242 && ok_to_do_nullmove(pos)
1243 && approximateEval >= beta - NullMoveMargin)
1245 ss[ply].currentMove = MOVE_NULL;
1248 pos.do_null_move(st);
1249 int R = (depth >= 5 * OnePly ? 4 : 3); // Null move dynamic reduction
1251 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1253 pos.undo_null_move();
1255 if (value_is_mate(nullValue))
1257 /* Do not return unproven mates */
1259 else if (nullValue >= beta)
1261 if (depth < 6 * OnePly)
1264 // Do zugzwang verification search
1265 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1269 // The null move failed low, which means that we may be faced with
1270 // some kind of threat. If the previous move was reduced, check if
1271 // the move that refuted the null move was somehow connected to the
1272 // move which was reduced. If a connection is found, return a fail
1273 // low score (which will cause the reduced move to fail high in the
1274 // parent node, which will trigger a re-search with full depth).
1275 if (nullValue == value_mated_in(ply + 2))
1278 ss[ply].threatMove = ss[ply + 1].currentMove;
1279 if ( depth < ThreatDepth
1280 && ss[ply - 1].reduction
1281 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1285 // Null move search not allowed, try razoring
1286 else if ( !value_is_mate(beta)
1287 && depth < RazorDepth
1288 && approximateEval < beta - RazorApprMargins[int(depth) - 2]
1289 && ss[ply - 1].currentMove != MOVE_NULL
1290 && ttMove == MOVE_NONE
1291 && !pos.has_pawn_on_7th(pos.side_to_move()))
1293 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1294 if (v < beta - RazorMargins[int(depth) - 2])
1298 // Go with internal iterative deepening if we don't have a TT move
1299 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1300 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1302 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1303 ttMove = ss[ply].pv[ply];
1306 // Initialize a MovePicker object for the current position, and prepare
1307 // to search all moves:
1308 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H, &ss[ply]);
1310 Move move, movesSearched[256];
1312 Value value, bestValue = -VALUE_INFINITE;
1313 Bitboard dcCandidates = mp.discovered_check_candidates();
1314 Value futilityValue = VALUE_NONE;
1315 bool useFutilityPruning = depth < SelectiveDepth
1318 // Loop through all legal moves until no moves remain or a beta cutoff
1320 while ( bestValue < beta
1321 && (move = mp.get_next_move()) != MOVE_NONE
1322 && !thread_should_stop(threadID))
1324 assert(move_is_ok(move));
1326 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1327 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1328 bool moveIsCapture = pos.move_is_capture(move);
1330 movesSearched[moveCount++] = ss[ply].currentMove = move;
1332 // Decide the new search depth
1334 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1335 Depth newDepth = depth - OnePly + ext;
1338 if ( useFutilityPruning
1341 && !move_promotion(move))
1343 // History pruning. See ok_to_prune() definition
1344 if ( moveCount >= 2 + int(depth)
1345 && ok_to_prune(pos, move, ss[ply].threatMove, depth, Threads[threadID].H))
1348 // Value based pruning
1349 if (approximateEval < beta)
1351 if (futilityValue == VALUE_NONE)
1352 futilityValue = evaluate(pos, ei, threadID)
1353 + FutilityMargins[int(depth) - 2];
1355 if (futilityValue < beta)
1357 if (futilityValue > bestValue)
1358 bestValue = futilityValue;
1364 // Make and search the move
1366 pos.do_move(move, st, dcCandidates);
1368 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1369 // if the move fails high will be re-searched at full depth.
1370 if ( depth >= 2*OnePly
1371 && moveCount >= LMRNonPVMoves
1374 && !move_promotion(move)
1375 && !move_is_castle(move)
1376 && !move_is_killer(move, ss[ply]))
1378 ss[ply].reduction = OnePly;
1379 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1382 value = beta; // Just to trigger next condition
1384 if (value >= beta) // Go with full depth non-pv search
1386 ss[ply].reduction = Depth(0);
1387 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1389 pos.undo_move(move);
1391 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1394 if (value > bestValue)
1400 if (value == value_mate_in(ply + 1))
1401 ss[ply].mateKiller = move;
1405 if ( ActiveThreads > 1
1407 && depth >= MinimumSplitDepth
1409 && idle_thread_exists(threadID)
1411 && !thread_should_stop(threadID)
1412 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1413 &mp, dcCandidates, threadID, false))
1417 // All legal moves have been searched. A special case: If there were
1418 // no legal moves, it must be mate or stalemate.
1420 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1422 // If the search is not aborted, update the transposition table,
1423 // history counters, and killer moves.
1424 if (AbortSearch || thread_should_stop(threadID))
1427 if (bestValue < beta)
1428 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE);
1431 BetaCounter.add(pos.side_to_move(), depth, threadID);
1432 Move m = ss[ply].pv[ply];
1433 if (ok_to_history(pos, m)) // Only non capture moves are considered
1435 update_history(pos, m, depth, Threads[threadID].H, movesSearched, moveCount);
1436 update_killers(m, ss[ply]);
1438 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m);
1441 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1447 // qsearch() is the quiescence search function, which is called by the main
1448 // search function when the remaining depth is zero (or, to be more precise,
1449 // less than OnePly).
1451 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1452 Depth depth, int ply, int threadID) {
1454 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1455 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1457 assert(ply >= 0 && ply < PLY_MAX);
1458 assert(threadID >= 0 && threadID < ActiveThreads);
1460 // Initialize, and make an early exit in case of an aborted search,
1461 // an instant draw, maximum ply reached, etc.
1462 init_node(ss, ply, threadID);
1464 // After init_node() that calls poll()
1465 if (AbortSearch || thread_should_stop(threadID))
1471 // Transposition table lookup, only when not in PV
1472 TTEntry* tte = NULL;
1473 bool pvNode = (beta - alpha != 1);
1476 tte = TT.retrieve(pos.get_key());
1477 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1479 assert(tte->type() != VALUE_TYPE_EVAL);
1481 return value_from_tt(tte->value(), ply);
1484 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1486 // Evaluate the position statically
1489 bool isCheck = pos.is_check();
1490 ei.futilityMargin = Value(0); // Manually initialize futilityMargin
1493 staticValue = -VALUE_INFINITE;
1495 else if (tte && tte->type() == VALUE_TYPE_EVAL)
1497 // Use the cached evaluation score if possible
1498 assert(tte->value() == evaluate(pos, ei, threadID));
1499 assert(ei.futilityMargin == Value(0));
1501 staticValue = tte->value();
1504 staticValue = evaluate(pos, ei, threadID);
1506 if (ply == PLY_MAX - 1)
1507 return evaluate(pos, ei, threadID);
1509 // Initialize "stand pat score", and return it immediately if it is
1511 Value bestValue = staticValue;
1513 if (bestValue >= beta)
1515 // Store the score to avoid a future costly evaluation() call
1516 if (!isCheck && !tte && ei.futilityMargin == 0)
1517 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE);
1522 if (bestValue > alpha)
1525 // Initialize a MovePicker object for the current position, and prepare
1526 // to search the moves. Because the depth is <= 0 here, only captures,
1527 // queen promotions and checks (only if depth == 0) will be generated.
1528 MovePicker mp = MovePicker(pos, ttMove, depth, Threads[threadID].H);
1531 Bitboard dcCandidates = mp.discovered_check_candidates();
1532 Color us = pos.side_to_move();
1533 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1535 // Loop through the moves until no moves remain or a beta cutoff
1537 while ( alpha < beta
1538 && (move = mp.get_next_move()) != MOVE_NONE)
1540 assert(move_is_ok(move));
1543 ss[ply].currentMove = move;
1549 && !move_promotion(move)
1550 && !pos.move_is_check(move, dcCandidates)
1551 && !pos.move_is_passed_pawn_push(move))
1553 Value futilityValue = staticValue
1554 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1555 pos.endgame_value_of_piece_on(move_to(move)))
1556 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1558 + ei.futilityMargin;
1560 if (futilityValue < alpha)
1562 if (futilityValue > bestValue)
1563 bestValue = futilityValue;
1568 // Don't search captures and checks with negative SEE values
1570 && !move_promotion(move)
1571 && (pos.midgame_value_of_piece_on(move_from(move)) >
1572 pos.midgame_value_of_piece_on(move_to(move)))
1573 && pos.see(move) < 0)
1576 // Make and search the move.
1578 pos.do_move(move, st, dcCandidates);
1579 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1580 pos.undo_move(move);
1582 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1585 if (value > bestValue)
1596 // All legal moves have been searched. A special case: If we're in check
1597 // and no legal moves were found, it is checkmate:
1598 if (pos.is_check() && moveCount == 0) // Mate!
1599 return value_mated_in(ply);
1601 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1603 // Update transposition table
1604 Move m = ss[ply].pv[ply];
1607 Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1));
1608 if (bestValue < beta)
1609 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE);
1611 TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m);
1614 // Update killers only for good check moves
1615 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1616 update_killers(m, ss[ply]);
1622 // sp_search() is used to search from a split point. This function is called
1623 // by each thread working at the split point. It is similar to the normal
1624 // search() function, but simpler. Because we have already probed the hash
1625 // table, done a null move search, and searched the first move before
1626 // splitting, we don't have to repeat all this work in sp_search(). We
1627 // also don't need to store anything to the hash table here: This is taken
1628 // care of after we return from the split point.
1630 void sp_search(SplitPoint *sp, int threadID) {
1632 assert(threadID >= 0 && threadID < ActiveThreads);
1633 assert(ActiveThreads > 1);
1635 Position pos = Position(sp->pos);
1636 SearchStack *ss = sp->sstack[threadID];
1639 bool isCheck = pos.is_check();
1640 bool useFutilityPruning = sp->depth < SelectiveDepth
1643 while ( sp->bestValue < sp->beta
1644 && !thread_should_stop(threadID)
1645 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1647 assert(move_is_ok(move));
1649 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1650 bool moveIsCapture = pos.move_is_capture(move);
1652 lock_grab(&(sp->lock));
1653 int moveCount = ++sp->moves;
1654 lock_release(&(sp->lock));
1656 ss[sp->ply].currentMove = move;
1658 // Decide the new search depth.
1660 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1661 Depth newDepth = sp->depth - OnePly + ext;
1664 if ( useFutilityPruning
1667 && !move_promotion(move)
1668 && moveCount >= 2 + int(sp->depth)
1669 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth, Threads[threadID].H))
1672 // Make and search the move.
1674 pos.do_move(move, st, sp->dcCandidates);
1676 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1677 // if the move fails high will be re-searched at full depth.
1679 && moveCount >= LMRNonPVMoves
1681 && !move_promotion(move)
1682 && !move_is_castle(move)
1683 && !move_is_killer(move, ss[sp->ply]))
1685 ss[sp->ply].reduction = OnePly;
1686 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1689 value = sp->beta; // Just to trigger next condition
1691 if (value >= sp->beta) // Go with full depth non-pv search
1693 ss[sp->ply].reduction = Depth(0);
1694 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1696 pos.undo_move(move);
1698 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1700 if (thread_should_stop(threadID))
1704 lock_grab(&(sp->lock));
1705 if (value > sp->bestValue && !thread_should_stop(threadID))
1707 sp->bestValue = value;
1708 if (sp->bestValue >= sp->beta)
1710 sp_update_pv(sp->parentSstack, ss, sp->ply);
1711 for (int i = 0; i < ActiveThreads; i++)
1712 if (i != threadID && (i == sp->master || sp->slaves[i]))
1713 Threads[i].stop = true;
1715 sp->finished = true;
1718 lock_release(&(sp->lock));
1721 lock_grab(&(sp->lock));
1723 // If this is the master thread and we have been asked to stop because of
1724 // a beta cutoff higher up in the tree, stop all slave threads:
1725 if (sp->master == threadID && thread_should_stop(threadID))
1726 for (int i = 0; i < ActiveThreads; i++)
1728 Threads[i].stop = true;
1731 sp->slaves[threadID] = 0;
1733 lock_release(&(sp->lock));
1737 // sp_search_pv() is used to search from a PV split point. This function
1738 // is called by each thread working at the split point. It is similar to
1739 // the normal search_pv() function, but simpler. Because we have already
1740 // probed the hash table and searched the first move before splitting, we
1741 // don't have to repeat all this work in sp_search_pv(). We also don't
1742 // need to store anything to the hash table here: This is taken care of
1743 // after we return from the split point.
1745 void sp_search_pv(SplitPoint *sp, int threadID) {
1747 assert(threadID >= 0 && threadID < ActiveThreads);
1748 assert(ActiveThreads > 1);
1750 Position pos = Position(sp->pos);
1751 SearchStack *ss = sp->sstack[threadID];
1755 while ( sp->alpha < sp->beta
1756 && !thread_should_stop(threadID)
1757 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1759 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1760 bool moveIsCapture = pos.move_is_capture(move);
1762 assert(move_is_ok(move));
1764 lock_grab(&(sp->lock));
1765 int moveCount = ++sp->moves;
1766 lock_release(&(sp->lock));
1768 ss[sp->ply].currentMove = move;
1770 // Decide the new search depth.
1772 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1773 Depth newDepth = sp->depth - OnePly + ext;
1775 // Make and search the move.
1777 pos.do_move(move, st, sp->dcCandidates);
1779 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1780 // if the move fails high will be re-searched at full depth.
1782 && moveCount >= LMRPVMoves
1784 && !move_promotion(move)
1785 && !move_is_castle(move)
1786 && !move_is_killer(move, ss[sp->ply]))
1788 ss[sp->ply].reduction = OnePly;
1789 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1792 value = sp->alpha + 1; // Just to trigger next condition
1794 if (value > sp->alpha) // Go with full depth non-pv search
1796 ss[sp->ply].reduction = Depth(0);
1797 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1799 if (value > sp->alpha && value < sp->beta)
1801 // When the search fails high at ply 1 while searching the first
1802 // move at the root, set the flag failHighPly1. This is used for
1803 // time managment: We don't want to stop the search early in
1804 // such cases, because resolving the fail high at ply 1 could
1805 // result in a big drop in score at the root.
1806 if (sp->ply == 1 && RootMoveNumber == 1)
1807 Threads[threadID].failHighPly1 = true;
1809 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1810 Threads[threadID].failHighPly1 = false;
1813 pos.undo_move(move);
1815 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1817 if (thread_should_stop(threadID))
1821 lock_grab(&(sp->lock));
1822 if (value > sp->bestValue && !thread_should_stop(threadID))
1824 sp->bestValue = value;
1825 if (value > sp->alpha)
1828 sp_update_pv(sp->parentSstack, ss, sp->ply);
1829 if (value == value_mate_in(sp->ply + 1))
1830 ss[sp->ply].mateKiller = move;
1832 if(value >= sp->beta)
1834 for(int i = 0; i < ActiveThreads; i++)
1835 if(i != threadID && (i == sp->master || sp->slaves[i]))
1836 Threads[i].stop = true;
1838 sp->finished = true;
1841 // If we are at ply 1, and we are searching the first root move at
1842 // ply 0, set the 'Problem' variable if the score has dropped a lot
1843 // (from the computer's point of view) since the previous iteration.
1846 && -value <= IterationInfo[Iteration-1].value - ProblemMargin)
1849 lock_release(&(sp->lock));
1852 lock_grab(&(sp->lock));
1854 // If this is the master thread and we have been asked to stop because of
1855 // a beta cutoff higher up in the tree, stop all slave threads.
1856 if (sp->master == threadID && thread_should_stop(threadID))
1857 for (int i = 0; i < ActiveThreads; i++)
1859 Threads[i].stop = true;
1862 sp->slaves[threadID] = 0;
1864 lock_release(&(sp->lock));
1867 /// The BetaCounterType class
1869 BetaCounterType::BetaCounterType() { clear(); }
1871 void BetaCounterType::clear() {
1873 for (int i = 0; i < THREAD_MAX; i++)
1874 Threads[i].betaCutOffs[WHITE] = Threads[i].betaCutOffs[BLACK] = 0ULL;
1877 void BetaCounterType::add(Color us, Depth d, int threadID) {
1879 // Weighted count based on depth
1880 Threads[threadID].betaCutOffs[us] += unsigned(d);
1883 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1886 for (int i = 0; i < THREAD_MAX; i++)
1888 our += Threads[i].betaCutOffs[us];
1889 their += Threads[i].betaCutOffs[opposite_color(us)];
1894 /// The RootMove class
1898 RootMove::RootMove() {
1899 nodes = cumulativeNodes = ourBeta = theirBeta = 0ULL;
1902 // RootMove::operator<() is the comparison function used when
1903 // sorting the moves. A move m1 is considered to be better
1904 // than a move m2 if it has a higher score, or if the moves
1905 // have equal score but m1 has the higher node count.
1907 bool RootMove::operator<(const RootMove& m) {
1909 if (score != m.score)
1910 return (score < m.score);
1912 return theirBeta <= m.theirBeta;
1915 /// The RootMoveList class
1919 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1921 MoveStack mlist[MaxRootMoves];
1922 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1924 // Generate all legal moves
1925 int lm_count = generate_legal_moves(pos, mlist);
1927 // Add each move to the moves[] array
1928 for (int i = 0; i < lm_count; i++)
1930 bool includeMove = includeAllMoves;
1932 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1933 includeMove = (searchMoves[k] == mlist[i].move);
1938 // Find a quick score for the move
1940 SearchStack ss[PLY_MAX_PLUS_2];
1942 moves[count].move = mlist[i].move;
1943 pos.do_move(moves[count].move, st);
1944 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0);
1945 pos.undo_move(moves[count].move);
1946 moves[count].pv[0] = moves[count].move;
1947 moves[count].pv[1] = MOVE_NONE; // FIXME
1954 // Simple accessor methods for the RootMoveList class
1956 inline Move RootMoveList::get_move(int moveNum) const {
1957 return moves[moveNum].move;
1960 inline Value RootMoveList::get_move_score(int moveNum) const {
1961 return moves[moveNum].score;
1964 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1965 moves[moveNum].score = score;
1968 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1969 moves[moveNum].nodes = nodes;
1970 moves[moveNum].cumulativeNodes += nodes;
1973 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1974 moves[moveNum].ourBeta = our;
1975 moves[moveNum].theirBeta = their;
1978 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1980 for(j = 0; pv[j] != MOVE_NONE; j++)
1981 moves[moveNum].pv[j] = pv[j];
1982 moves[moveNum].pv[j] = MOVE_NONE;
1985 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1986 return moves[moveNum].pv[i];
1989 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1990 return moves[moveNum].cumulativeNodes;
1993 inline int RootMoveList::move_count() const {
1998 // RootMoveList::scan_for_easy_move() is called at the end of the first
1999 // iteration, and is used to detect an "easy move", i.e. a move which appears
2000 // to be much bester than all the rest. If an easy move is found, the move
2001 // is returned, otherwise the function returns MOVE_NONE. It is very
2002 // important that this function is called at the right moment: The code
2003 // assumes that the first iteration has been completed and the moves have
2004 // been sorted. This is done in RootMoveList c'tor.
2006 Move RootMoveList::scan_for_easy_move() const {
2013 // moves are sorted so just consider the best and the second one
2014 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
2020 // RootMoveList::sort() sorts the root move list at the beginning of a new
2023 inline void RootMoveList::sort() {
2025 sort_multipv(count - 1); // all items
2029 // RootMoveList::sort_multipv() sorts the first few moves in the root move
2030 // list by their scores and depths. It is used to order the different PVs
2031 // correctly in MultiPV mode.
2033 void RootMoveList::sort_multipv(int n) {
2035 for (int i = 1; i <= n; i++)
2037 RootMove rm = moves[i];
2039 for (j = i; j > 0 && moves[j-1] < rm; j--)
2040 moves[j] = moves[j-1];
2046 // init_node() is called at the beginning of all the search functions
2047 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2048 // stack object corresponding to the current node. Once every
2049 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2050 // for user input and checks whether it is time to stop the search.
2052 void init_node(SearchStack ss[], int ply, int threadID) {
2053 assert(ply >= 0 && ply < PLY_MAX);
2054 assert(threadID >= 0 && threadID < ActiveThreads);
2056 Threads[threadID].nodes++;
2060 if(NodesSincePoll >= NodesBetweenPolls) {
2067 ss[ply+2].initKillers();
2069 if(Threads[threadID].printCurrentLine)
2070 print_current_line(ss, ply, threadID);
2074 // update_pv() is called whenever a search returns a value > alpha. It
2075 // updates the PV in the SearchStack object corresponding to the current
2078 void update_pv(SearchStack ss[], int ply) {
2079 assert(ply >= 0 && ply < PLY_MAX);
2081 ss[ply].pv[ply] = ss[ply].currentMove;
2083 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2084 ss[ply].pv[p] = ss[ply+1].pv[p];
2085 ss[ply].pv[p] = MOVE_NONE;
2089 // sp_update_pv() is a variant of update_pv for use at split points. The
2090 // difference between the two functions is that sp_update_pv also updates
2091 // the PV at the parent node.
2093 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2094 assert(ply >= 0 && ply < PLY_MAX);
2096 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2098 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2099 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2100 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2104 // connected_moves() tests whether two moves are 'connected' in the sense
2105 // that the first move somehow made the second move possible (for instance
2106 // if the moving piece is the same in both moves). The first move is
2107 // assumed to be the move that was made to reach the current position, while
2108 // the second move is assumed to be a move from the current position.
2110 bool connected_moves(const Position &pos, Move m1, Move m2) {
2111 Square f1, t1, f2, t2;
2113 assert(move_is_ok(m1));
2114 assert(move_is_ok(m2));
2119 // Case 1: The moving piece is the same in both moves.
2125 // Case 2: The destination square for m2 was vacated by m1.
2131 // Case 3: Moving through the vacated square:
2132 if(piece_is_slider(pos.piece_on(f2)) &&
2133 bit_is_set(squares_between(f2, t2), f1))
2136 // Case 4: The destination square for m2 is attacked by the moving piece
2138 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2141 // Case 5: Discovered check, checking piece is the piece moved in m1:
2142 if(piece_is_slider(pos.piece_on(t1)) &&
2143 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2145 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2147 Bitboard occ = pos.occupied_squares();
2148 Color us = pos.side_to_move();
2149 Square ksq = pos.king_square(us);
2150 clear_bit(&occ, f2);
2151 if(pos.type_of_piece_on(t1) == BISHOP) {
2152 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2155 else if(pos.type_of_piece_on(t1) == ROOK) {
2156 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2160 assert(pos.type_of_piece_on(t1) == QUEEN);
2161 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2170 // value_is_mate() checks if the given value is a mate one
2171 // eventually compensated for the ply.
2173 bool value_is_mate(Value value) {
2175 assert(abs(value) <= VALUE_INFINITE);
2177 return value <= value_mated_in(PLY_MAX)
2178 || value >= value_mate_in(PLY_MAX);
2182 // move_is_killer() checks if the given move is among the
2183 // killer moves of that ply.
2185 bool move_is_killer(Move m, const SearchStack& ss) {
2187 const Move* k = ss.killers;
2188 for (int i = 0; i < KILLER_MAX; i++, k++)
2196 // extension() decides whether a move should be searched with normal depth,
2197 // or with extended depth. Certain classes of moves (checking moves, in
2198 // particular) are searched with bigger depth than ordinary moves and in
2199 // any case are marked as 'dangerous'. Note that also if a move is not
2200 // extended, as example because the corresponding UCI option is set to zero,
2201 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2203 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2204 bool singleReply, bool mateThreat, bool* dangerous) {
2206 assert(m != MOVE_NONE);
2208 Depth result = Depth(0);
2209 *dangerous = check || singleReply || mateThreat;
2212 result += CheckExtension[pvNode];
2215 result += SingleReplyExtension[pvNode];
2218 result += MateThreatExtension[pvNode];
2220 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2222 if (pos.move_is_pawn_push_to_7th(m))
2224 result += PawnPushTo7thExtension[pvNode];
2227 if (pos.move_is_passed_pawn_push(m))
2229 result += PassedPawnExtension[pvNode];
2235 && pos.type_of_piece_on(move_to(m)) != PAWN
2236 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2237 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2238 && !move_promotion(m)
2241 result += PawnEndgameExtension[pvNode];
2247 && pos.type_of_piece_on(move_to(m)) != PAWN
2254 return Min(result, OnePly);
2258 // ok_to_do_nullmove() looks at the current position and decides whether
2259 // doing a 'null move' should be allowed. In order to avoid zugzwang
2260 // problems, null moves are not allowed when the side to move has very
2261 // little material left. Currently, the test is a bit too simple: Null
2262 // moves are avoided only when the side to move has only pawns left. It's
2263 // probably a good idea to avoid null moves in at least some more
2264 // complicated endgames, e.g. KQ vs KR. FIXME
2266 bool ok_to_do_nullmove(const Position &pos) {
2267 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2273 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2274 // non-tactical moves late in the move list close to the leaves are
2275 // candidates for pruning.
2277 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d, const History& H) {
2278 Square mfrom, mto, tfrom, tto;
2280 assert(move_is_ok(m));
2281 assert(threat == MOVE_NONE || move_is_ok(threat));
2282 assert(!move_promotion(m));
2283 assert(!pos.move_is_check(m));
2284 assert(!pos.move_is_capture(m));
2285 assert(!pos.move_is_passed_pawn_push(m));
2286 assert(d >= OnePly);
2288 mfrom = move_from(m);
2290 tfrom = move_from(threat);
2291 tto = move_to(threat);
2293 // Case 1: Castling moves are never pruned.
2294 if (move_is_castle(m))
2297 // Case 2: Don't prune moves which move the threatened piece
2298 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2301 // Case 3: If the threatened piece has value less than or equal to the
2302 // value of the threatening piece, don't prune move which defend it.
2303 if ( !PruneDefendingMoves
2304 && threat != MOVE_NONE
2305 && pos.move_is_capture(threat)
2306 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2307 || pos.type_of_piece_on(tfrom) == KING)
2308 && pos.move_attacks_square(m, tto))
2311 // Case 4: Don't prune moves with good history.
2312 if (!H.ok_to_prune(pos.piece_on(mfrom), mto, d))
2315 // Case 5: If the moving piece in the threatened move is a slider, don't
2316 // prune safe moves which block its ray.
2317 if ( !PruneBlockingMoves
2318 && threat != MOVE_NONE
2319 && piece_is_slider(pos.piece_on(tfrom))
2320 && bit_is_set(squares_between(tfrom, tto), mto)
2328 // ok_to_use_TT() returns true if a transposition table score
2329 // can be used at a given point in search.
2331 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2333 Value v = value_from_tt(tte->value(), ply);
2335 return ( tte->depth() >= depth
2336 || v >= Max(value_mate_in(100), beta)
2337 || v < Min(value_mated_in(100), beta))
2339 && ( (is_lower_bound(tte->type()) && v >= beta)
2340 || (is_upper_bound(tte->type()) && v < beta));
2344 // ok_to_history() returns true if a move m can be stored
2345 // in history. Should be a non capturing move nor a promotion.
2347 bool ok_to_history(const Position& pos, Move m) {
2349 return !pos.move_is_capture(m) && !move_promotion(m);
2353 // update_history() registers a good move that produced a beta-cutoff
2354 // in history and marks as failures all the other moves of that ply.
2356 void update_history(const Position& pos, Move m, Depth depth, History& H,
2357 Move movesSearched[], int moveCount) {
2359 H.success(pos.piece_on(move_from(m)), move_to(m), depth);
2361 for (int i = 0; i < moveCount - 1; i++)
2363 assert(m != movesSearched[i]);
2364 if (ok_to_history(pos, movesSearched[i]))
2365 H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i]));
2370 // update_killers() add a good move that produced a beta-cutoff
2371 // among the killer moves of that ply.
2373 void update_killers(Move m, SearchStack& ss) {
2375 if (m == ss.killers[0])
2378 for (int i = KILLER_MAX - 1; i > 0; i--)
2379 ss.killers[i] = ss.killers[i - 1];
2384 // fail_high_ply_1() checks if some thread is currently resolving a fail
2385 // high at ply 1 at the node below the first root node. This information
2386 // is used for time managment.
2388 bool fail_high_ply_1() {
2389 for(int i = 0; i < ActiveThreads; i++)
2390 if(Threads[i].failHighPly1)
2396 // current_search_time() returns the number of milliseconds which have passed
2397 // since the beginning of the current search.
2399 int current_search_time() {
2400 return get_system_time() - SearchStartTime;
2404 // nps() computes the current nodes/second count.
2407 int t = current_search_time();
2408 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2412 // poll() performs two different functions: It polls for user input, and it
2413 // looks at the time consumed so far and decides if it's time to abort the
2418 static int lastInfoTime;
2419 int t = current_search_time();
2424 // We are line oriented, don't read single chars
2425 std::string command;
2426 if (!std::getline(std::cin, command))
2429 if (command == "quit")
2432 PonderSearch = false;
2436 else if(command == "stop")
2439 PonderSearch = false;
2441 else if(command == "ponderhit")
2444 // Print search information
2448 else if (lastInfoTime > t)
2449 // HACK: Must be a new search where we searched less than
2450 // NodesBetweenPolls nodes during the first second of search.
2453 else if (t - lastInfoTime >= 1000)
2460 if (dbg_show_hit_rate)
2461 dbg_print_hit_rate();
2463 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2464 << " time " << t << " hashfull " << TT.full() << std::endl;
2465 lock_release(&IOLock);
2466 if (ShowCurrentLine)
2467 Threads[0].printCurrentLine = true;
2469 // Should we stop the search?
2473 bool overTime = t > AbsoluteMaxSearchTime
2474 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime && !FailLow) //FIXME: We are not checking any problem flags, BUG?
2475 || ( !FailHigh && !FailLow && !fail_high_ply_1() && !Problem
2476 && t > 6*(MaxSearchTime + ExtraSearchTime));
2478 if ( (Iteration >= 3 && (!InfiniteSearch && overTime))
2479 || (ExactMaxTime && t >= ExactMaxTime)
2480 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2485 // ponderhit() is called when the program is pondering (i.e. thinking while
2486 // it's the opponent's turn to move) in order to let the engine know that
2487 // it correctly predicted the opponent's move.
2490 int t = current_search_time();
2491 PonderSearch = false;
2492 if(Iteration >= 3 &&
2493 (!InfiniteSearch && (StopOnPonderhit ||
2494 t > AbsoluteMaxSearchTime ||
2495 (RootMoveNumber == 1 &&
2496 t > MaxSearchTime + ExtraSearchTime && !FailLow) ||
2497 (!FailHigh && !FailLow && !fail_high_ply_1() && !Problem &&
2498 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2503 // print_current_line() prints the current line of search for a given
2504 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2506 void print_current_line(SearchStack ss[], int ply, int threadID) {
2507 assert(ply >= 0 && ply < PLY_MAX);
2508 assert(threadID >= 0 && threadID < ActiveThreads);
2510 if(!Threads[threadID].idle) {
2512 std::cout << "info currline " << (threadID + 1);
2513 for(int p = 0; p < ply; p++)
2514 std::cout << " " << ss[p].currentMove;
2515 std::cout << std::endl;
2516 lock_release(&IOLock);
2518 Threads[threadID].printCurrentLine = false;
2519 if(threadID + 1 < ActiveThreads)
2520 Threads[threadID + 1].printCurrentLine = true;
2524 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2525 // while the program is pondering. The point is to work around a wrinkle in
2526 // the UCI protocol: When pondering, the engine is not allowed to give a
2527 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2528 // We simply wait here until one of these commands is sent, and return,
2529 // after which the bestmove and pondermove will be printed (in id_loop()).
2531 void wait_for_stop_or_ponderhit() {
2533 std::string command;
2537 if (!std::getline(std::cin, command))
2540 if (command == "quit")
2545 else if(command == "ponderhit" || command == "stop")
2551 // idle_loop() is where the threads are parked when they have no work to do.
2552 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2553 // object for which the current thread is the master.
2555 void idle_loop(int threadID, SplitPoint *waitSp) {
2556 assert(threadID >= 0 && threadID < THREAD_MAX);
2558 Threads[threadID].running = true;
2561 if(AllThreadsShouldExit && threadID != 0)
2564 // If we are not thinking, wait for a condition to be signaled instead
2565 // of wasting CPU time polling for work:
2566 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2567 #if !defined(_MSC_VER)
2568 pthread_mutex_lock(&WaitLock);
2569 if(Idle || threadID >= ActiveThreads)
2570 pthread_cond_wait(&WaitCond, &WaitLock);
2571 pthread_mutex_unlock(&WaitLock);
2573 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2577 // If this thread has been assigned work, launch a search:
2578 if(Threads[threadID].workIsWaiting) {
2579 Threads[threadID].workIsWaiting = false;
2580 if(Threads[threadID].splitPoint->pvNode)
2581 sp_search_pv(Threads[threadID].splitPoint, threadID);
2583 sp_search(Threads[threadID].splitPoint, threadID);
2584 Threads[threadID].idle = true;
2587 // If this thread is the master of a split point and all threads have
2588 // finished their work at this split point, return from the idle loop:
2589 if(waitSp != NULL && waitSp->cpus == 0)
2593 Threads[threadID].running = false;
2597 // init_split_point_stack() is called during program initialization, and
2598 // initializes all split point objects.
2600 void init_split_point_stack() {
2601 for(int i = 0; i < THREAD_MAX; i++)
2602 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2603 SplitPointStack[i][j].parent = NULL;
2604 lock_init(&(SplitPointStack[i][j].lock), NULL);
2609 // destroy_split_point_stack() is called when the program exits, and
2610 // destroys all locks in the precomputed split point objects.
2612 void destroy_split_point_stack() {
2613 for(int i = 0; i < THREAD_MAX; i++)
2614 for(int j = 0; j < MaxActiveSplitPoints; j++)
2615 lock_destroy(&(SplitPointStack[i][j].lock));
2619 // thread_should_stop() checks whether the thread with a given threadID has
2620 // been asked to stop, directly or indirectly. This can happen if a beta
2621 // cutoff has occured in thre thread's currently active split point, or in
2622 // some ancestor of the current split point.
2624 bool thread_should_stop(int threadID) {
2625 assert(threadID >= 0 && threadID < ActiveThreads);
2629 if(Threads[threadID].stop)
2631 if(ActiveThreads <= 2)
2633 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2635 Threads[threadID].stop = true;
2642 // thread_is_available() checks whether the thread with threadID "slave" is
2643 // available to help the thread with threadID "master" at a split point. An
2644 // obvious requirement is that "slave" must be idle. With more than two
2645 // threads, this is not by itself sufficient: If "slave" is the master of
2646 // some active split point, it is only available as a slave to the other
2647 // threads which are busy searching the split point at the top of "slave"'s
2648 // split point stack (the "helpful master concept" in YBWC terminology).
2650 bool thread_is_available(int slave, int master) {
2651 assert(slave >= 0 && slave < ActiveThreads);
2652 assert(master >= 0 && master < ActiveThreads);
2653 assert(ActiveThreads > 1);
2655 if(!Threads[slave].idle || slave == master)
2658 if(Threads[slave].activeSplitPoints == 0)
2659 // No active split points means that the thread is available as a slave
2660 // for any other thread.
2663 if(ActiveThreads == 2)
2666 // Apply the "helpful master" concept if possible.
2667 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2674 // idle_thread_exists() tries to find an idle thread which is available as
2675 // a slave for the thread with threadID "master".
2677 bool idle_thread_exists(int master) {
2678 assert(master >= 0 && master < ActiveThreads);
2679 assert(ActiveThreads > 1);
2681 for(int i = 0; i < ActiveThreads; i++)
2682 if(thread_is_available(i, master))
2688 // split() does the actual work of distributing the work at a node between
2689 // several threads at PV nodes. If it does not succeed in splitting the
2690 // node (because no idle threads are available, or because we have no unused
2691 // split point objects), the function immediately returns false. If
2692 // splitting is possible, a SplitPoint object is initialized with all the
2693 // data that must be copied to the helper threads (the current position and
2694 // search stack, alpha, beta, the search depth, etc.), and we tell our
2695 // helper threads that they have been assigned work. This will cause them
2696 // to instantly leave their idle loops and call sp_search_pv(). When all
2697 // threads have returned from sp_search_pv (or, equivalently, when
2698 // splitPoint->cpus becomes 0), split() returns true.
2700 bool split(const Position &p, SearchStack *sstck, int ply,
2701 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2702 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2705 assert(sstck != NULL);
2706 assert(ply >= 0 && ply < PLY_MAX);
2707 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2708 assert(!pvNode || *alpha < *beta);
2709 assert(*beta <= VALUE_INFINITE);
2710 assert(depth > Depth(0));
2711 assert(master >= 0 && master < ActiveThreads);
2712 assert(ActiveThreads > 1);
2714 SplitPoint *splitPoint;
2719 // If no other thread is available to help us, or if we have too many
2720 // active split points, don't split:
2721 if(!idle_thread_exists(master) ||
2722 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2723 lock_release(&MPLock);
2727 // Pick the next available split point object from the split point stack:
2728 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2729 Threads[master].activeSplitPoints++;
2731 // Initialize the split point object:
2732 splitPoint->parent = Threads[master].splitPoint;
2733 splitPoint->finished = false;
2734 splitPoint->ply = ply;
2735 splitPoint->depth = depth;
2736 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2737 splitPoint->beta = *beta;
2738 splitPoint->pvNode = pvNode;
2739 splitPoint->dcCandidates = dcCandidates;
2740 splitPoint->bestValue = *bestValue;
2741 splitPoint->master = master;
2742 splitPoint->mp = mp;
2743 splitPoint->moves = *moves;
2744 splitPoint->cpus = 1;
2745 splitPoint->pos.copy(p);
2746 splitPoint->parentSstack = sstck;
2747 for(i = 0; i < ActiveThreads; i++)
2748 splitPoint->slaves[i] = 0;
2750 // Copy the current position and the search stack to the master thread:
2751 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2752 Threads[master].splitPoint = splitPoint;
2754 // Make copies of the current position and search stack for each thread:
2755 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2757 if(thread_is_available(i, master)) {
2758 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2759 Threads[i].splitPoint = splitPoint;
2760 splitPoint->slaves[i] = 1;
2764 // Tell the threads that they have work to do. This will make them leave
2766 for(i = 0; i < ActiveThreads; i++)
2767 if(i == master || splitPoint->slaves[i]) {
2768 Threads[i].workIsWaiting = true;
2769 Threads[i].idle = false;
2770 Threads[i].stop = false;
2773 lock_release(&MPLock);
2775 // Everything is set up. The master thread enters the idle loop, from
2776 // which it will instantly launch a search, because its workIsWaiting
2777 // slot is 'true'. We send the split point as a second parameter to the
2778 // idle loop, which means that the main thread will return from the idle
2779 // loop when all threads have finished their work at this split point
2780 // (i.e. when // splitPoint->cpus == 0).
2781 idle_loop(master, splitPoint);
2783 // We have returned from the idle loop, which means that all threads are
2784 // finished. Update alpha, beta and bestvalue, and return:
2786 if(pvNode) *alpha = splitPoint->alpha;
2787 *beta = splitPoint->beta;
2788 *bestValue = splitPoint->bestValue;
2789 Threads[master].stop = false;
2790 Threads[master].idle = false;
2791 Threads[master].activeSplitPoints--;
2792 Threads[master].splitPoint = splitPoint->parent;
2793 lock_release(&MPLock);
2799 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2800 // to start a new search from the root.
2802 void wake_sleeping_threads() {
2803 if(ActiveThreads > 1) {
2804 for(int i = 1; i < ActiveThreads; i++) {
2805 Threads[i].idle = true;
2806 Threads[i].workIsWaiting = false;
2808 #if !defined(_MSC_VER)
2809 pthread_mutex_lock(&WaitLock);
2810 pthread_cond_broadcast(&WaitCond);
2811 pthread_mutex_unlock(&WaitLock);
2813 for(int i = 1; i < THREAD_MAX; i++)
2814 SetEvent(SitIdleEvent[i]);
2820 // init_thread() is the function which is called when a new thread is
2821 // launched. It simply calls the idle_loop() function with the supplied
2822 // threadID. There are two versions of this function; one for POSIX threads
2823 // and one for Windows threads.
2825 #if !defined(_MSC_VER)
2827 void *init_thread(void *threadID) {
2828 idle_loop(*(int *)threadID, NULL);
2834 DWORD WINAPI init_thread(LPVOID threadID) {
2835 idle_loop(*(int *)threadID, NULL);