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 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/>.
39 #include "ucioption.h"
43 //// Local definitions
50 // The BetaCounterType class is used to order moves at ply one.
51 // Apart for the first one that has its score, following moves
52 // normally have score -VALUE_INFINITE, so are ordered according
53 // to the number of beta cutoffs occurred under their subtree during
54 // the last iteration.
56 struct BetaCounterType {
60 void add(Color us, Depth d, int threadID);
61 void read(Color us, int64_t& our, int64_t& their);
63 int64_t hits[THREAD_MAX][2];
67 // The RootMove class is used for moves at the root at the tree. For each
68 // root move, we store a score, a node count, and a PV (really a refutation
69 // in the case of moves which fail low).
74 bool operator<(const RootMove&); // used to sort
78 int64_t nodes, cumulativeNodes;
79 Move pv[PLY_MAX_PLUS_2];
80 int64_t ourBeta, theirBeta;
84 // The RootMoveList class is essentially an array of RootMove objects, with
85 // a handful of methods for accessing the data in the individual moves.
90 RootMoveList(Position &pos, Move searchMoves[]);
91 inline Move get_move(int moveNum) const;
92 inline Value get_move_score(int moveNum) const;
93 inline void set_move_score(int moveNum, Value score);
94 inline void set_move_nodes(int moveNum, int64_t nodes);
95 inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
96 void set_move_pv(int moveNum, const Move pv[]);
97 inline Move get_move_pv(int moveNum, int i) const;
98 inline int64_t get_move_cumulative_nodes(int moveNum) const;
99 inline int move_count() const;
100 Move scan_for_easy_move() const;
102 void sort_multipv(int n);
105 static const int MaxRootMoves = 500;
106 RootMove moves[MaxRootMoves];
111 /// Constants and variables
113 // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
116 int LMRNonPVMoves = 4;
118 // Depth limit for use of dynamic threat detection:
119 Depth ThreatDepth = 5*OnePly;
121 // Depth limit for selective search:
122 Depth SelectiveDepth = 7*OnePly;
124 // Use internal iterative deepening?
125 const bool UseIIDAtPVNodes = true;
126 const bool UseIIDAtNonPVNodes = false;
128 // Use null move driven internal iterative deepening?
129 bool UseNullDrivenIID = false;
131 // Internal iterative deepening margin. At Non-PV moves, when
132 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
133 // when the static evaluation is at most IIDMargin below beta.
134 const Value IIDMargin = Value(0x100);
136 // Easy move margin. An easy move candidate must be at least this much
137 // better than the second best move.
138 const Value EasyMoveMargin = Value(0x200);
140 // Problem margin. If the score of the first move at iteration N+1 has
141 // dropped by more than this since iteration N, the boolean variable
142 // "Problem" is set to true, which will make the program spend some extra
143 // time looking for a better move.
144 const Value ProblemMargin = Value(0x28);
146 // No problem margin. If the boolean "Problem" is true, and a new move
147 // is found at the root which is less than NoProblemMargin worse than the
148 // best move from the previous iteration, Problem is set back to false.
149 const Value NoProblemMargin = Value(0x14);
151 // Null move margin. A null move search will not be done if the approximate
152 // evaluation of the position is more than NullMoveMargin below beta.
153 const Value NullMoveMargin = Value(0x300);
155 // Pruning criterions. See the code and comments in ok_to_prune() to
156 // understand their precise meaning.
157 const bool PruneEscapeMoves = false;
158 const bool PruneDefendingMoves = false;
159 const bool PruneBlockingMoves = false;
161 // Use futility pruning?
162 bool UseQSearchFutilityPruning = true;
163 bool UseFutilityPruning = true;
165 // Margins for futility pruning in the quiescence search, and at frontier
166 // and near frontier nodes
167 Value FutilityMarginQS = Value(0x80);
168 Value FutilityMargins[6] = { Value(0x120), Value(0x220), Value(0x250),
169 Value(0x280), Value(0x320), Value(0x360) };
172 Depth RazorDepth = 4*OnePly;
173 Value RazorMargin = Value(0x300);
175 // Last seconds noise filtering (LSN)
176 bool UseLSNFiltering = false;
177 bool looseOnTime = false;
178 int LSNTime = 4 * 1000; // In milliseconds
179 Value LSNValue = Value(0x200);
181 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
182 Depth CheckExtension[2] = {OnePly, OnePly};
183 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
184 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
185 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
186 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
187 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
189 // Search depth at iteration 1
190 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
194 int NodesBetweenPolls = 30000;
196 // Iteration counters
199 BetaCounterType BetaCounter;
201 // Scores and number of times the best move changed for each iteration:
202 Value ValueByIteration[PLY_MAX_PLUS_2];
203 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
208 // Time managment variables
210 int MaxNodes, MaxDepth;
211 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
212 Move BestRootMove, PonderMove, EasyMove;
216 bool StopOnPonderhit;
221 bool PonderingEnabled;
224 // Show current line?
225 bool ShowCurrentLine = false;
228 bool UseLogFile = false;
229 std::ofstream LogFile;
231 // MP related variables
232 Depth MinimumSplitDepth = 4*OnePly;
233 int MaxThreadsPerSplitPoint = 4;
234 Thread Threads[THREAD_MAX];
236 bool AllThreadsShouldExit = false;
237 const int MaxActiveSplitPoints = 8;
238 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
241 #if !defined(_MSC_VER)
242 pthread_cond_t WaitCond;
243 pthread_mutex_t WaitLock;
245 HANDLE SitIdleEvent[THREAD_MAX];
251 Value id_loop(const Position &pos, Move searchMoves[]);
252 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
253 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
254 Depth depth, int ply, int threadID);
255 Value search(Position &pos, SearchStack ss[], Value beta,
256 Depth depth, int ply, bool allowNullmove, int threadID);
257 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
258 Depth depth, int ply, int threadID);
259 void sp_search(SplitPoint *sp, int threadID);
260 void sp_search_pv(SplitPoint *sp, int threadID);
261 void init_search_stack(SearchStack& ss);
262 void init_search_stack(SearchStack ss[]);
263 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
264 void update_pv(SearchStack ss[], int ply);
265 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
266 bool connected_moves(const Position &pos, Move m1, Move m2);
267 bool value_is_mate(Value value);
268 bool move_is_killer(Move m, const SearchStack& ss);
269 Depth extension(const Position &pos, Move m, bool pvNode, bool check, bool singleReply, bool mateThreat, bool* dangerous);
270 bool ok_to_do_nullmove(const Position &pos);
271 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
272 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
273 bool ok_to_history(const Position &pos, Move m);
274 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
275 void update_killers(Move m, SearchStack& ss);
277 bool fail_high_ply_1();
278 int current_search_time();
282 void print_current_line(SearchStack ss[], int ply, int threadID);
283 void wait_for_stop_or_ponderhit();
285 void idle_loop(int threadID, SplitPoint *waitSp);
286 void init_split_point_stack();
287 void destroy_split_point_stack();
288 bool thread_should_stop(int threadID);
289 bool thread_is_available(int slave, int master);
290 bool idle_thread_exists(int master);
291 bool split(const Position &pos, SearchStack *ss, int ply,
292 Value *alpha, Value *beta, Value *bestValue, Depth depth,
293 int *moves, MovePicker *mp, Bitboard dcCandidates, int master,
295 void wake_sleeping_threads();
297 #if !defined(_MSC_VER)
298 void *init_thread(void *threadID);
300 DWORD WINAPI init_thread(LPVOID threadID);
307 //// Global variables
310 // The main transposition table
311 TranspositionTable TT = TranspositionTable(TTDefaultSize);
314 // Number of active threads:
315 int ActiveThreads = 1;
317 // Locks. In principle, there is no need for IOLock to be a global variable,
318 // but it could turn out to be useful for debugging.
321 History H; // Should be made local?
323 // The empty search stack
324 SearchStack EmptySearchStack;
331 /// think() is the external interface to Stockfish's search, and is called when
332 /// the program receives the UCI 'go' command. It initializes various
333 /// search-related global variables, and calls root_search()
335 void 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())
346 OpeningBook.open("book.bin");
348 bookMove = OpeningBook.get_move(pos);
349 if (bookMove != MOVE_NONE)
351 std::cout << "bestmove " << bookMove << std::endl;
356 // Initialize global search variables
358 SearchStartTime = get_system_time();
359 BestRootMove = MOVE_NONE;
360 PonderMove = MOVE_NONE;
361 EasyMove = MOVE_NONE;
362 for (int i = 0; i < THREAD_MAX; i++)
364 Threads[i].nodes = 0ULL;
365 Threads[i].failHighPly1 = false;
368 InfiniteSearch = infinite;
369 PonderSearch = ponder;
370 StopOnPonderhit = false;
375 ExactMaxTime = maxTime;
377 // Read UCI option values
378 TT.set_size(get_option_value_int("Hash"));
379 if (button_was_pressed("Clear Hash"))
382 PonderingEnabled = get_option_value_bool("Ponder");
383 MultiPV = get_option_value_int("MultiPV");
385 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
386 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
388 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
389 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
391 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
392 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
394 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
395 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
397 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
398 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
400 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
401 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
403 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
404 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
405 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
406 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
408 Chess960 = get_option_value_bool("UCI_Chess960");
409 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
410 UseLogFile = get_option_value_bool("Use Search Log");
412 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
414 UseNullDrivenIID = get_option_value_bool("Null driven IID");
415 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
416 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
418 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
419 int fmScale = get_option_value_int("Futility Margin (Main Serach)");
420 for (int i = 0; i < 6; i++)
421 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
423 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
424 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
426 UseLSNFiltering = get_option_value_bool("LSN filtering");
427 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
428 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
430 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
431 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
433 read_weights(pos.side_to_move());
435 int newActiveThreads = get_option_value_int("Threads");
436 if (newActiveThreads != ActiveThreads)
438 ActiveThreads = newActiveThreads;
439 init_eval(ActiveThreads);
442 // Wake up sleeping threads:
443 wake_sleeping_threads();
445 for (int i = 1; i < ActiveThreads; i++)
446 assert(thread_is_available(i, 0));
448 // Set thinking time:
449 int myTime = time[side_to_move];
450 int myIncrement = increment[side_to_move];
451 int oppTime = time[1 - side_to_move];
453 if (!movesToGo) // Sudden death time control
457 MaxSearchTime = myTime / 30 + myIncrement;
458 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
459 } else { // Blitz game without increment
460 MaxSearchTime = myTime / 30;
461 AbsoluteMaxSearchTime = myTime / 8;
464 else // (x moves) / (y minutes)
468 MaxSearchTime = myTime / 2;
469 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
471 MaxSearchTime = myTime / Min(movesToGo, 20);
472 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
476 if (PonderingEnabled)
478 MaxSearchTime += MaxSearchTime / 4;
479 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
482 // Fixed depth or fixed number of nodes?
485 InfiniteSearch = true; // HACK
490 NodesBetweenPolls = Min(MaxNodes, 30000);
491 InfiniteSearch = true; // HACK
494 NodesBetweenPolls = 30000;
497 // Write information to search log file:
499 LogFile << "Searching: " << pos.to_fen() << std::endl
500 << "infinite: " << infinite
501 << " ponder: " << ponder
502 << " time: " << myTime
503 << " increment: " << myIncrement
504 << " moves to go: " << movesToGo << std::endl;
507 // We're ready to start thinking. Call the iterative deepening loop
511 Value v = id_loop(pos, searchMoves);
512 looseOnTime = ( UseLSNFiltering
519 looseOnTime = false; // reset for next match
520 while (SearchStartTime + myTime + 1000 > get_system_time())
522 id_loop(pos, searchMoves); // to fail gracefully
539 /// init_threads() is called during startup. It launches all helper threads,
540 /// and initializes the split point stack and the global locks and condition
543 void init_threads() {
547 #if !defined(_MSC_VER)
548 pthread_t pthread[1];
551 for (i = 0; i < THREAD_MAX; i++)
552 Threads[i].activeSplitPoints = 0;
554 // Initialize global locks:
555 lock_init(&MPLock, NULL);
556 lock_init(&IOLock, NULL);
558 init_split_point_stack();
560 #if !defined(_MSC_VER)
561 pthread_mutex_init(&WaitLock, NULL);
562 pthread_cond_init(&WaitCond, NULL);
564 for (i = 0; i < THREAD_MAX; i++)
565 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
568 // All threads except the main thread should be initialized to idle state
569 for (i = 1; i < THREAD_MAX; i++)
571 Threads[i].stop = false;
572 Threads[i].workIsWaiting = false;
573 Threads[i].idle = true;
574 Threads[i].running = false;
577 // Launch the helper threads
578 for(i = 1; i < THREAD_MAX; i++)
580 #if !defined(_MSC_VER)
581 pthread_create(pthread, NULL, init_thread, (void*)(&i));
584 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
587 // Wait until the thread has finished launching:
588 while (!Threads[i].running);
591 // Init also the empty search stack
592 init_search_stack(EmptySearchStack);
596 /// stop_threads() is called when the program exits. It makes all the
597 /// helper threads exit cleanly.
599 void stop_threads() {
601 ActiveThreads = THREAD_MAX; // HACK
602 Idle = false; // HACK
603 wake_sleeping_threads();
604 AllThreadsShouldExit = true;
605 for (int i = 1; i < THREAD_MAX; i++)
607 Threads[i].stop = true;
608 while(Threads[i].running);
610 destroy_split_point_stack();
614 /// nodes_searched() returns the total number of nodes searched so far in
615 /// the current search.
617 int64_t nodes_searched() {
619 int64_t result = 0ULL;
620 for (int i = 0; i < ActiveThreads; i++)
621 result += Threads[i].nodes;
628 // id_loop() is the main iterative deepening loop. It calls root_search
629 // repeatedly with increasing depth until the allocated thinking time has
630 // been consumed, the user stops the search, or the maximum search depth is
633 Value id_loop(const Position &pos, Move searchMoves[]) {
636 SearchStack ss[PLY_MAX_PLUS_2];
638 // searchMoves are verified, copied, scored and sorted
639 RootMoveList rml(p, searchMoves);
644 init_search_stack(ss);
646 ValueByIteration[0] = Value(0);
647 ValueByIteration[1] = rml.get_move_score(0);
649 LastIterations = false;
651 EasyMove = rml.scan_for_easy_move();
653 // Iterative deepening loop
654 while (!AbortSearch && Iteration < PLY_MAX)
656 // Initialize iteration
659 BestMoveChangesByIteration[Iteration] = 0;
663 std::cout << "info depth " << Iteration << std::endl;
665 // Search to the current depth
666 ValueByIteration[Iteration] = root_search(p, ss, rml);
668 // Erase the easy move if it differs from the new best move
669 if (ss[0].pv[0] != EasyMove)
670 EasyMove = MOVE_NONE;
677 bool stopSearch = false;
679 // Stop search early if there is only a single legal move:
680 if (Iteration >= 6 && rml.move_count() == 1)
683 // Stop search early when the last two iterations returned a mate score
685 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
686 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
689 // Stop search early if one move seems to be much better than the rest
690 int64_t nodes = nodes_searched();
692 && EasyMove == ss[0].pv[0]
693 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
694 && current_search_time() > MaxSearchTime / 16)
695 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
696 && current_search_time() > MaxSearchTime / 32)))
699 // Add some extra time if the best move has changed during the last two iterations
700 if (Iteration > 5 && Iteration <= 50)
701 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
702 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
704 // Try to guess if the current iteration is the last one or the last two
705 LastIterations = (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*58) / 128);
707 // Stop search if most of MaxSearchTime is consumed at the end of the
708 // iteration. We probably don't have enough time to search the first
709 // move at the next iteration anyway.
710 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
718 StopOnPonderhit = true;
721 // Write PV to transposition table, in case the relevant entries have
722 // been overwritten during the search:
723 TT.insert_pv(p, ss[0].pv);
725 if (MaxDepth && Iteration >= MaxDepth)
731 // If we are pondering, we shouldn't print the best move before we
734 wait_for_stop_or_ponderhit();
736 // Print final search statistics
737 std::cout << "info nodes " << nodes_searched()
739 << " time " << current_search_time()
740 << " hashfull " << TT.full() << std::endl;
742 // Print the best move and the ponder move to the standard output
743 std::cout << "bestmove " << ss[0].pv[0];
744 if (ss[0].pv[1] != MOVE_NONE)
745 std::cout << " ponder " << ss[0].pv[1];
747 std::cout << std::endl;
752 dbg_print_mean(LogFile);
754 if (dbg_show_hit_rate)
755 dbg_print_hit_rate(LogFile);
758 LogFile << "Nodes: " << nodes_searched() << std::endl
759 << "Nodes/second: " << nps() << std::endl
760 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
762 p.do_move(ss[0].pv[0], u);
763 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
764 << std::endl << std::endl;
766 return rml.get_move_score(0);
770 // root_search() is the function which searches the root node. It is
771 // similar to search_pv except that it uses a different move ordering
772 // scheme (perhaps we should try to use this at internal PV nodes, too?)
773 // and prints some information to the standard output.
775 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
777 Value alpha = -VALUE_INFINITE;
778 Value beta = VALUE_INFINITE, value;
779 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
781 // Loop through all the moves in the root move list
782 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
789 RootMoveNumber = i + 1;
792 // Remember the node count before the move is searched. The node counts
793 // are used to sort the root moves at the next iteration.
794 nodes = nodes_searched();
796 // Reset beta cut-off counters
799 // Pick the next root move, and print the move and the move number to
800 // the standard output.
801 move = ss[0].currentMove = rml.get_move(i);
802 if (current_search_time() >= 1000)
803 std::cout << "info currmove " << move
804 << " currmovenumber " << i + 1 << std::endl;
806 // Decide search depth for this move
808 ext = extension(pos, move, true, pos.move_is_check(move), false, false, &dangerous);
809 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
811 // Make the move, and search it
812 pos.do_move(move, u, dcCandidates);
816 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
817 // If the value has dropped a lot compared to the last iteration,
818 // set the boolean variable Problem to true. This variable is used
819 // for time managment: When Problem is true, we try to complete the
820 // current iteration before playing a move.
821 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
823 if (Problem && StopOnPonderhit)
824 StopOnPonderhit = false;
828 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
831 // Fail high! Set the boolean variable FailHigh to true, and
832 // re-search the move with a big window. The variable FailHigh is
833 // used for time managment: We try to avoid aborting the search
834 // prematurely during a fail high research.
836 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
840 pos.undo_move(move, u);
842 // Finished searching the move. If AbortSearch is true, the search
843 // was aborted because the user interrupted the search or because we
844 // ran out of time. In this case, the return value of the search cannot
845 // be trusted, and we break out of the loop without updating the best
850 // Remember the node count for this move. The node counts are used to
851 // sort the root moves at the next iteration.
852 rml.set_move_nodes(i, nodes_searched() - nodes);
854 // Remember the beta-cutoff statistics
856 BetaCounter.read(pos.side_to_move(), our, their);
857 rml.set_beta_counters(i, our, their);
859 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
861 if (value <= alpha && i >= MultiPV)
862 rml.set_move_score(i, -VALUE_INFINITE);
868 rml.set_move_score(i, value);
870 rml.set_move_pv(i, ss[0].pv);
874 // We record how often the best move has been changed in each
875 // iteration. This information is used for time managment: When
876 // the best move changes frequently, we allocate some more time.
878 BestMoveChangesByIteration[Iteration]++;
880 // Print search information to the standard output:
881 std::cout << "info depth " << Iteration
882 << " score " << value_to_string(value)
883 << " time " << current_search_time()
884 << " nodes " << nodes_searched()
888 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
889 std::cout << ss[0].pv[j] << " ";
891 std::cout << std::endl;
894 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
899 // Reset the global variable Problem to false if the value isn't too
900 // far below the final value from the last iteration.
901 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
907 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
910 std::cout << "info multipv " << j + 1
911 << " score " << value_to_string(rml.get_move_score(j))
912 << " depth " << ((j <= i)? Iteration : Iteration - 1)
913 << " time " << current_search_time()
914 << " nodes " << nodes_searched()
918 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
919 std::cout << rml.get_move_pv(j, k) << " ";
921 std::cout << std::endl;
923 alpha = rml.get_move_score(Min(i, MultiPV-1));
931 // search_pv() is the main search function for PV nodes.
933 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
934 Depth depth, int ply, int threadID) {
936 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
937 assert(beta > alpha && beta <= VALUE_INFINITE);
938 assert(ply >= 0 && ply < PLY_MAX);
939 assert(threadID >= 0 && threadID < ActiveThreads);
942 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
944 // Initialize, and make an early exit in case of an aborted search,
945 // an instant draw, maximum ply reached, etc.
946 init_node(pos, ss, ply, threadID);
948 // After init_node() that calls poll()
949 if (AbortSearch || thread_should_stop(threadID))
957 if (ply >= PLY_MAX - 1)
958 return evaluate(pos, ei, threadID);
960 // Mate distance pruning
961 Value oldAlpha = alpha;
962 alpha = Max(value_mated_in(ply), alpha);
963 beta = Min(value_mate_in(ply+1), beta);
967 // Transposition table lookup. At PV nodes, we don't use the TT for
968 // pruning, but only for move ordering.
969 const TTEntry* tte = TT.retrieve(pos);
970 Move ttMove = (tte ? tte->move() : MOVE_NONE);
972 // Go with internal iterative deepening if we don't have a TT move
973 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
975 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
976 ttMove = ss[ply].pv[ply];
979 // Initialize a MovePicker object for the current position, and prepare
980 // to search all moves
981 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
983 Move move, movesSearched[256];
985 Value value, bestValue = -VALUE_INFINITE;
986 Bitboard dcCandidates = mp.discovered_check_candidates();
987 bool isCheck = pos.is_check();
988 bool mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move()));
990 // Loop through all legal moves until no moves remain or a beta cutoff
993 && (move = mp.get_next_move()) != MOVE_NONE
994 && !thread_should_stop(threadID))
996 assert(move_is_ok(move));
998 bool singleReply = (isCheck && mp.number_of_moves() == 1);
999 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1000 bool moveIsCapture = pos.move_is_capture(move);
1002 movesSearched[moveCount++] = ss[ply].currentMove = move;
1005 ss[ply].currentMoveCaptureValue =
1006 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1008 ss[ply].currentMoveCaptureValue = Value(0);
1010 // Decide the new search depth
1012 Depth ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat, &dangerous);
1013 Depth newDepth = depth - OnePly + ext;
1015 // Make and search the move
1017 pos.do_move(move, u, dcCandidates);
1019 if (moveCount == 1) // The first move in list is the PV
1020 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1023 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1024 // if the move fails high will be re-searched at full depth.
1025 if ( depth >= 2*OnePly
1026 && moveCount >= LMRPVMoves
1029 && !move_promotion(move)
1030 && !move_is_castle(move)
1031 && !move_is_killer(move, ss[ply]))
1033 ss[ply].reduction = OnePly;
1034 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1037 value = alpha + 1; // Just to trigger next condition
1039 if (value > alpha) // Go with full depth non-pv search
1041 ss[ply].reduction = Depth(0);
1042 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1043 if (value > alpha && value < beta)
1045 // When the search fails high at ply 1 while searching the first
1046 // move at the root, set the flag failHighPly1. This is used for
1047 // time managment: We don't want to stop the search early in
1048 // such cases, because resolving the fail high at ply 1 could
1049 // result in a big drop in score at the root.
1050 if (ply == 1 && RootMoveNumber == 1)
1051 Threads[threadID].failHighPly1 = true;
1053 // A fail high occurred. Re-search at full window (pv search)
1054 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1055 Threads[threadID].failHighPly1 = false;
1059 pos.undo_move(move, u);
1061 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1064 if (value > bestValue)
1071 if (value == value_mate_in(ply + 1))
1072 ss[ply].mateKiller = move;
1074 // If we are at ply 1, and we are searching the first root move at
1075 // ply 0, set the 'Problem' variable if the score has dropped a lot
1076 // (from the computer's point of view) since the previous iteration:
1079 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1084 if ( ActiveThreads > 1
1086 && depth >= MinimumSplitDepth
1088 && idle_thread_exists(threadID)
1090 && !thread_should_stop(threadID)
1091 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1092 &moveCount, &mp, dcCandidates, threadID, true))
1096 // All legal moves have been searched. A special case: If there were
1097 // no legal moves, it must be mate or stalemate:
1099 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1101 // If the search is not aborted, update the transposition table,
1102 // history counters, and killer moves.
1103 if (AbortSearch || thread_should_stop(threadID))
1106 if (bestValue <= oldAlpha)
1107 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1109 else if (bestValue >= beta)
1111 BetaCounter.add(pos.side_to_move(), depth, threadID);
1112 Move m = ss[ply].pv[ply];
1113 if (ok_to_history(pos, m)) // Only non capture moves are considered
1115 update_history(pos, m, depth, movesSearched, moveCount);
1116 update_killers(m, ss[ply]);
1118 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1121 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1127 // search() is the search function for zero-width nodes.
1129 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1130 int ply, bool allowNullmove, int threadID) {
1132 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1133 assert(ply >= 0 && ply < PLY_MAX);
1134 assert(threadID >= 0 && threadID < ActiveThreads);
1137 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1139 // Initialize, and make an early exit in case of an aborted search,
1140 // an instant draw, maximum ply reached, etc.
1141 init_node(pos, ss, ply, threadID);
1143 // After init_node() that calls poll()
1144 if (AbortSearch || thread_should_stop(threadID))
1152 if (ply >= PLY_MAX - 1)
1153 return evaluate(pos, ei, threadID);
1155 // Mate distance pruning
1156 if (value_mated_in(ply) >= beta)
1159 if (value_mate_in(ply + 1) < beta)
1162 // Transposition table lookup
1163 const TTEntry* tte = TT.retrieve(pos);
1164 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1166 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1168 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1169 return value_from_tt(tte->value(), ply);
1172 Value approximateEval = quick_evaluate(pos);
1173 bool mateThreat = false;
1174 bool nullDrivenIID = false;
1175 bool isCheck = pos.is_check();
1181 && !value_is_mate(beta)
1182 && ok_to_do_nullmove(pos)
1183 && approximateEval >= beta - NullMoveMargin)
1185 ss[ply].currentMove = MOVE_NULL;
1188 pos.do_null_move(u);
1189 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1191 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1193 // Check for a null capture artifact, if the value without the null capture
1194 // is above beta then mark the node as a suspicious failed low. We will verify
1195 // later if we are really under threat.
1196 if ( UseNullDrivenIID
1198 && depth > 6 * OnePly
1199 &&!value_is_mate(nullValue)
1200 && ttMove == MOVE_NONE
1201 && ss[ply + 1].currentMove != MOVE_NONE
1202 && pos.move_is_capture(ss[ply + 1].currentMove)
1203 && pos.see(ss[ply + 1].currentMove) + nullValue >= beta)
1204 nullDrivenIID = true;
1206 pos.undo_null_move(u);
1208 if (value_is_mate(nullValue))
1210 /* Do not return unproven mates */
1212 else if (nullValue >= beta)
1214 if (depth < 6 * OnePly)
1217 // Do zugzwang verification search
1218 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1222 // The null move failed low, which means that we may be faced with
1223 // some kind of threat. If the previous move was reduced, check if
1224 // the move that refuted the null move was somehow connected to the
1225 // move which was reduced. If a connection is found, return a fail
1226 // low score (which will cause the reduced move to fail high in the
1227 // parent node, which will trigger a re-search with full depth).
1228 if (nullValue == value_mated_in(ply + 2))
1231 nullDrivenIID = false;
1233 ss[ply].threatMove = ss[ply + 1].currentMove;
1234 if ( depth < ThreatDepth
1235 && ss[ply - 1].reduction
1236 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1240 // Null move search not allowed, try razoring
1241 else if ( !value_is_mate(beta)
1242 && approximateEval < beta - RazorMargin
1243 && depth < RazorDepth
1245 && ttMove == MOVE_NONE
1246 && !pos.has_pawn_on_7th(pos.side_to_move()))
1248 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1249 if (v < beta - RazorMargin / 2 - int(depth - OnePly) * RazorMargin / 8)
1253 // Go with internal iterative deepening if we don't have a TT move
1254 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1255 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1257 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1258 ttMove = ss[ply].pv[ply];
1260 else if (nullDrivenIID)
1262 // The null move failed low due to a suspicious capture. Perhaps we
1263 // are facing a null capture artifact due to the side to move change
1264 // and this position should fail high. So do a normal search with a
1265 // reduced depth to get a good ttMove to use in the following full
1267 Move tm = ss[ply].threatMove;
1269 assert(tm != MOVE_NONE);
1270 assert(ttMove == MOVE_NONE);
1272 search(pos, ss, beta, depth/2, ply, false, threadID);
1273 ttMove = ss[ply].pv[ply];
1274 ss[ply].threatMove = tm;
1277 // Initialize a MovePicker object for the current position, and prepare
1278 // to search all moves:
1279 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1281 Move move, movesSearched[256];
1283 Value value, bestValue = -VALUE_INFINITE;
1284 Bitboard dcCandidates = mp.discovered_check_candidates();
1285 Value futilityValue = VALUE_NONE;
1286 bool useFutilityPruning = UseFutilityPruning
1287 && depth < SelectiveDepth
1290 // Loop through all legal moves until no moves remain or a beta cutoff
1292 while ( bestValue < beta
1293 && (move = mp.get_next_move()) != MOVE_NONE
1294 && !thread_should_stop(threadID))
1296 assert(move_is_ok(move));
1298 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1299 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1300 bool moveIsCapture = pos.move_is_capture(move);
1302 movesSearched[moveCount++] = ss[ply].currentMove = move;
1304 // Decide the new search depth
1306 Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat, &dangerous);
1307 Depth newDepth = depth - OnePly + ext;
1310 if ( useFutilityPruning
1313 && !move_promotion(move))
1315 // History pruning. See ok_to_prune() definition
1316 if ( moveCount >= 2 + int(depth)
1317 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1320 // Value based pruning
1321 if (depth < 7 * OnePly && approximateEval < beta)
1323 if (futilityValue == VALUE_NONE)
1324 futilityValue = evaluate(pos, ei, threadID)
1325 + FutilityMargins[int(depth)/2 - 1]
1328 if (futilityValue < beta)
1330 if (futilityValue > bestValue)
1331 bestValue = futilityValue;
1337 // Make and search the move
1339 pos.do_move(move, u, dcCandidates);
1341 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1342 // if the move fails high will be re-searched at full depth.
1343 if ( depth >= 2*OnePly
1344 && moveCount >= LMRNonPVMoves
1347 && !move_promotion(move)
1348 && !move_is_castle(move)
1349 && !move_is_killer(move, ss[ply]))
1351 ss[ply].reduction = OnePly;
1352 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1355 value = beta; // Just to trigger next condition
1357 if (value >= beta) // Go with full depth non-pv search
1359 ss[ply].reduction = Depth(0);
1360 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1362 pos.undo_move(move, u);
1364 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1367 if (value > bestValue)
1373 if (value == value_mate_in(ply + 1))
1374 ss[ply].mateKiller = move;
1378 if ( ActiveThreads > 1
1380 && depth >= MinimumSplitDepth
1382 && idle_thread_exists(threadID)
1384 && !thread_should_stop(threadID)
1385 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1386 &mp, dcCandidates, threadID, false))
1390 // All legal moves have been searched. A special case: If there were
1391 // no legal moves, it must be mate or stalemate.
1393 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1395 // If the search is not aborted, update the transposition table,
1396 // history counters, and killer moves.
1397 if (AbortSearch || thread_should_stop(threadID))
1400 if (bestValue < beta)
1401 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1404 BetaCounter.add(pos.side_to_move(), depth, threadID);
1405 Move m = ss[ply].pv[ply];
1406 if (ok_to_history(pos, m)) // Only non capture moves are considered
1408 update_history(pos, m, depth, movesSearched, moveCount);
1409 update_killers(m, ss[ply]);
1411 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1417 // qsearch() is the quiescence search function, which is called by the main
1418 // search function when the remaining depth is zero (or, to be more precise,
1419 // less than OnePly).
1421 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1422 Depth depth, int ply, int threadID) {
1424 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1425 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1427 assert(ply >= 0 && ply < PLY_MAX);
1428 assert(threadID >= 0 && threadID < ActiveThreads);
1430 // Initialize, and make an early exit in case of an aborted search,
1431 // an instant draw, maximum ply reached, etc.
1432 init_node(pos, ss, ply, threadID);
1434 // After init_node() that calls poll()
1435 if (AbortSearch || thread_should_stop(threadID))
1441 // Transposition table lookup
1442 const TTEntry* tte = TT.retrieve(pos);
1443 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1444 return value_from_tt(tte->value(), ply);
1446 // Evaluate the position statically
1448 bool isCheck = pos.is_check();
1449 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1451 if (ply == PLY_MAX - 1)
1452 return evaluate(pos, ei, threadID);
1454 // Initialize "stand pat score", and return it immediately if it is
1456 Value bestValue = staticValue;
1458 if (bestValue >= beta)
1461 if (bestValue > alpha)
1464 // Initialize a MovePicker object for the current position, and prepare
1465 // to search the moves. Because the depth is <= 0 here, only captures,
1466 // queen promotions and checks (only if depth == 0) will be generated.
1467 bool pvNode = (beta - alpha != 1);
1468 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1471 Bitboard dcCandidates = mp.discovered_check_candidates();
1472 bool enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1474 // Loop through the moves until no moves remain or a beta cutoff
1476 while ( alpha < beta
1477 && (move = mp.get_next_move()) != MOVE_NONE)
1479 assert(move_is_ok(move));
1482 ss[ply].currentMove = move;
1485 if ( UseQSearchFutilityPruning
1489 && !move_promotion(move)
1490 && !pos.move_is_check(move, dcCandidates)
1491 && !pos.move_is_passed_pawn_push(move))
1493 Value futilityValue = staticValue
1494 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1495 pos.endgame_value_of_piece_on(move_to(move)))
1496 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1498 + ei.futilityMargin;
1500 if (futilityValue < alpha)
1502 if (futilityValue > bestValue)
1503 bestValue = futilityValue;
1508 // Don't search captures and checks with negative SEE values
1510 && !move_promotion(move)
1511 && (pos.midgame_value_of_piece_on(move_from(move)) >
1512 pos.midgame_value_of_piece_on(move_to(move)))
1513 && pos.see(move) < 0)
1516 // Make and search the move.
1518 pos.do_move(move, u, dcCandidates);
1519 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1520 pos.undo_move(move, u);
1522 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1525 if (value > bestValue)
1536 // All legal moves have been searched. A special case: If we're in check
1537 // and no legal moves were found, it is checkmate:
1538 if (pos.is_check() && moveCount == 0) // Mate!
1539 return value_mated_in(ply);
1541 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1543 // Update transposition table
1544 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1546 // Update killers only for good check moves
1547 Move m = ss[ply].currentMove;
1548 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1550 // Wrong to update history when depth is <= 0
1551 update_killers(m, ss[ply]);
1557 // sp_search() is used to search from a split point. This function is called
1558 // by each thread working at the split point. It is similar to the normal
1559 // search() function, but simpler. Because we have already probed the hash
1560 // table, done a null move search, and searched the first move before
1561 // splitting, we don't have to repeat all this work in sp_search(). We
1562 // also don't need to store anything to the hash table here: This is taken
1563 // care of after we return from the split point.
1565 void sp_search(SplitPoint *sp, int threadID) {
1567 assert(threadID >= 0 && threadID < ActiveThreads);
1568 assert(ActiveThreads > 1);
1570 Position pos = Position(sp->pos);
1571 SearchStack *ss = sp->sstack[threadID];
1574 bool isCheck = pos.is_check();
1575 bool useFutilityPruning = UseFutilityPruning
1576 && sp->depth < SelectiveDepth
1579 while ( sp->bestValue < sp->beta
1580 && !thread_should_stop(threadID)
1581 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1583 assert(move_is_ok(move));
1585 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1586 bool moveIsCapture = pos.move_is_capture(move);
1588 lock_grab(&(sp->lock));
1589 int moveCount = ++sp->moves;
1590 lock_release(&(sp->lock));
1592 ss[sp->ply].currentMove = move;
1594 // Decide the new search depth.
1596 Depth ext = extension(pos, move, false, moveIsCheck, false, false, &dangerous);
1597 Depth newDepth = sp->depth - OnePly + ext;
1600 if ( useFutilityPruning
1603 && !move_promotion(move)
1604 && moveCount >= 2 + int(sp->depth)
1605 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1608 // Make and search the move.
1610 pos.do_move(move, u, sp->dcCandidates);
1612 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1613 // if the move fails high will be re-searched at full depth.
1615 && moveCount >= LMRNonPVMoves
1617 && !move_promotion(move)
1618 && !move_is_castle(move)
1619 && !move_is_killer(move, ss[sp->ply]))
1621 ss[sp->ply].reduction = OnePly;
1622 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1625 value = sp->beta; // Just to trigger next condition
1627 if (value >= sp->beta) // Go with full depth non-pv search
1629 ss[sp->ply].reduction = Depth(0);
1630 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1632 pos.undo_move(move, u);
1634 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1636 if (thread_should_stop(threadID))
1640 lock_grab(&(sp->lock));
1641 if (value > sp->bestValue && !thread_should_stop(threadID))
1643 sp->bestValue = value;
1644 if (sp->bestValue >= sp->beta)
1646 sp_update_pv(sp->parentSstack, ss, sp->ply);
1647 for (int i = 0; i < ActiveThreads; i++)
1648 if (i != threadID && (i == sp->master || sp->slaves[i]))
1649 Threads[i].stop = true;
1651 sp->finished = true;
1654 lock_release(&(sp->lock));
1657 lock_grab(&(sp->lock));
1659 // If this is the master thread and we have been asked to stop because of
1660 // a beta cutoff higher up in the tree, stop all slave threads:
1661 if (sp->master == threadID && thread_should_stop(threadID))
1662 for (int i = 0; i < ActiveThreads; i++)
1664 Threads[i].stop = true;
1667 sp->slaves[threadID] = 0;
1669 lock_release(&(sp->lock));
1673 // sp_search_pv() is used to search from a PV split point. This function
1674 // is called by each thread working at the split point. It is similar to
1675 // the normal search_pv() function, but simpler. Because we have already
1676 // probed the hash table and searched the first move before splitting, we
1677 // don't have to repeat all this work in sp_search_pv(). We also don't
1678 // need to store anything to the hash table here: This is taken care of
1679 // after we return from the split point.
1681 void sp_search_pv(SplitPoint *sp, int threadID) {
1683 assert(threadID >= 0 && threadID < ActiveThreads);
1684 assert(ActiveThreads > 1);
1686 Position pos = Position(sp->pos);
1687 SearchStack *ss = sp->sstack[threadID];
1691 while ( sp->alpha < sp->beta
1692 && !thread_should_stop(threadID)
1693 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1695 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1696 bool moveIsCapture = pos.move_is_capture(move);
1698 assert(move_is_ok(move));
1701 ss[sp->ply].currentMoveCaptureValue =
1702 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1704 ss[sp->ply].currentMoveCaptureValue = Value(0);
1706 lock_grab(&(sp->lock));
1707 int moveCount = ++sp->moves;
1708 lock_release(&(sp->lock));
1710 ss[sp->ply].currentMove = move;
1712 // Decide the new search depth.
1714 Depth ext = extension(pos, move, true, moveIsCheck, false, false, &dangerous);
1715 Depth newDepth = sp->depth - OnePly + ext;
1717 // Make and search the move.
1719 pos.do_move(move, u, sp->dcCandidates);
1721 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1722 // if the move fails high will be re-searched at full depth.
1724 && moveCount >= LMRPVMoves
1726 && !move_promotion(move)
1727 && !move_is_castle(move)
1728 && !move_is_killer(move, ss[sp->ply]))
1730 ss[sp->ply].reduction = OnePly;
1731 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1734 value = sp->alpha + 1; // Just to trigger next condition
1736 if (value > sp->alpha) // Go with full depth non-pv search
1738 ss[sp->ply].reduction = Depth(0);
1739 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1741 if (value > sp->alpha && value < sp->beta)
1743 // When the search fails high at ply 1 while searching the first
1744 // move at the root, set the flag failHighPly1. This is used for
1745 // time managment: We don't want to stop the search early in
1746 // such cases, because resolving the fail high at ply 1 could
1747 // result in a big drop in score at the root.
1748 if (sp->ply == 1 && RootMoveNumber == 1)
1749 Threads[threadID].failHighPly1 = true;
1751 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1752 Threads[threadID].failHighPly1 = false;
1755 pos.undo_move(move, u);
1757 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1759 if (thread_should_stop(threadID))
1763 lock_grab(&(sp->lock));
1764 if (value > sp->bestValue && !thread_should_stop(threadID))
1766 sp->bestValue = value;
1767 if (value > sp->alpha)
1770 sp_update_pv(sp->parentSstack, ss, sp->ply);
1771 if (value == value_mate_in(sp->ply + 1))
1772 ss[sp->ply].mateKiller = move;
1774 if(value >= sp->beta)
1776 for(int i = 0; i < ActiveThreads; i++)
1777 if(i != threadID && (i == sp->master || sp->slaves[i]))
1778 Threads[i].stop = true;
1780 sp->finished = true;
1783 // If we are at ply 1, and we are searching the first root move at
1784 // ply 0, set the 'Problem' variable if the score has dropped a lot
1785 // (from the computer's point of view) since the previous iteration.
1788 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1791 lock_release(&(sp->lock));
1794 lock_grab(&(sp->lock));
1796 // If this is the master thread and we have been asked to stop because of
1797 // a beta cutoff higher up in the tree, stop all slave threads.
1798 if (sp->master == threadID && thread_should_stop(threadID))
1799 for (int i = 0; i < ActiveThreads; i++)
1801 Threads[i].stop = true;
1804 sp->slaves[threadID] = 0;
1806 lock_release(&(sp->lock));
1809 /// The BetaCounterType class
1811 BetaCounterType::BetaCounterType() { clear(); }
1813 void BetaCounterType::clear() {
1815 for (int i = 0; i < THREAD_MAX; i++)
1816 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1819 void BetaCounterType::add(Color us, Depth d, int threadID) {
1821 // Weighted count based on depth
1822 hits[threadID][us] += int(d);
1825 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1828 for (int i = 0; i < THREAD_MAX; i++)
1831 their += hits[i][opposite_color(us)];
1836 /// The RootMove class
1840 RootMove::RootMove() {
1841 nodes = cumulativeNodes = 0ULL;
1844 // RootMove::operator<() is the comparison function used when
1845 // sorting the moves. A move m1 is considered to be better
1846 // than a move m2 if it has a higher score, or if the moves
1847 // have equal score but m1 has the higher node count.
1849 bool RootMove::operator<(const RootMove& m) {
1851 if (score != m.score)
1852 return (score < m.score);
1854 return theirBeta <= m.theirBeta;
1857 /// The RootMoveList class
1861 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1863 MoveStack mlist[MaxRootMoves];
1864 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1866 // Generate all legal moves
1867 int lm_count = generate_legal_moves(pos, mlist);
1869 // Add each move to the moves[] array
1870 for (int i = 0; i < lm_count; i++)
1872 bool includeMove = includeAllMoves;
1874 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1875 includeMove = (searchMoves[k] == mlist[i].move);
1879 // Find a quick score for the move
1881 SearchStack ss[PLY_MAX_PLUS_2];
1883 moves[count].move = mlist[i].move;
1884 moves[count].nodes = 0ULL;
1885 pos.do_move(moves[count].move, u);
1886 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1888 pos.undo_move(moves[count].move, u);
1889 moves[count].pv[0] = moves[i].move;
1890 moves[count].pv[1] = MOVE_NONE; // FIXME
1898 // Simple accessor methods for the RootMoveList class
1900 inline Move RootMoveList::get_move(int moveNum) const {
1901 return moves[moveNum].move;
1904 inline Value RootMoveList::get_move_score(int moveNum) const {
1905 return moves[moveNum].score;
1908 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1909 moves[moveNum].score = score;
1912 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1913 moves[moveNum].nodes = nodes;
1914 moves[moveNum].cumulativeNodes += nodes;
1917 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1918 moves[moveNum].ourBeta = our;
1919 moves[moveNum].theirBeta = their;
1922 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1924 for(j = 0; pv[j] != MOVE_NONE; j++)
1925 moves[moveNum].pv[j] = pv[j];
1926 moves[moveNum].pv[j] = MOVE_NONE;
1929 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1930 return moves[moveNum].pv[i];
1933 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1934 return moves[moveNum].cumulativeNodes;
1937 inline int RootMoveList::move_count() const {
1942 // RootMoveList::scan_for_easy_move() is called at the end of the first
1943 // iteration, and is used to detect an "easy move", i.e. a move which appears
1944 // to be much bester than all the rest. If an easy move is found, the move
1945 // is returned, otherwise the function returns MOVE_NONE. It is very
1946 // important that this function is called at the right moment: The code
1947 // assumes that the first iteration has been completed and the moves have
1948 // been sorted. This is done in RootMoveList c'tor.
1950 Move RootMoveList::scan_for_easy_move() const {
1957 // moves are sorted so just consider the best and the second one
1958 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1964 // RootMoveList::sort() sorts the root move list at the beginning of a new
1967 inline void RootMoveList::sort() {
1969 sort_multipv(count - 1); // all items
1973 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1974 // list by their scores and depths. It is used to order the different PVs
1975 // correctly in MultiPV mode.
1977 void RootMoveList::sort_multipv(int n) {
1979 for (int i = 1; i <= n; i++)
1981 RootMove rm = moves[i];
1983 for (j = i; j > 0 && moves[j-1] < rm; j--)
1984 moves[j] = moves[j-1];
1990 // init_search_stack() initializes a search stack at the beginning of a
1991 // new search from the root.
1992 void init_search_stack(SearchStack& ss) {
1994 ss.pv[0] = MOVE_NONE;
1995 ss.pv[1] = MOVE_NONE;
1996 ss.currentMove = MOVE_NONE;
1997 ss.threatMove = MOVE_NONE;
1998 ss.reduction = Depth(0);
1999 for (int j = 0; j < KILLER_MAX; j++)
2000 ss.killers[j] = MOVE_NONE;
2003 void init_search_stack(SearchStack ss[]) {
2005 for (int i = 0; i < 3; i++)
2007 ss[i].pv[i] = MOVE_NONE;
2008 ss[i].pv[i+1] = MOVE_NONE;
2009 ss[i].currentMove = MOVE_NONE;
2010 ss[i].threatMove = MOVE_NONE;
2011 ss[i].reduction = Depth(0);
2012 for (int j = 0; j < KILLER_MAX; j++)
2013 ss[i].killers[j] = MOVE_NONE;
2018 // init_node() is called at the beginning of all the search functions
2019 // (search(), search_pv(), qsearch(), and so on) and initializes the search
2020 // stack object corresponding to the current node. Once every
2021 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
2022 // for user input and checks whether it is time to stop the search.
2024 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
2025 assert(ply >= 0 && ply < PLY_MAX);
2026 assert(threadID >= 0 && threadID < ActiveThreads);
2028 Threads[threadID].nodes++;
2032 if(NodesSincePoll >= NodesBetweenPolls) {
2037 ss[ply].pv[ply] = ss[ply].pv[ply+1] = ss[ply].currentMove = MOVE_NONE;
2038 ss[ply+2].mateKiller = MOVE_NONE;
2039 ss[ply].threatMove = MOVE_NONE;
2040 ss[ply].reduction = Depth(0);
2041 ss[ply].currentMoveCaptureValue = Value(0);
2042 for (int j = 0; j < KILLER_MAX; j++)
2043 ss[ply+2].killers[j] = MOVE_NONE;
2045 if(Threads[threadID].printCurrentLine)
2046 print_current_line(ss, ply, threadID);
2050 // update_pv() is called whenever a search returns a value > alpha. It
2051 // updates the PV in the SearchStack object corresponding to the current
2054 void update_pv(SearchStack ss[], int ply) {
2055 assert(ply >= 0 && ply < PLY_MAX);
2057 ss[ply].pv[ply] = ss[ply].currentMove;
2059 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2060 ss[ply].pv[p] = ss[ply+1].pv[p];
2061 ss[ply].pv[p] = MOVE_NONE;
2065 // sp_update_pv() is a variant of update_pv for use at split points. The
2066 // difference between the two functions is that sp_update_pv also updates
2067 // the PV at the parent node.
2069 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2070 assert(ply >= 0 && ply < PLY_MAX);
2072 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2074 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2075 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2076 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2080 // connected_moves() tests whether two moves are 'connected' in the sense
2081 // that the first move somehow made the second move possible (for instance
2082 // if the moving piece is the same in both moves). The first move is
2083 // assumed to be the move that was made to reach the current position, while
2084 // the second move is assumed to be a move from the current position.
2086 bool connected_moves(const Position &pos, Move m1, Move m2) {
2087 Square f1, t1, f2, t2;
2089 assert(move_is_ok(m1));
2090 assert(move_is_ok(m2));
2095 // Case 1: The moving piece is the same in both moves.
2101 // Case 2: The destination square for m2 was vacated by m1.
2107 // Case 3: Moving through the vacated square:
2108 if(piece_is_slider(pos.piece_on(f2)) &&
2109 bit_is_set(squares_between(f2, t2), f1))
2112 // Case 4: The destination square for m2 is attacked by the moving piece
2114 if(pos.piece_attacks_square(t1, t2))
2117 // Case 5: Discovered check, checking piece is the piece moved in m1:
2118 if(piece_is_slider(pos.piece_on(t1)) &&
2119 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2121 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2123 Bitboard occ = pos.occupied_squares();
2124 Color us = pos.side_to_move();
2125 Square ksq = pos.king_square(us);
2126 clear_bit(&occ, f2);
2127 if(pos.type_of_piece_on(t1) == BISHOP) {
2128 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2131 else if(pos.type_of_piece_on(t1) == ROOK) {
2132 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2136 assert(pos.type_of_piece_on(t1) == QUEEN);
2137 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2146 // value_is_mate() checks if the given value is a mate one
2147 // eventually compensated for the ply.
2149 bool value_is_mate(Value value) {
2151 assert(abs(value) <= VALUE_INFINITE);
2153 return value <= value_mated_in(PLY_MAX)
2154 || value >= value_mate_in(PLY_MAX);
2158 // move_is_killer() checks if the given move is among the
2159 // killer moves of that ply.
2161 bool move_is_killer(Move m, const SearchStack& ss) {
2163 const Move* k = ss.killers;
2164 for (int i = 0; i < KILLER_MAX; i++, k++)
2172 // extension() decides whether a move should be searched with normal depth,
2173 // or with extended depth. Certain classes of moves (checking moves, in
2174 // particular) are searched with bigger depth than ordinary moves and in
2175 // any case are marked as 'dangerous'. Note that also if a move is not
2176 // extended, as example because the corresponding UCI option is set to zero,
2177 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2179 Depth extension(const Position &pos, Move m, bool pvNode, bool check,
2180 bool singleReply, bool mateThreat, bool* dangerous) {
2182 assert(m != MOVE_NONE);
2184 Depth result = Depth(0);
2185 *dangerous = check || singleReply || mateThreat;
2188 result += CheckExtension[pvNode];
2191 result += SingleReplyExtension[pvNode];
2194 result += MateThreatExtension[pvNode];
2196 if (pos.move_is_pawn_push_to_7th(m))
2198 result += PawnPushTo7thExtension[pvNode];
2201 if (pos.move_is_passed_pawn_push(m))
2203 result += PassedPawnExtension[pvNode];
2207 if ( pos.move_is_capture(m)
2208 && pos.type_of_piece_on(move_to(m)) != PAWN
2209 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2210 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2211 && !move_promotion(m)
2214 result += PawnEndgameExtension[pvNode];
2219 && pos.move_is_capture(m)
2220 && pos.type_of_piece_on(move_to(m)) != PAWN
2227 return Min(result, OnePly);
2231 // ok_to_do_nullmove() looks at the current position and decides whether
2232 // doing a 'null move' should be allowed. In order to avoid zugzwang
2233 // problems, null moves are not allowed when the side to move has very
2234 // little material left. Currently, the test is a bit too simple: Null
2235 // moves are avoided only when the side to move has only pawns left. It's
2236 // probably a good idea to avoid null moves in at least some more
2237 // complicated endgames, e.g. KQ vs KR. FIXME
2239 bool ok_to_do_nullmove(const Position &pos) {
2240 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2246 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2247 // non-tactical moves late in the move list close to the leaves are
2248 // candidates for pruning.
2250 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2251 Square mfrom, mto, tfrom, tto;
2253 assert(move_is_ok(m));
2254 assert(threat == MOVE_NONE || move_is_ok(threat));
2255 assert(!move_promotion(m));
2256 assert(!pos.move_is_check(m));
2257 assert(!pos.move_is_capture(m));
2258 assert(!pos.move_is_passed_pawn_push(m));
2259 assert(d >= OnePly);
2261 mfrom = move_from(m);
2263 tfrom = move_from(threat);
2264 tto = move_to(threat);
2266 // Case 1: Castling moves are never pruned.
2267 if (move_is_castle(m))
2270 // Case 2: Don't prune moves which move the threatened piece
2271 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2274 // Case 3: If the threatened piece has value less than or equal to the
2275 // value of the threatening piece, don't prune move which defend it.
2276 if ( !PruneDefendingMoves
2277 && threat != MOVE_NONE
2278 && pos.move_is_capture(threat)
2279 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2280 || pos.type_of_piece_on(tfrom) == KING)
2281 && pos.move_attacks_square(m, tto))
2284 // Case 4: Don't prune moves with good history.
2285 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2288 // Case 5: If the moving piece in the threatened move is a slider, don't
2289 // prune safe moves which block its ray.
2290 if ( !PruneBlockingMoves
2291 && threat != MOVE_NONE
2292 && piece_is_slider(pos.piece_on(tfrom))
2293 && bit_is_set(squares_between(tfrom, tto), mto)
2301 // ok_to_use_TT() returns true if a transposition table score
2302 // can be used at a given point in search.
2304 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2306 Value v = value_from_tt(tte->value(), ply);
2308 return ( tte->depth() >= depth
2309 || v >= Max(value_mate_in(100), beta)
2310 || v < Min(value_mated_in(100), beta))
2312 && ( (is_lower_bound(tte->type()) && v >= beta)
2313 || (is_upper_bound(tte->type()) && v < beta));
2317 // ok_to_history() returns true if a move m can be stored
2318 // in history. Should be a non capturing move nor a promotion.
2320 bool ok_to_history(const Position& pos, Move m) {
2322 return !pos.move_is_capture(m) && !move_promotion(m);
2326 // update_history() registers a good move that produced a beta-cutoff
2327 // in history and marks as failures all the other moves of that ply.
2329 void update_history(const Position& pos, Move m, Depth depth,
2330 Move movesSearched[], int moveCount) {
2332 H.success(pos.piece_on(move_from(m)), m, depth);
2334 for (int i = 0; i < moveCount - 1; i++)
2336 assert(m != movesSearched[i]);
2337 if (ok_to_history(pos, movesSearched[i]))
2338 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2343 // update_killers() add a good move that produced a beta-cutoff
2344 // among the killer moves of that ply.
2346 void update_killers(Move m, SearchStack& ss) {
2348 if (m == ss.killers[0])
2351 for (int i = KILLER_MAX - 1; i > 0; i--)
2352 ss.killers[i] = ss.killers[i - 1];
2357 // fail_high_ply_1() checks if some thread is currently resolving a fail
2358 // high at ply 1 at the node below the first root node. This information
2359 // is used for time managment.
2361 bool fail_high_ply_1() {
2362 for(int i = 0; i < ActiveThreads; i++)
2363 if(Threads[i].failHighPly1)
2369 // current_search_time() returns the number of milliseconds which have passed
2370 // since the beginning of the current search.
2372 int current_search_time() {
2373 return get_system_time() - SearchStartTime;
2377 // nps() computes the current nodes/second count.
2380 int t = current_search_time();
2381 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2385 // poll() performs two different functions: It polls for user input, and it
2386 // looks at the time consumed so far and decides if it's time to abort the
2391 static int lastInfoTime;
2392 int t = current_search_time();
2397 // We are line oriented, don't read single chars
2398 std::string command;
2399 if (!std::getline(std::cin, command))
2402 if (command == "quit")
2405 PonderSearch = false;
2408 else if(command == "stop")
2411 PonderSearch = false;
2413 else if(command == "ponderhit")
2416 // Print search information
2420 else if (lastInfoTime > t)
2421 // HACK: Must be a new search where we searched less than
2422 // NodesBetweenPolls nodes during the first second of search.
2425 else if (t - lastInfoTime >= 1000)
2432 if (dbg_show_hit_rate)
2433 dbg_print_hit_rate();
2435 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2436 << " time " << t << " hashfull " << TT.full() << std::endl;
2437 lock_release(&IOLock);
2438 if (ShowCurrentLine)
2439 Threads[0].printCurrentLine = true;
2441 // Should we stop the search?
2445 bool overTime = t > AbsoluteMaxSearchTime
2446 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2447 || ( !FailHigh && !fail_high_ply_1() && !Problem
2448 && t > 6*(MaxSearchTime + ExtraSearchTime));
2450 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2451 || (ExactMaxTime && t >= ExactMaxTime)
2452 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2457 // ponderhit() is called when the program is pondering (i.e. thinking while
2458 // it's the opponent's turn to move) in order to let the engine know that
2459 // it correctly predicted the opponent's move.
2462 int t = current_search_time();
2463 PonderSearch = false;
2464 if(Iteration >= 2 &&
2465 (!InfiniteSearch && (StopOnPonderhit ||
2466 t > AbsoluteMaxSearchTime ||
2467 (RootMoveNumber == 1 &&
2468 t > MaxSearchTime + ExtraSearchTime) ||
2469 (!FailHigh && !fail_high_ply_1() && !Problem &&
2470 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2475 // print_current_line() prints the current line of search for a given
2476 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2478 void print_current_line(SearchStack ss[], int ply, int threadID) {
2479 assert(ply >= 0 && ply < PLY_MAX);
2480 assert(threadID >= 0 && threadID < ActiveThreads);
2482 if(!Threads[threadID].idle) {
2484 std::cout << "info currline " << (threadID + 1);
2485 for(int p = 0; p < ply; p++)
2486 std::cout << " " << ss[p].currentMove;
2487 std::cout << std::endl;
2488 lock_release(&IOLock);
2490 Threads[threadID].printCurrentLine = false;
2491 if(threadID + 1 < ActiveThreads)
2492 Threads[threadID + 1].printCurrentLine = true;
2496 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2497 // while the program is pondering. The point is to work around a wrinkle in
2498 // the UCI protocol: When pondering, the engine is not allowed to give a
2499 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2500 // We simply wait here until one of these commands is sent, and return,
2501 // after which the bestmove and pondermove will be printed (in id_loop()).
2503 void wait_for_stop_or_ponderhit() {
2504 std::string command;
2507 if(!std::getline(std::cin, command))
2510 if(command == "quit") {
2511 OpeningBook.close();
2516 else if(command == "ponderhit" || command == "stop")
2522 // idle_loop() is where the threads are parked when they have no work to do.
2523 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2524 // object for which the current thread is the master.
2526 void idle_loop(int threadID, SplitPoint *waitSp) {
2527 assert(threadID >= 0 && threadID < THREAD_MAX);
2529 Threads[threadID].running = true;
2532 if(AllThreadsShouldExit && threadID != 0)
2535 // If we are not thinking, wait for a condition to be signaled instead
2536 // of wasting CPU time polling for work:
2537 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2538 #if !defined(_MSC_VER)
2539 pthread_mutex_lock(&WaitLock);
2540 if(Idle || threadID >= ActiveThreads)
2541 pthread_cond_wait(&WaitCond, &WaitLock);
2542 pthread_mutex_unlock(&WaitLock);
2544 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2548 // If this thread has been assigned work, launch a search:
2549 if(Threads[threadID].workIsWaiting) {
2550 Threads[threadID].workIsWaiting = false;
2551 if(Threads[threadID].splitPoint->pvNode)
2552 sp_search_pv(Threads[threadID].splitPoint, threadID);
2554 sp_search(Threads[threadID].splitPoint, threadID);
2555 Threads[threadID].idle = true;
2558 // If this thread is the master of a split point and all threads have
2559 // finished their work at this split point, return from the idle loop:
2560 if(waitSp != NULL && waitSp->cpus == 0)
2564 Threads[threadID].running = false;
2568 // init_split_point_stack() is called during program initialization, and
2569 // initializes all split point objects.
2571 void init_split_point_stack() {
2572 for(int i = 0; i < THREAD_MAX; i++)
2573 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2574 SplitPointStack[i][j].parent = NULL;
2575 lock_init(&(SplitPointStack[i][j].lock), NULL);
2580 // destroy_split_point_stack() is called when the program exits, and
2581 // destroys all locks in the precomputed split point objects.
2583 void destroy_split_point_stack() {
2584 for(int i = 0; i < THREAD_MAX; i++)
2585 for(int j = 0; j < MaxActiveSplitPoints; j++)
2586 lock_destroy(&(SplitPointStack[i][j].lock));
2590 // thread_should_stop() checks whether the thread with a given threadID has
2591 // been asked to stop, directly or indirectly. This can happen if a beta
2592 // cutoff has occured in thre thread's currently active split point, or in
2593 // some ancestor of the current split point.
2595 bool thread_should_stop(int threadID) {
2596 assert(threadID >= 0 && threadID < ActiveThreads);
2600 if(Threads[threadID].stop)
2602 if(ActiveThreads <= 2)
2604 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2606 Threads[threadID].stop = true;
2613 // thread_is_available() checks whether the thread with threadID "slave" is
2614 // available to help the thread with threadID "master" at a split point. An
2615 // obvious requirement is that "slave" must be idle. With more than two
2616 // threads, this is not by itself sufficient: If "slave" is the master of
2617 // some active split point, it is only available as a slave to the other
2618 // threads which are busy searching the split point at the top of "slave"'s
2619 // split point stack (the "helpful master concept" in YBWC terminology).
2621 bool thread_is_available(int slave, int master) {
2622 assert(slave >= 0 && slave < ActiveThreads);
2623 assert(master >= 0 && master < ActiveThreads);
2624 assert(ActiveThreads > 1);
2626 if(!Threads[slave].idle || slave == master)
2629 if(Threads[slave].activeSplitPoints == 0)
2630 // No active split points means that the thread is available as a slave
2631 // for any other thread.
2634 if(ActiveThreads == 2)
2637 // Apply the "helpful master" concept if possible.
2638 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2645 // idle_thread_exists() tries to find an idle thread which is available as
2646 // a slave for the thread with threadID "master".
2648 bool idle_thread_exists(int master) {
2649 assert(master >= 0 && master < ActiveThreads);
2650 assert(ActiveThreads > 1);
2652 for(int i = 0; i < ActiveThreads; i++)
2653 if(thread_is_available(i, master))
2659 // split() does the actual work of distributing the work at a node between
2660 // several threads at PV nodes. If it does not succeed in splitting the
2661 // node (because no idle threads are available, or because we have no unused
2662 // split point objects), the function immediately returns false. If
2663 // splitting is possible, a SplitPoint object is initialized with all the
2664 // data that must be copied to the helper threads (the current position and
2665 // search stack, alpha, beta, the search depth, etc.), and we tell our
2666 // helper threads that they have been assigned work. This will cause them
2667 // to instantly leave their idle loops and call sp_search_pv(). When all
2668 // threads have returned from sp_search_pv (or, equivalently, when
2669 // splitPoint->cpus becomes 0), split() returns true.
2671 bool split(const Position &p, SearchStack *sstck, int ply,
2672 Value *alpha, Value *beta, Value *bestValue,
2673 Depth depth, int *moves,
2674 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2676 assert(sstck != NULL);
2677 assert(ply >= 0 && ply < PLY_MAX);
2678 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2679 assert(!pvNode || *alpha < *beta);
2680 assert(*beta <= VALUE_INFINITE);
2681 assert(depth > Depth(0));
2682 assert(master >= 0 && master < ActiveThreads);
2683 assert(ActiveThreads > 1);
2685 SplitPoint *splitPoint;
2690 // If no other thread is available to help us, or if we have too many
2691 // active split points, don't split:
2692 if(!idle_thread_exists(master) ||
2693 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2694 lock_release(&MPLock);
2698 // Pick the next available split point object from the split point stack:
2699 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2700 Threads[master].activeSplitPoints++;
2702 // Initialize the split point object:
2703 splitPoint->parent = Threads[master].splitPoint;
2704 splitPoint->finished = false;
2705 splitPoint->ply = ply;
2706 splitPoint->depth = depth;
2707 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2708 splitPoint->beta = *beta;
2709 splitPoint->pvNode = pvNode;
2710 splitPoint->dcCandidates = dcCandidates;
2711 splitPoint->bestValue = *bestValue;
2712 splitPoint->master = master;
2713 splitPoint->mp = mp;
2714 splitPoint->moves = *moves;
2715 splitPoint->cpus = 1;
2716 splitPoint->pos.copy(p);
2717 splitPoint->parentSstack = sstck;
2718 for(i = 0; i < ActiveThreads; i++)
2719 splitPoint->slaves[i] = 0;
2721 // Copy the current position and the search stack to the master thread:
2722 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2723 Threads[master].splitPoint = splitPoint;
2725 // Make copies of the current position and search stack for each thread:
2726 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2728 if(thread_is_available(i, master)) {
2729 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2730 Threads[i].splitPoint = splitPoint;
2731 splitPoint->slaves[i] = 1;
2735 // Tell the threads that they have work to do. This will make them leave
2737 for(i = 0; i < ActiveThreads; i++)
2738 if(i == master || splitPoint->slaves[i]) {
2739 Threads[i].workIsWaiting = true;
2740 Threads[i].idle = false;
2741 Threads[i].stop = false;
2744 lock_release(&MPLock);
2746 // Everything is set up. The master thread enters the idle loop, from
2747 // which it will instantly launch a search, because its workIsWaiting
2748 // slot is 'true'. We send the split point as a second parameter to the
2749 // idle loop, which means that the main thread will return from the idle
2750 // loop when all threads have finished their work at this split point
2751 // (i.e. when // splitPoint->cpus == 0).
2752 idle_loop(master, splitPoint);
2754 // We have returned from the idle loop, which means that all threads are
2755 // finished. Update alpha, beta and bestvalue, and return:
2757 if(pvNode) *alpha = splitPoint->alpha;
2758 *beta = splitPoint->beta;
2759 *bestValue = splitPoint->bestValue;
2760 Threads[master].stop = false;
2761 Threads[master].idle = false;
2762 Threads[master].activeSplitPoints--;
2763 Threads[master].splitPoint = splitPoint->parent;
2764 lock_release(&MPLock);
2770 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2771 // to start a new search from the root.
2773 void wake_sleeping_threads() {
2774 if(ActiveThreads > 1) {
2775 for(int i = 1; i < ActiveThreads; i++) {
2776 Threads[i].idle = true;
2777 Threads[i].workIsWaiting = false;
2779 #if !defined(_MSC_VER)
2780 pthread_mutex_lock(&WaitLock);
2781 pthread_cond_broadcast(&WaitCond);
2782 pthread_mutex_unlock(&WaitLock);
2784 for(int i = 1; i < THREAD_MAX; i++)
2785 SetEvent(SitIdleEvent[i]);
2791 // init_thread() is the function which is called when a new thread is
2792 // launched. It simply calls the idle_loop() function with the supplied
2793 // threadID. There are two versions of this function; one for POSIX threads
2794 // and one for Windows threads.
2796 #if !defined(_MSC_VER)
2798 void *init_thread(void *threadID) {
2799 idle_loop(*(int *)threadID, NULL);
2805 DWORD WINAPI init_thread(LPVOID threadID) {
2806 idle_loop(*(int *)threadID, NULL);