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 // Internal iterative deepening margin. At Non-PV moves, when
129 // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
130 // when the static evaluation is at most IIDMargin below beta.
131 const Value IIDMargin = Value(0x100);
133 // Easy move margin. An easy move candidate must be at least this much
134 // better than the second best move.
135 const Value EasyMoveMargin = Value(0x200);
137 // Problem margin. If the score of the first move at iteration N+1 has
138 // dropped by more than this since iteration N, the boolean variable
139 // "Problem" is set to true, which will make the program spend some extra
140 // time looking for a better move.
141 const Value ProblemMargin = Value(0x28);
143 // No problem margin. If the boolean "Problem" is true, and a new move
144 // is found at the root which is less than NoProblemMargin worse than the
145 // best move from the previous iteration, Problem is set back to false.
146 const Value NoProblemMargin = Value(0x14);
148 // Null move margin. A null move search will not be done if the approximate
149 // evaluation of the position is more than NullMoveMargin below beta.
150 const Value NullMoveMargin = Value(0x300);
152 // Pruning criterions. See the code and comments in ok_to_prune() to
153 // understand their precise meaning.
154 const bool PruneEscapeMoves = false;
155 const bool PruneDefendingMoves = false;
156 const bool PruneBlockingMoves = false;
158 // Use futility pruning?
159 bool UseQSearchFutilityPruning = true;
160 bool UseFutilityPruning = true;
162 // Margins for futility pruning in the quiescence search, and at frontier
163 // and near frontier nodes
164 Value FutilityMarginQS = Value(0x80);
165 Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
166 Value(0x2A0), Value(0x340), Value(0x3A0) };
169 const bool RazorAtDepthOne = false;
170 Depth RazorDepth = 4*OnePly;
171 Value RazorMargin = Value(0x300);
173 // Last seconds noise filtering (LSN)
174 bool UseLSNFiltering = false;
175 bool looseOnTime = false;
176 int LSNTime = 4 * 1000; // In milliseconds
177 Value LSNValue = Value(0x200);
179 // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes.
180 Depth CheckExtension[2] = {OnePly, OnePly};
181 Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
182 Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
183 Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
184 Depth PawnEndgameExtension[2] = {OnePly, OnePly};
185 Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
187 // Search depth at iteration 1
188 const Depth InitialDepth = OnePly /*+ OnePly/2*/;
192 int NodesBetweenPolls = 30000;
194 // Iteration counters
196 BetaCounterType BetaCounter;
198 // Scores and number of times the best move changed for each iteration:
199 Value ValueByIteration[PLY_MAX_PLUS_2];
200 int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
205 // Time managment variables
207 int MaxNodes, MaxDepth;
208 int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
213 bool StopOnPonderhit;
218 bool PonderingEnabled;
221 // Show current line?
222 bool ShowCurrentLine = false;
225 bool UseLogFile = false;
226 std::ofstream LogFile;
228 // MP related variables
229 Depth MinimumSplitDepth = 4*OnePly;
230 int MaxThreadsPerSplitPoint = 4;
231 Thread Threads[THREAD_MAX];
233 bool AllThreadsShouldExit = false;
234 const int MaxActiveSplitPoints = 8;
235 SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
238 #if !defined(_MSC_VER)
239 pthread_cond_t WaitCond;
240 pthread_mutex_t WaitLock;
242 HANDLE SitIdleEvent[THREAD_MAX];
248 Value id_loop(const Position &pos, Move searchMoves[]);
249 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
250 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
251 Depth depth, int ply, int threadID);
252 Value search(Position &pos, SearchStack ss[], Value beta,
253 Depth depth, int ply, bool allowNullmove, int threadID);
254 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
255 Depth depth, int ply, int threadID);
256 void sp_search(SplitPoint *sp, int threadID);
257 void sp_search_pv(SplitPoint *sp, int threadID);
258 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
259 void update_pv(SearchStack ss[], int ply);
260 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
261 bool connected_moves(const Position &pos, Move m1, Move m2);
262 bool value_is_mate(Value value);
263 bool move_is_killer(Move m, const SearchStack& ss);
264 Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
265 bool ok_to_do_nullmove(const Position &pos);
266 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
267 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
268 bool ok_to_history(const Position &pos, Move m);
269 void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
270 void update_killers(Move m, SearchStack& ss);
272 bool fail_high_ply_1();
273 int current_search_time();
277 void print_current_line(SearchStack ss[], int ply, int threadID);
278 void wait_for_stop_or_ponderhit();
280 void idle_loop(int threadID, SplitPoint *waitSp);
281 void init_split_point_stack();
282 void destroy_split_point_stack();
283 bool thread_should_stop(int threadID);
284 bool thread_is_available(int slave, int master);
285 bool idle_thread_exists(int master);
286 bool split(const Position &pos, SearchStack *ss, int ply,
287 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
288 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
289 void wake_sleeping_threads();
291 #if !defined(_MSC_VER)
292 void *init_thread(void *threadID);
294 DWORD WINAPI init_thread(LPVOID threadID);
301 //// Global variables
304 // The main transposition table
305 TranspositionTable TT = TranspositionTable(TTDefaultSize);
308 // Number of active threads:
309 int ActiveThreads = 1;
311 // Locks. In principle, there is no need for IOLock to be a global variable,
312 // but it could turn out to be useful for debugging.
315 History H; // Should be made local?
317 // The empty search stack
318 SearchStack EmptySearchStack;
321 // SearchStack::init() initializes a search stack. Used at the beginning of a
322 // new search from the root.
323 void SearchStack::init(int ply) {
325 pv[ply] = pv[ply + 1] = MOVE_NONE;
326 currentMove = threatMove = MOVE_NONE;
327 reduction = Depth(0);
328 currentMoveCaptureValue = Value(0);
331 void SearchStack::initKillers() {
333 mateKiller = MOVE_NONE;
334 for (int i = 0; i < KILLER_MAX; i++)
335 killers[i] = MOVE_NONE;
343 /// think() is the external interface to Stockfish's search, and is called when
344 /// the program receives the UCI 'go' command. It initializes various
345 /// search-related global variables, and calls root_search()
347 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
348 int time[], int increment[], int movesToGo, int maxDepth,
349 int maxNodes, int maxTime, Move searchMoves[]) {
351 // Look for a book move
352 if (!infinite && !ponder && get_option_value_bool("OwnBook"))
355 if (get_option_value_string("Book File") != OpeningBook.file_name())
358 OpeningBook.open("book.bin");
360 bookMove = OpeningBook.get_move(pos);
361 if (bookMove != MOVE_NONE)
363 std::cout << "bestmove " << bookMove << std::endl;
368 // Initialize global search variables
370 SearchStartTime = get_system_time();
371 EasyMove = MOVE_NONE;
372 for (int i = 0; i < THREAD_MAX; i++)
374 Threads[i].nodes = 0ULL;
375 Threads[i].failHighPly1 = false;
378 InfiniteSearch = infinite;
379 PonderSearch = ponder;
380 StopOnPonderhit = false;
385 ExactMaxTime = maxTime;
387 // Read UCI option values
388 TT.set_size(get_option_value_int("Hash"));
389 if (button_was_pressed("Clear Hash"))
392 PonderingEnabled = get_option_value_bool("Ponder");
393 MultiPV = get_option_value_int("MultiPV");
395 CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
396 CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
398 SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
399 SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
401 PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
402 PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
404 PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
405 PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
407 PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
408 PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
410 MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
411 MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
413 LMRPVMoves = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
414 LMRNonPVMoves = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
415 ThreatDepth = get_option_value_int("Threat Depth") * OnePly;
416 SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
418 Chess960 = get_option_value_bool("UCI_Chess960");
419 ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
420 UseLogFile = get_option_value_bool("Use Search Log");
422 LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
424 UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
425 UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
427 FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
428 int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
429 for (int i = 0; i < 6; i++)
430 FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
432 RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
433 RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
435 UseLSNFiltering = get_option_value_bool("LSN filtering");
436 LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
437 LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
439 MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
440 MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
442 read_weights(pos.side_to_move());
444 int newActiveThreads = get_option_value_int("Threads");
445 if (newActiveThreads != ActiveThreads)
447 ActiveThreads = newActiveThreads;
448 init_eval(ActiveThreads);
451 // Wake up sleeping threads:
452 wake_sleeping_threads();
454 for (int i = 1; i < ActiveThreads; i++)
455 assert(thread_is_available(i, 0));
457 // Set thinking time:
458 int myTime = time[side_to_move];
459 int myIncrement = increment[side_to_move];
461 if (!movesToGo) // Sudden death time control
465 MaxSearchTime = myTime / 30 + myIncrement;
466 AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
467 } else { // Blitz game without increment
468 MaxSearchTime = myTime / 30;
469 AbsoluteMaxSearchTime = myTime / 8;
472 else // (x moves) / (y minutes)
476 MaxSearchTime = myTime / 2;
477 AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
479 MaxSearchTime = myTime / Min(movesToGo, 20);
480 AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
484 if (PonderingEnabled)
486 MaxSearchTime += MaxSearchTime / 4;
487 MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
490 // Fixed depth or fixed number of nodes?
493 InfiniteSearch = true; // HACK
498 NodesBetweenPolls = Min(MaxNodes, 30000);
499 InfiniteSearch = true; // HACK
502 NodesBetweenPolls = 30000;
505 // Write information to search log file:
507 LogFile << "Searching: " << pos.to_fen() << std::endl
508 << "infinite: " << infinite
509 << " ponder: " << ponder
510 << " time: " << myTime
511 << " increment: " << myIncrement
512 << " moves to go: " << movesToGo << std::endl;
515 // We're ready to start thinking. Call the iterative deepening loop
519 Value v = id_loop(pos, searchMoves);
520 looseOnTime = ( UseLSNFiltering
527 looseOnTime = false; // reset for next match
528 while (SearchStartTime + myTime + 1000 > get_system_time())
530 id_loop(pos, searchMoves); // to fail gracefully
547 /// init_threads() is called during startup. It launches all helper threads,
548 /// and initializes the split point stack and the global locks and condition
551 void init_threads() {
555 #if !defined(_MSC_VER)
556 pthread_t pthread[1];
559 for (i = 0; i < THREAD_MAX; i++)
560 Threads[i].activeSplitPoints = 0;
562 // Initialize global locks:
563 lock_init(&MPLock, NULL);
564 lock_init(&IOLock, NULL);
566 init_split_point_stack();
568 #if !defined(_MSC_VER)
569 pthread_mutex_init(&WaitLock, NULL);
570 pthread_cond_init(&WaitCond, NULL);
572 for (i = 0; i < THREAD_MAX; i++)
573 SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
576 // All threads except the main thread should be initialized to idle state
577 for (i = 1; i < THREAD_MAX; i++)
579 Threads[i].stop = false;
580 Threads[i].workIsWaiting = false;
581 Threads[i].idle = true;
582 Threads[i].running = false;
585 // Launch the helper threads
586 for(i = 1; i < THREAD_MAX; i++)
588 #if !defined(_MSC_VER)
589 pthread_create(pthread, NULL, init_thread, (void*)(&i));
592 CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
595 // Wait until the thread has finished launching:
596 while (!Threads[i].running);
599 // Init also the empty search stack
600 EmptySearchStack.init(0);
601 EmptySearchStack.initKillers();
605 /// stop_threads() is called when the program exits. It makes all the
606 /// helper threads exit cleanly.
608 void stop_threads() {
610 ActiveThreads = THREAD_MAX; // HACK
611 Idle = false; // HACK
612 wake_sleeping_threads();
613 AllThreadsShouldExit = true;
614 for (int i = 1; i < THREAD_MAX; i++)
616 Threads[i].stop = true;
617 while(Threads[i].running);
619 destroy_split_point_stack();
623 /// nodes_searched() returns the total number of nodes searched so far in
624 /// the current search.
626 int64_t nodes_searched() {
628 int64_t result = 0ULL;
629 for (int i = 0; i < ActiveThreads; i++)
630 result += Threads[i].nodes;
637 // id_loop() is the main iterative deepening loop. It calls root_search
638 // repeatedly with increasing depth until the allocated thinking time has
639 // been consumed, the user stops the search, or the maximum search depth is
642 Value id_loop(const Position &pos, Move searchMoves[]) {
645 SearchStack ss[PLY_MAX_PLUS_2];
647 // searchMoves are verified, copied, scored and sorted
648 RootMoveList rml(p, searchMoves);
653 for (int i = 0; i < 3; i++)
658 ValueByIteration[0] = Value(0);
659 ValueByIteration[1] = rml.get_move_score(0);
662 EasyMove = rml.scan_for_easy_move();
664 // Iterative deepening loop
665 while (!AbortSearch && Iteration < PLY_MAX)
667 // Initialize iteration
670 BestMoveChangesByIteration[Iteration] = 0;
674 std::cout << "info depth " << Iteration << std::endl;
676 // Search to the current depth
677 ValueByIteration[Iteration] = root_search(p, ss, rml);
679 // Erase the easy move if it differs from the new best move
680 if (ss[0].pv[0] != EasyMove)
681 EasyMove = MOVE_NONE;
688 bool stopSearch = false;
690 // Stop search early if there is only a single legal move:
691 if (Iteration >= 6 && rml.move_count() == 1)
694 // Stop search early when the last two iterations returned a mate score
696 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
697 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
700 // Stop search early if one move seems to be much better than the rest
701 int64_t nodes = nodes_searched();
703 && EasyMove == ss[0].pv[0]
704 && ( ( rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
705 && current_search_time() > MaxSearchTime / 16)
706 ||( rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
707 && current_search_time() > MaxSearchTime / 32)))
710 // Add some extra time if the best move has changed during the last two iterations
711 if (Iteration > 5 && Iteration <= 50)
712 ExtraSearchTime = BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2)
713 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
715 // Stop search if most of MaxSearchTime is consumed at the end of the
716 // iteration. We probably don't have enough time to search the first
717 // move at the next iteration anyway.
718 if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
726 StopOnPonderhit = true;
729 // Write PV to transposition table, in case the relevant entries have
730 // been overwritten during the search:
731 TT.insert_pv(p, ss[0].pv);
733 if (MaxDepth && Iteration >= MaxDepth)
739 // If we are pondering, we shouldn't print the best move before we
742 wait_for_stop_or_ponderhit();
744 // Print final search statistics
745 std::cout << "info nodes " << nodes_searched()
747 << " time " << current_search_time()
748 << " hashfull " << TT.full() << std::endl;
750 // Print the best move and the ponder move to the standard output
751 std::cout << "bestmove " << ss[0].pv[0];
752 if (ss[0].pv[1] != MOVE_NONE)
753 std::cout << " ponder " << ss[0].pv[1];
755 std::cout << std::endl;
760 dbg_print_mean(LogFile);
762 if (dbg_show_hit_rate)
763 dbg_print_hit_rate(LogFile);
766 LogFile << "Nodes: " << nodes_searched() << std::endl
767 << "Nodes/second: " << nps() << std::endl
768 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
770 p.do_move(ss[0].pv[0], st);
771 LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
772 << std::endl << std::endl;
774 return rml.get_move_score(0);
778 // root_search() is the function which searches the root node. It is
779 // similar to search_pv except that it uses a different move ordering
780 // scheme (perhaps we should try to use this at internal PV nodes, too?)
781 // and prints some information to the standard output.
783 Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
785 Value alpha = -VALUE_INFINITE;
786 Value beta = VALUE_INFINITE, value;
787 Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
789 // Loop through all the moves in the root move list
790 for (int i = 0; i < rml.move_count() && !AbortSearch; i++)
797 RootMoveNumber = i + 1;
800 // Remember the node count before the move is searched. The node counts
801 // are used to sort the root moves at the next iteration.
802 nodes = nodes_searched();
804 // Reset beta cut-off counters
807 // Pick the next root move, and print the move and the move number to
808 // the standard output.
809 move = ss[0].currentMove = rml.get_move(i);
810 if (current_search_time() >= 1000)
811 std::cout << "info currmove " << move
812 << " currmovenumber " << i + 1 << std::endl;
814 // Decide search depth for this move
816 ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
817 newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
819 // Make the move, and search it
820 pos.do_move(move, st, dcCandidates);
824 value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
825 // If the value has dropped a lot compared to the last iteration,
826 // set the boolean variable Problem to true. This variable is used
827 // for time managment: When Problem is true, we try to complete the
828 // current iteration before playing a move.
829 Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
831 if (Problem && StopOnPonderhit)
832 StopOnPonderhit = false;
836 value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
839 // Fail high! Set the boolean variable FailHigh to true, and
840 // re-search the move with a big window. The variable FailHigh is
841 // used for time managment: We try to avoid aborting the search
842 // prematurely during a fail high research.
844 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
850 // Finished searching the move. If AbortSearch is true, the search
851 // was aborted because the user interrupted the search or because we
852 // ran out of time. In this case, the return value of the search cannot
853 // be trusted, and we break out of the loop without updating the best
858 // Remember the node count for this move. The node counts are used to
859 // sort the root moves at the next iteration.
860 rml.set_move_nodes(i, nodes_searched() - nodes);
862 // Remember the beta-cutoff statistics
864 BetaCounter.read(pos.side_to_move(), our, their);
865 rml.set_beta_counters(i, our, their);
867 assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
869 if (value <= alpha && i >= MultiPV)
870 rml.set_move_score(i, -VALUE_INFINITE);
876 rml.set_move_score(i, value);
878 rml.set_move_pv(i, ss[0].pv);
882 // We record how often the best move has been changed in each
883 // iteration. This information is used for time managment: When
884 // the best move changes frequently, we allocate some more time.
886 BestMoveChangesByIteration[Iteration]++;
888 // Print search information to the standard output:
889 std::cout << "info depth " << Iteration
890 << " score " << value_to_string(value)
891 << " time " << current_search_time()
892 << " nodes " << nodes_searched()
896 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
897 std::cout << ss[0].pv[j] << " ";
899 std::cout << std::endl;
902 LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
907 // Reset the global variable Problem to false if the value isn't too
908 // far below the final value from the last iteration.
909 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
915 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
918 std::cout << "info multipv " << j + 1
919 << " score " << value_to_string(rml.get_move_score(j))
920 << " depth " << ((j <= i)? Iteration : Iteration - 1)
921 << " time " << current_search_time()
922 << " nodes " << nodes_searched()
926 for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
927 std::cout << rml.get_move_pv(j, k) << " ";
929 std::cout << std::endl;
931 alpha = rml.get_move_score(Min(i, MultiPV-1));
939 // search_pv() is the main search function for PV nodes.
941 Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
942 Depth depth, int ply, int threadID) {
944 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
945 assert(beta > alpha && beta <= VALUE_INFINITE);
946 assert(ply >= 0 && ply < PLY_MAX);
947 assert(threadID >= 0 && threadID < ActiveThreads);
950 return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
952 // Initialize, and make an early exit in case of an aborted search,
953 // an instant draw, maximum ply reached, etc.
954 init_node(pos, ss, ply, threadID);
956 // After init_node() that calls poll()
957 if (AbortSearch || thread_should_stop(threadID))
965 if (ply >= PLY_MAX - 1)
966 return evaluate(pos, ei, threadID);
968 // Mate distance pruning
969 Value oldAlpha = alpha;
970 alpha = Max(value_mated_in(ply), alpha);
971 beta = Min(value_mate_in(ply+1), beta);
975 // Transposition table lookup. At PV nodes, we don't use the TT for
976 // pruning, but only for move ordering.
977 const TTEntry* tte = TT.retrieve(pos);
978 Move ttMove = (tte ? tte->move() : MOVE_NONE);
980 // Go with internal iterative deepening if we don't have a TT move
981 if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
983 search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
984 ttMove = ss[ply].pv[ply];
987 // Initialize a MovePicker object for the current position, and prepare
988 // to search all moves
989 MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
991 Move move, movesSearched[256];
993 Value value, bestValue = -VALUE_INFINITE;
994 Bitboard dcCandidates = mp.discovered_check_candidates();
995 Color us = pos.side_to_move();
996 bool isCheck = pos.is_check();
997 bool mateThreat = pos.has_mate_threat(opposite_color(us));
999 // Loop through all legal moves until no moves remain or a beta cutoff
1001 while ( alpha < beta
1002 && (move = mp.get_next_move()) != MOVE_NONE
1003 && !thread_should_stop(threadID))
1005 assert(move_is_ok(move));
1007 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1008 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1009 bool moveIsCapture = pos.move_is_capture(move);
1011 movesSearched[moveCount++] = ss[ply].currentMove = move;
1014 ss[ply].currentMoveCaptureValue =
1015 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1017 ss[ply].currentMoveCaptureValue = Value(0);
1019 // Decide the new search depth
1021 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1022 Depth newDepth = depth - OnePly + ext;
1024 // Make and search the move
1026 pos.do_move(move, st, dcCandidates);
1028 if (moveCount == 1) // The first move in list is the PV
1029 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1032 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1033 // if the move fails high will be re-searched at full depth.
1034 if ( depth >= 2*OnePly
1035 && moveCount >= LMRPVMoves
1038 && !move_promotion(move)
1039 && !move_is_castle(move)
1040 && !move_is_killer(move, ss[ply]))
1042 ss[ply].reduction = OnePly;
1043 value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1046 value = alpha + 1; // Just to trigger next condition
1048 if (value > alpha) // Go with full depth non-pv search
1050 ss[ply].reduction = Depth(0);
1051 value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1052 if (value > alpha && value < beta)
1054 // When the search fails high at ply 1 while searching the first
1055 // move at the root, set the flag failHighPly1. This is used for
1056 // time managment: We don't want to stop the search early in
1057 // such cases, because resolving the fail high at ply 1 could
1058 // result in a big drop in score at the root.
1059 if (ply == 1 && RootMoveNumber == 1)
1060 Threads[threadID].failHighPly1 = true;
1062 // A fail high occurred. Re-search at full window (pv search)
1063 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1064 Threads[threadID].failHighPly1 = false;
1068 pos.undo_move(move);
1070 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1073 if (value > bestValue)
1080 if (value == value_mate_in(ply + 1))
1081 ss[ply].mateKiller = move;
1083 // If we are at ply 1, and we are searching the first root move at
1084 // ply 0, set the 'Problem' variable if the score has dropped a lot
1085 // (from the computer's point of view) since the previous iteration:
1088 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1093 if ( ActiveThreads > 1
1095 && depth >= MinimumSplitDepth
1097 && idle_thread_exists(threadID)
1099 && !thread_should_stop(threadID)
1100 && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1101 &moveCount, &mp, dcCandidates, threadID, true))
1105 // All legal moves have been searched. A special case: If there were
1106 // no legal moves, it must be mate or stalemate:
1108 return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1110 // If the search is not aborted, update the transposition table,
1111 // history counters, and killer moves.
1112 if (AbortSearch || thread_should_stop(threadID))
1115 if (bestValue <= oldAlpha)
1116 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1118 else if (bestValue >= beta)
1120 BetaCounter.add(pos.side_to_move(), depth, threadID);
1121 Move m = ss[ply].pv[ply];
1122 if (ok_to_history(pos, m)) // Only non capture moves are considered
1124 update_history(pos, m, depth, movesSearched, moveCount);
1125 update_killers(m, ss[ply]);
1127 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1130 TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1136 // search() is the search function for zero-width nodes.
1138 Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1139 int ply, bool allowNullmove, int threadID) {
1141 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1142 assert(ply >= 0 && ply < PLY_MAX);
1143 assert(threadID >= 0 && threadID < ActiveThreads);
1146 return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1148 // Initialize, and make an early exit in case of an aborted search,
1149 // an instant draw, maximum ply reached, etc.
1150 init_node(pos, ss, ply, threadID);
1152 // After init_node() that calls poll()
1153 if (AbortSearch || thread_should_stop(threadID))
1161 if (ply >= PLY_MAX - 1)
1162 return evaluate(pos, ei, threadID);
1164 // Mate distance pruning
1165 if (value_mated_in(ply) >= beta)
1168 if (value_mate_in(ply + 1) < beta)
1171 // Transposition table lookup
1172 const TTEntry* tte = TT.retrieve(pos);
1173 Move ttMove = (tte ? tte->move() : MOVE_NONE);
1175 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1177 ss[ply].currentMove = ttMove; // can be MOVE_NONE
1178 return value_from_tt(tte->value(), ply);
1181 Value approximateEval = quick_evaluate(pos);
1182 bool mateThreat = false;
1183 bool isCheck = pos.is_check();
1189 && !value_is_mate(beta)
1190 && ok_to_do_nullmove(pos)
1191 && approximateEval >= beta - NullMoveMargin)
1193 ss[ply].currentMove = MOVE_NULL;
1196 pos.do_null_move(st);
1197 int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1199 Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1201 pos.undo_null_move();
1203 if (value_is_mate(nullValue))
1205 /* Do not return unproven mates */
1207 else if (nullValue >= beta)
1209 if (depth < 6 * OnePly)
1212 // Do zugzwang verification search
1213 Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1217 // The null move failed low, which means that we may be faced with
1218 // some kind of threat. If the previous move was reduced, check if
1219 // the move that refuted the null move was somehow connected to the
1220 // move which was reduced. If a connection is found, return a fail
1221 // low score (which will cause the reduced move to fail high in the
1222 // parent node, which will trigger a re-search with full depth).
1223 if (nullValue == value_mated_in(ply + 2))
1226 ss[ply].threatMove = ss[ply + 1].currentMove;
1227 if ( depth < ThreatDepth
1228 && ss[ply - 1].reduction
1229 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1233 // Null move search not allowed, try razoring
1234 else if ( !value_is_mate(beta)
1235 && approximateEval < beta - RazorMargin
1236 && depth < RazorDepth
1237 && (RazorAtDepthOne || depth > OnePly)
1238 && ttMove == MOVE_NONE
1239 && !pos.has_pawn_on_7th(pos.side_to_move()))
1241 Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1242 if ( (v < beta - RazorMargin - RazorMargin / 4)
1243 || (depth < 3*OnePly && v < beta - RazorMargin)
1244 || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1248 // Go with internal iterative deepening if we don't have a TT move
1249 if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1250 evaluate(pos, ei, threadID) >= beta - IIDMargin)
1252 search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1253 ttMove = ss[ply].pv[ply];
1256 // Initialize a MovePicker object for the current position, and prepare
1257 // to search all moves:
1258 MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1260 Move move, movesSearched[256];
1262 Value value, bestValue = -VALUE_INFINITE;
1263 Bitboard dcCandidates = mp.discovered_check_candidates();
1264 Value futilityValue = VALUE_NONE;
1265 bool useFutilityPruning = UseFutilityPruning
1266 && depth < SelectiveDepth
1269 // Loop through all legal moves until no moves remain or a beta cutoff
1271 while ( bestValue < beta
1272 && (move = mp.get_next_move()) != MOVE_NONE
1273 && !thread_should_stop(threadID))
1275 assert(move_is_ok(move));
1277 bool singleReply = (isCheck && mp.number_of_moves() == 1);
1278 bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1279 bool moveIsCapture = pos.move_is_capture(move);
1281 movesSearched[moveCount++] = ss[ply].currentMove = move;
1283 // Decide the new search depth
1285 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1286 Depth newDepth = depth - OnePly + ext;
1289 if ( useFutilityPruning
1292 && !move_promotion(move))
1294 // History pruning. See ok_to_prune() definition
1295 if ( moveCount >= 2 + int(depth)
1296 && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1299 // Value based pruning
1300 if (depth < 7 * OnePly && approximateEval < beta)
1302 if (futilityValue == VALUE_NONE)
1303 futilityValue = evaluate(pos, ei, threadID)
1304 + FutilityMargins[int(depth)/2 - 1]
1307 if (futilityValue < beta)
1309 if (futilityValue > bestValue)
1310 bestValue = futilityValue;
1316 // Make and search the move
1318 pos.do_move(move, st, dcCandidates);
1320 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1321 // if the move fails high will be re-searched at full depth.
1322 if ( depth >= 2*OnePly
1323 && moveCount >= LMRNonPVMoves
1326 && !move_promotion(move)
1327 && !move_is_castle(move)
1328 && !move_is_killer(move, ss[ply]))
1330 ss[ply].reduction = OnePly;
1331 value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1334 value = beta; // Just to trigger next condition
1336 if (value >= beta) // Go with full depth non-pv search
1338 ss[ply].reduction = Depth(0);
1339 value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1341 pos.undo_move(move);
1343 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1346 if (value > bestValue)
1352 if (value == value_mate_in(ply + 1))
1353 ss[ply].mateKiller = move;
1357 if ( ActiveThreads > 1
1359 && depth >= MinimumSplitDepth
1361 && idle_thread_exists(threadID)
1363 && !thread_should_stop(threadID)
1364 && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1365 &mp, dcCandidates, threadID, false))
1369 // All legal moves have been searched. A special case: If there were
1370 // no legal moves, it must be mate or stalemate.
1372 return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1374 // If the search is not aborted, update the transposition table,
1375 // history counters, and killer moves.
1376 if (AbortSearch || thread_should_stop(threadID))
1379 if (bestValue < beta)
1380 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1383 BetaCounter.add(pos.side_to_move(), depth, threadID);
1384 Move m = ss[ply].pv[ply];
1385 if (ok_to_history(pos, m)) // Only non capture moves are considered
1387 update_history(pos, m, depth, movesSearched, moveCount);
1388 update_killers(m, ss[ply]);
1390 TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1396 // qsearch() is the quiescence search function, which is called by the main
1397 // search function when the remaining depth is zero (or, to be more precise,
1398 // less than OnePly).
1400 Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1401 Depth depth, int ply, int threadID) {
1403 assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1404 assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1406 assert(ply >= 0 && ply < PLY_MAX);
1407 assert(threadID >= 0 && threadID < ActiveThreads);
1409 // Initialize, and make an early exit in case of an aborted search,
1410 // an instant draw, maximum ply reached, etc.
1411 init_node(pos, ss, ply, threadID);
1413 // After init_node() that calls poll()
1414 if (AbortSearch || thread_should_stop(threadID))
1420 // Transposition table lookup, only when not in PV
1421 bool pvNode = (beta - alpha != 1);
1424 const TTEntry* tte = TT.retrieve(pos);
1425 if (tte && ok_to_use_TT(tte, depth, beta, ply))
1426 return value_from_tt(tte->value(), ply);
1429 // Evaluate the position statically
1431 bool isCheck = pos.is_check();
1432 Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1434 if (ply == PLY_MAX - 1)
1435 return evaluate(pos, ei, threadID);
1437 // Initialize "stand pat score", and return it immediately if it is
1439 Value bestValue = staticValue;
1441 if (bestValue >= beta)
1444 if (bestValue > alpha)
1447 // Initialize a MovePicker object for the current position, and prepare
1448 // to search the moves. Because the depth is <= 0 here, only captures,
1449 // queen promotions and checks (only if depth == 0) will be generated.
1450 MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1453 Bitboard dcCandidates = mp.discovered_check_candidates();
1454 Color us = pos.side_to_move();
1455 bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1457 // Loop through the moves until no moves remain or a beta cutoff
1459 while ( alpha < beta
1460 && (move = mp.get_next_move()) != MOVE_NONE)
1462 assert(move_is_ok(move));
1465 ss[ply].currentMove = move;
1468 if ( UseQSearchFutilityPruning
1472 && !move_promotion(move)
1473 && !pos.move_is_check(move, dcCandidates)
1474 && !pos.move_is_passed_pawn_push(move))
1476 Value futilityValue = staticValue
1477 + Max(pos.midgame_value_of_piece_on(move_to(move)),
1478 pos.endgame_value_of_piece_on(move_to(move)))
1479 + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1481 + ei.futilityMargin;
1483 if (futilityValue < alpha)
1485 if (futilityValue > bestValue)
1486 bestValue = futilityValue;
1491 // Don't search captures and checks with negative SEE values
1493 && !move_promotion(move)
1494 && (pos.midgame_value_of_piece_on(move_from(move)) >
1495 pos.midgame_value_of_piece_on(move_to(move)))
1496 && pos.see(move) < 0)
1499 // Make and search the move.
1501 pos.do_move(move, st, dcCandidates);
1502 Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1503 pos.undo_move(move);
1505 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1508 if (value > bestValue)
1519 // All legal moves have been searched. A special case: If we're in check
1520 // and no legal moves were found, it is checkmate:
1521 if (pos.is_check() && moveCount == 0) // Mate!
1522 return value_mated_in(ply);
1524 assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1526 // Update transposition table
1527 TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1529 // Update killers only for good check moves
1530 Move m = ss[ply].currentMove;
1531 if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1533 // Wrong to update history when depth is <= 0
1534 update_killers(m, ss[ply]);
1540 // sp_search() is used to search from a split point. This function is called
1541 // by each thread working at the split point. It is similar to the normal
1542 // search() function, but simpler. Because we have already probed the hash
1543 // table, done a null move search, and searched the first move before
1544 // splitting, we don't have to repeat all this work in sp_search(). We
1545 // also don't need to store anything to the hash table here: This is taken
1546 // care of after we return from the split point.
1548 void sp_search(SplitPoint *sp, int threadID) {
1550 assert(threadID >= 0 && threadID < ActiveThreads);
1551 assert(ActiveThreads > 1);
1553 Position pos = Position(sp->pos);
1554 SearchStack *ss = sp->sstack[threadID];
1557 bool isCheck = pos.is_check();
1558 bool useFutilityPruning = UseFutilityPruning
1559 && sp->depth < SelectiveDepth
1562 while ( sp->bestValue < sp->beta
1563 && !thread_should_stop(threadID)
1564 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1566 assert(move_is_ok(move));
1568 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1569 bool moveIsCapture = pos.move_is_capture(move);
1571 lock_grab(&(sp->lock));
1572 int moveCount = ++sp->moves;
1573 lock_release(&(sp->lock));
1575 ss[sp->ply].currentMove = move;
1577 // Decide the new search depth.
1579 Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1580 Depth newDepth = sp->depth - OnePly + ext;
1583 if ( useFutilityPruning
1586 && !move_promotion(move)
1587 && moveCount >= 2 + int(sp->depth)
1588 && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1591 // Make and search the move.
1593 pos.do_move(move, st, sp->dcCandidates);
1595 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1596 // if the move fails high will be re-searched at full depth.
1598 && moveCount >= LMRNonPVMoves
1600 && !move_promotion(move)
1601 && !move_is_castle(move)
1602 && !move_is_killer(move, ss[sp->ply]))
1604 ss[sp->ply].reduction = OnePly;
1605 value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1608 value = sp->beta; // Just to trigger next condition
1610 if (value >= sp->beta) // Go with full depth non-pv search
1612 ss[sp->ply].reduction = Depth(0);
1613 value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1615 pos.undo_move(move);
1617 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1619 if (thread_should_stop(threadID))
1623 lock_grab(&(sp->lock));
1624 if (value > sp->bestValue && !thread_should_stop(threadID))
1626 sp->bestValue = value;
1627 if (sp->bestValue >= sp->beta)
1629 sp_update_pv(sp->parentSstack, ss, sp->ply);
1630 for (int i = 0; i < ActiveThreads; i++)
1631 if (i != threadID && (i == sp->master || sp->slaves[i]))
1632 Threads[i].stop = true;
1634 sp->finished = true;
1637 lock_release(&(sp->lock));
1640 lock_grab(&(sp->lock));
1642 // If this is the master thread and we have been asked to stop because of
1643 // a beta cutoff higher up in the tree, stop all slave threads:
1644 if (sp->master == threadID && thread_should_stop(threadID))
1645 for (int i = 0; i < ActiveThreads; i++)
1647 Threads[i].stop = true;
1650 sp->slaves[threadID] = 0;
1652 lock_release(&(sp->lock));
1656 // sp_search_pv() is used to search from a PV split point. This function
1657 // is called by each thread working at the split point. It is similar to
1658 // the normal search_pv() function, but simpler. Because we have already
1659 // probed the hash table and searched the first move before splitting, we
1660 // don't have to repeat all this work in sp_search_pv(). We also don't
1661 // need to store anything to the hash table here: This is taken care of
1662 // after we return from the split point.
1664 void sp_search_pv(SplitPoint *sp, int threadID) {
1666 assert(threadID >= 0 && threadID < ActiveThreads);
1667 assert(ActiveThreads > 1);
1669 Position pos = Position(sp->pos);
1670 SearchStack *ss = sp->sstack[threadID];
1674 while ( sp->alpha < sp->beta
1675 && !thread_should_stop(threadID)
1676 && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1678 bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1679 bool moveIsCapture = pos.move_is_capture(move);
1681 assert(move_is_ok(move));
1684 ss[sp->ply].currentMoveCaptureValue =
1685 move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1687 ss[sp->ply].currentMoveCaptureValue = Value(0);
1689 lock_grab(&(sp->lock));
1690 int moveCount = ++sp->moves;
1691 lock_release(&(sp->lock));
1693 ss[sp->ply].currentMove = move;
1695 // Decide the new search depth.
1697 Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1698 Depth newDepth = sp->depth - OnePly + ext;
1700 // Make and search the move.
1702 pos.do_move(move, st, sp->dcCandidates);
1704 // Try to reduce non-pv search depth by one ply if move seems not problematic,
1705 // if the move fails high will be re-searched at full depth.
1707 && moveCount >= LMRPVMoves
1709 && !move_promotion(move)
1710 && !move_is_castle(move)
1711 && !move_is_killer(move, ss[sp->ply]))
1713 ss[sp->ply].reduction = OnePly;
1714 value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1717 value = sp->alpha + 1; // Just to trigger next condition
1719 if (value > sp->alpha) // Go with full depth non-pv search
1721 ss[sp->ply].reduction = Depth(0);
1722 value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1724 if (value > sp->alpha && value < sp->beta)
1726 // When the search fails high at ply 1 while searching the first
1727 // move at the root, set the flag failHighPly1. This is used for
1728 // time managment: We don't want to stop the search early in
1729 // such cases, because resolving the fail high at ply 1 could
1730 // result in a big drop in score at the root.
1731 if (sp->ply == 1 && RootMoveNumber == 1)
1732 Threads[threadID].failHighPly1 = true;
1734 value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1735 Threads[threadID].failHighPly1 = false;
1738 pos.undo_move(move);
1740 assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1742 if (thread_should_stop(threadID))
1746 lock_grab(&(sp->lock));
1747 if (value > sp->bestValue && !thread_should_stop(threadID))
1749 sp->bestValue = value;
1750 if (value > sp->alpha)
1753 sp_update_pv(sp->parentSstack, ss, sp->ply);
1754 if (value == value_mate_in(sp->ply + 1))
1755 ss[sp->ply].mateKiller = move;
1757 if(value >= sp->beta)
1759 for(int i = 0; i < ActiveThreads; i++)
1760 if(i != threadID && (i == sp->master || sp->slaves[i]))
1761 Threads[i].stop = true;
1763 sp->finished = true;
1766 // If we are at ply 1, and we are searching the first root move at
1767 // ply 0, set the 'Problem' variable if the score has dropped a lot
1768 // (from the computer's point of view) since the previous iteration.
1771 && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1774 lock_release(&(sp->lock));
1777 lock_grab(&(sp->lock));
1779 // If this is the master thread and we have been asked to stop because of
1780 // a beta cutoff higher up in the tree, stop all slave threads.
1781 if (sp->master == threadID && thread_should_stop(threadID))
1782 for (int i = 0; i < ActiveThreads; i++)
1784 Threads[i].stop = true;
1787 sp->slaves[threadID] = 0;
1789 lock_release(&(sp->lock));
1792 /// The BetaCounterType class
1794 BetaCounterType::BetaCounterType() { clear(); }
1796 void BetaCounterType::clear() {
1798 for (int i = 0; i < THREAD_MAX; i++)
1799 hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1802 void BetaCounterType::add(Color us, Depth d, int threadID) {
1804 // Weighted count based on depth
1805 hits[threadID][us] += int(d);
1808 void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1811 for (int i = 0; i < THREAD_MAX; i++)
1814 their += hits[i][opposite_color(us)];
1819 /// The RootMove class
1823 RootMove::RootMove() {
1824 nodes = cumulativeNodes = 0ULL;
1827 // RootMove::operator<() is the comparison function used when
1828 // sorting the moves. A move m1 is considered to be better
1829 // than a move m2 if it has a higher score, or if the moves
1830 // have equal score but m1 has the higher node count.
1832 bool RootMove::operator<(const RootMove& m) {
1834 if (score != m.score)
1835 return (score < m.score);
1837 return theirBeta <= m.theirBeta;
1840 /// The RootMoveList class
1844 RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1846 MoveStack mlist[MaxRootMoves];
1847 bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1849 // Generate all legal moves
1850 int lm_count = generate_legal_moves(pos, mlist);
1852 // Add each move to the moves[] array
1853 for (int i = 0; i < lm_count; i++)
1855 bool includeMove = includeAllMoves;
1857 for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1858 includeMove = (searchMoves[k] == mlist[i].move);
1862 // Find a quick score for the move
1864 SearchStack ss[PLY_MAX_PLUS_2];
1866 moves[count].move = mlist[i].move;
1867 moves[count].nodes = 0ULL;
1868 pos.do_move(moves[count].move, st);
1869 moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1871 pos.undo_move(moves[count].move);
1872 moves[count].pv[0] = moves[i].move;
1873 moves[count].pv[1] = MOVE_NONE; // FIXME
1881 // Simple accessor methods for the RootMoveList class
1883 inline Move RootMoveList::get_move(int moveNum) const {
1884 return moves[moveNum].move;
1887 inline Value RootMoveList::get_move_score(int moveNum) const {
1888 return moves[moveNum].score;
1891 inline void RootMoveList::set_move_score(int moveNum, Value score) {
1892 moves[moveNum].score = score;
1895 inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1896 moves[moveNum].nodes = nodes;
1897 moves[moveNum].cumulativeNodes += nodes;
1900 inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1901 moves[moveNum].ourBeta = our;
1902 moves[moveNum].theirBeta = their;
1905 void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1907 for(j = 0; pv[j] != MOVE_NONE; j++)
1908 moves[moveNum].pv[j] = pv[j];
1909 moves[moveNum].pv[j] = MOVE_NONE;
1912 inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1913 return moves[moveNum].pv[i];
1916 inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1917 return moves[moveNum].cumulativeNodes;
1920 inline int RootMoveList::move_count() const {
1925 // RootMoveList::scan_for_easy_move() is called at the end of the first
1926 // iteration, and is used to detect an "easy move", i.e. a move which appears
1927 // to be much bester than all the rest. If an easy move is found, the move
1928 // is returned, otherwise the function returns MOVE_NONE. It is very
1929 // important that this function is called at the right moment: The code
1930 // assumes that the first iteration has been completed and the moves have
1931 // been sorted. This is done in RootMoveList c'tor.
1933 Move RootMoveList::scan_for_easy_move() const {
1940 // moves are sorted so just consider the best and the second one
1941 if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1947 // RootMoveList::sort() sorts the root move list at the beginning of a new
1950 inline void RootMoveList::sort() {
1952 sort_multipv(count - 1); // all items
1956 // RootMoveList::sort_multipv() sorts the first few moves in the root move
1957 // list by their scores and depths. It is used to order the different PVs
1958 // correctly in MultiPV mode.
1960 void RootMoveList::sort_multipv(int n) {
1962 for (int i = 1; i <= n; i++)
1964 RootMove rm = moves[i];
1966 for (j = i; j > 0 && moves[j-1] < rm; j--)
1967 moves[j] = moves[j-1];
1973 // init_node() is called at the beginning of all the search functions
1974 // (search(), search_pv(), qsearch(), and so on) and initializes the search
1975 // stack object corresponding to the current node. Once every
1976 // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1977 // for user input and checks whether it is time to stop the search.
1979 void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1980 assert(ply >= 0 && ply < PLY_MAX);
1981 assert(threadID >= 0 && threadID < ActiveThreads);
1983 Threads[threadID].nodes++;
1987 if(NodesSincePoll >= NodesBetweenPolls) {
1994 ss[ply+2].initKillers();
1996 if(Threads[threadID].printCurrentLine)
1997 print_current_line(ss, ply, threadID);
2001 // update_pv() is called whenever a search returns a value > alpha. It
2002 // updates the PV in the SearchStack object corresponding to the current
2005 void update_pv(SearchStack ss[], int ply) {
2006 assert(ply >= 0 && ply < PLY_MAX);
2008 ss[ply].pv[ply] = ss[ply].currentMove;
2010 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2011 ss[ply].pv[p] = ss[ply+1].pv[p];
2012 ss[ply].pv[p] = MOVE_NONE;
2016 // sp_update_pv() is a variant of update_pv for use at split points. The
2017 // difference between the two functions is that sp_update_pv also updates
2018 // the PV at the parent node.
2020 void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2021 assert(ply >= 0 && ply < PLY_MAX);
2023 ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2025 for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2026 ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2027 ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2031 // connected_moves() tests whether two moves are 'connected' in the sense
2032 // that the first move somehow made the second move possible (for instance
2033 // if the moving piece is the same in both moves). The first move is
2034 // assumed to be the move that was made to reach the current position, while
2035 // the second move is assumed to be a move from the current position.
2037 bool connected_moves(const Position &pos, Move m1, Move m2) {
2038 Square f1, t1, f2, t2;
2040 assert(move_is_ok(m1));
2041 assert(move_is_ok(m2));
2046 // Case 1: The moving piece is the same in both moves.
2052 // Case 2: The destination square for m2 was vacated by m1.
2058 // Case 3: Moving through the vacated square:
2059 if(piece_is_slider(pos.piece_on(f2)) &&
2060 bit_is_set(squares_between(f2, t2), f1))
2063 // Case 4: The destination square for m2 is attacked by the moving piece
2065 if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2068 // Case 5: Discovered check, checking piece is the piece moved in m1:
2069 if(piece_is_slider(pos.piece_on(t1)) &&
2070 bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2072 !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2074 Bitboard occ = pos.occupied_squares();
2075 Color us = pos.side_to_move();
2076 Square ksq = pos.king_square(us);
2077 clear_bit(&occ, f2);
2078 if(pos.type_of_piece_on(t1) == BISHOP) {
2079 if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2082 else if(pos.type_of_piece_on(t1) == ROOK) {
2083 if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2087 assert(pos.type_of_piece_on(t1) == QUEEN);
2088 if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2097 // value_is_mate() checks if the given value is a mate one
2098 // eventually compensated for the ply.
2100 bool value_is_mate(Value value) {
2102 assert(abs(value) <= VALUE_INFINITE);
2104 return value <= value_mated_in(PLY_MAX)
2105 || value >= value_mate_in(PLY_MAX);
2109 // move_is_killer() checks if the given move is among the
2110 // killer moves of that ply.
2112 bool move_is_killer(Move m, const SearchStack& ss) {
2114 const Move* k = ss.killers;
2115 for (int i = 0; i < KILLER_MAX; i++, k++)
2123 // extension() decides whether a move should be searched with normal depth,
2124 // or with extended depth. Certain classes of moves (checking moves, in
2125 // particular) are searched with bigger depth than ordinary moves and in
2126 // any case are marked as 'dangerous'. Note that also if a move is not
2127 // extended, as example because the corresponding UCI option is set to zero,
2128 // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2130 Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2131 bool singleReply, bool mateThreat, bool* dangerous) {
2133 assert(m != MOVE_NONE);
2135 Depth result = Depth(0);
2136 *dangerous = check || singleReply || mateThreat;
2139 result += CheckExtension[pvNode];
2142 result += SingleReplyExtension[pvNode];
2145 result += MateThreatExtension[pvNode];
2147 if (pos.type_of_piece_on(move_from(m)) == PAWN)
2149 if (pos.move_is_pawn_push_to_7th(m))
2151 result += PawnPushTo7thExtension[pvNode];
2154 if (pos.move_is_passed_pawn_push(m))
2156 result += PassedPawnExtension[pvNode];
2162 && pos.type_of_piece_on(move_to(m)) != PAWN
2163 && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2164 - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2165 && !move_promotion(m)
2168 result += PawnEndgameExtension[pvNode];
2174 && pos.type_of_piece_on(move_to(m)) != PAWN
2181 return Min(result, OnePly);
2185 // ok_to_do_nullmove() looks at the current position and decides whether
2186 // doing a 'null move' should be allowed. In order to avoid zugzwang
2187 // problems, null moves are not allowed when the side to move has very
2188 // little material left. Currently, the test is a bit too simple: Null
2189 // moves are avoided only when the side to move has only pawns left. It's
2190 // probably a good idea to avoid null moves in at least some more
2191 // complicated endgames, e.g. KQ vs KR. FIXME
2193 bool ok_to_do_nullmove(const Position &pos) {
2194 if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2200 // ok_to_prune() tests whether it is safe to forward prune a move. Only
2201 // non-tactical moves late in the move list close to the leaves are
2202 // candidates for pruning.
2204 bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2205 Square mfrom, mto, tfrom, tto;
2207 assert(move_is_ok(m));
2208 assert(threat == MOVE_NONE || move_is_ok(threat));
2209 assert(!move_promotion(m));
2210 assert(!pos.move_is_check(m));
2211 assert(!pos.move_is_capture(m));
2212 assert(!pos.move_is_passed_pawn_push(m));
2213 assert(d >= OnePly);
2215 mfrom = move_from(m);
2217 tfrom = move_from(threat);
2218 tto = move_to(threat);
2220 // Case 1: Castling moves are never pruned.
2221 if (move_is_castle(m))
2224 // Case 2: Don't prune moves which move the threatened piece
2225 if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2228 // Case 3: If the threatened piece has value less than or equal to the
2229 // value of the threatening piece, don't prune move which defend it.
2230 if ( !PruneDefendingMoves
2231 && threat != MOVE_NONE
2232 && pos.move_is_capture(threat)
2233 && ( pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2234 || pos.type_of_piece_on(tfrom) == KING)
2235 && pos.move_attacks_square(m, tto))
2238 // Case 4: Don't prune moves with good history.
2239 if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2242 // Case 5: If the moving piece in the threatened move is a slider, don't
2243 // prune safe moves which block its ray.
2244 if ( !PruneBlockingMoves
2245 && threat != MOVE_NONE
2246 && piece_is_slider(pos.piece_on(tfrom))
2247 && bit_is_set(squares_between(tfrom, tto), mto)
2255 // ok_to_use_TT() returns true if a transposition table score
2256 // can be used at a given point in search.
2258 bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2260 Value v = value_from_tt(tte->value(), ply);
2262 return ( tte->depth() >= depth
2263 || v >= Max(value_mate_in(100), beta)
2264 || v < Min(value_mated_in(100), beta))
2266 && ( (is_lower_bound(tte->type()) && v >= beta)
2267 || (is_upper_bound(tte->type()) && v < beta));
2271 // ok_to_history() returns true if a move m can be stored
2272 // in history. Should be a non capturing move nor a promotion.
2274 bool ok_to_history(const Position& pos, Move m) {
2276 return !pos.move_is_capture(m) && !move_promotion(m);
2280 // update_history() registers a good move that produced a beta-cutoff
2281 // in history and marks as failures all the other moves of that ply.
2283 void update_history(const Position& pos, Move m, Depth depth,
2284 Move movesSearched[], int moveCount) {
2286 H.success(pos.piece_on(move_from(m)), m, depth);
2288 for (int i = 0; i < moveCount - 1; i++)
2290 assert(m != movesSearched[i]);
2291 if (ok_to_history(pos, movesSearched[i]))
2292 H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2297 // update_killers() add a good move that produced a beta-cutoff
2298 // among the killer moves of that ply.
2300 void update_killers(Move m, SearchStack& ss) {
2302 if (m == ss.killers[0])
2305 for (int i = KILLER_MAX - 1; i > 0; i--)
2306 ss.killers[i] = ss.killers[i - 1];
2311 // fail_high_ply_1() checks if some thread is currently resolving a fail
2312 // high at ply 1 at the node below the first root node. This information
2313 // is used for time managment.
2315 bool fail_high_ply_1() {
2316 for(int i = 0; i < ActiveThreads; i++)
2317 if(Threads[i].failHighPly1)
2323 // current_search_time() returns the number of milliseconds which have passed
2324 // since the beginning of the current search.
2326 int current_search_time() {
2327 return get_system_time() - SearchStartTime;
2331 // nps() computes the current nodes/second count.
2334 int t = current_search_time();
2335 return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2339 // poll() performs two different functions: It polls for user input, and it
2340 // looks at the time consumed so far and decides if it's time to abort the
2345 static int lastInfoTime;
2346 int t = current_search_time();
2351 // We are line oriented, don't read single chars
2352 std::string command;
2353 if (!std::getline(std::cin, command))
2356 if (command == "quit")
2359 PonderSearch = false;
2362 else if(command == "stop")
2365 PonderSearch = false;
2367 else if(command == "ponderhit")
2370 // Print search information
2374 else if (lastInfoTime > t)
2375 // HACK: Must be a new search where we searched less than
2376 // NodesBetweenPolls nodes during the first second of search.
2379 else if (t - lastInfoTime >= 1000)
2386 if (dbg_show_hit_rate)
2387 dbg_print_hit_rate();
2389 std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2390 << " time " << t << " hashfull " << TT.full() << std::endl;
2391 lock_release(&IOLock);
2392 if (ShowCurrentLine)
2393 Threads[0].printCurrentLine = true;
2395 // Should we stop the search?
2399 bool overTime = t > AbsoluteMaxSearchTime
2400 || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2401 || ( !FailHigh && !fail_high_ply_1() && !Problem
2402 && t > 6*(MaxSearchTime + ExtraSearchTime));
2404 if ( (Iteration >= 2 && (!InfiniteSearch && overTime))
2405 || (ExactMaxTime && t >= ExactMaxTime)
2406 || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2411 // ponderhit() is called when the program is pondering (i.e. thinking while
2412 // it's the opponent's turn to move) in order to let the engine know that
2413 // it correctly predicted the opponent's move.
2416 int t = current_search_time();
2417 PonderSearch = false;
2418 if(Iteration >= 2 &&
2419 (!InfiniteSearch && (StopOnPonderhit ||
2420 t > AbsoluteMaxSearchTime ||
2421 (RootMoveNumber == 1 &&
2422 t > MaxSearchTime + ExtraSearchTime) ||
2423 (!FailHigh && !fail_high_ply_1() && !Problem &&
2424 t > 6*(MaxSearchTime + ExtraSearchTime)))))
2429 // print_current_line() prints the current line of search for a given
2430 // thread. Called when the UCI option UCI_ShowCurrLine is 'true'.
2432 void print_current_line(SearchStack ss[], int ply, int threadID) {
2433 assert(ply >= 0 && ply < PLY_MAX);
2434 assert(threadID >= 0 && threadID < ActiveThreads);
2436 if(!Threads[threadID].idle) {
2438 std::cout << "info currline " << (threadID + 1);
2439 for(int p = 0; p < ply; p++)
2440 std::cout << " " << ss[p].currentMove;
2441 std::cout << std::endl;
2442 lock_release(&IOLock);
2444 Threads[threadID].printCurrentLine = false;
2445 if(threadID + 1 < ActiveThreads)
2446 Threads[threadID + 1].printCurrentLine = true;
2450 // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2451 // while the program is pondering. The point is to work around a wrinkle in
2452 // the UCI protocol: When pondering, the engine is not allowed to give a
2453 // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2454 // We simply wait here until one of these commands is sent, and return,
2455 // after which the bestmove and pondermove will be printed (in id_loop()).
2457 void wait_for_stop_or_ponderhit() {
2458 std::string command;
2461 if(!std::getline(std::cin, command))
2464 if(command == "quit") {
2465 OpeningBook.close();
2470 else if(command == "ponderhit" || command == "stop")
2476 // idle_loop() is where the threads are parked when they have no work to do.
2477 // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2478 // object for which the current thread is the master.
2480 void idle_loop(int threadID, SplitPoint *waitSp) {
2481 assert(threadID >= 0 && threadID < THREAD_MAX);
2483 Threads[threadID].running = true;
2486 if(AllThreadsShouldExit && threadID != 0)
2489 // If we are not thinking, wait for a condition to be signaled instead
2490 // of wasting CPU time polling for work:
2491 while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2492 #if !defined(_MSC_VER)
2493 pthread_mutex_lock(&WaitLock);
2494 if(Idle || threadID >= ActiveThreads)
2495 pthread_cond_wait(&WaitCond, &WaitLock);
2496 pthread_mutex_unlock(&WaitLock);
2498 WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2502 // If this thread has been assigned work, launch a search:
2503 if(Threads[threadID].workIsWaiting) {
2504 Threads[threadID].workIsWaiting = false;
2505 if(Threads[threadID].splitPoint->pvNode)
2506 sp_search_pv(Threads[threadID].splitPoint, threadID);
2508 sp_search(Threads[threadID].splitPoint, threadID);
2509 Threads[threadID].idle = true;
2512 // If this thread is the master of a split point and all threads have
2513 // finished their work at this split point, return from the idle loop:
2514 if(waitSp != NULL && waitSp->cpus == 0)
2518 Threads[threadID].running = false;
2522 // init_split_point_stack() is called during program initialization, and
2523 // initializes all split point objects.
2525 void init_split_point_stack() {
2526 for(int i = 0; i < THREAD_MAX; i++)
2527 for(int j = 0; j < MaxActiveSplitPoints; j++) {
2528 SplitPointStack[i][j].parent = NULL;
2529 lock_init(&(SplitPointStack[i][j].lock), NULL);
2534 // destroy_split_point_stack() is called when the program exits, and
2535 // destroys all locks in the precomputed split point objects.
2537 void destroy_split_point_stack() {
2538 for(int i = 0; i < THREAD_MAX; i++)
2539 for(int j = 0; j < MaxActiveSplitPoints; j++)
2540 lock_destroy(&(SplitPointStack[i][j].lock));
2544 // thread_should_stop() checks whether the thread with a given threadID has
2545 // been asked to stop, directly or indirectly. This can happen if a beta
2546 // cutoff has occured in thre thread's currently active split point, or in
2547 // some ancestor of the current split point.
2549 bool thread_should_stop(int threadID) {
2550 assert(threadID >= 0 && threadID < ActiveThreads);
2554 if(Threads[threadID].stop)
2556 if(ActiveThreads <= 2)
2558 for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2560 Threads[threadID].stop = true;
2567 // thread_is_available() checks whether the thread with threadID "slave" is
2568 // available to help the thread with threadID "master" at a split point. An
2569 // obvious requirement is that "slave" must be idle. With more than two
2570 // threads, this is not by itself sufficient: If "slave" is the master of
2571 // some active split point, it is only available as a slave to the other
2572 // threads which are busy searching the split point at the top of "slave"'s
2573 // split point stack (the "helpful master concept" in YBWC terminology).
2575 bool thread_is_available(int slave, int master) {
2576 assert(slave >= 0 && slave < ActiveThreads);
2577 assert(master >= 0 && master < ActiveThreads);
2578 assert(ActiveThreads > 1);
2580 if(!Threads[slave].idle || slave == master)
2583 if(Threads[slave].activeSplitPoints == 0)
2584 // No active split points means that the thread is available as a slave
2585 // for any other thread.
2588 if(ActiveThreads == 2)
2591 // Apply the "helpful master" concept if possible.
2592 if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2599 // idle_thread_exists() tries to find an idle thread which is available as
2600 // a slave for the thread with threadID "master".
2602 bool idle_thread_exists(int master) {
2603 assert(master >= 0 && master < ActiveThreads);
2604 assert(ActiveThreads > 1);
2606 for(int i = 0; i < ActiveThreads; i++)
2607 if(thread_is_available(i, master))
2613 // split() does the actual work of distributing the work at a node between
2614 // several threads at PV nodes. If it does not succeed in splitting the
2615 // node (because no idle threads are available, or because we have no unused
2616 // split point objects), the function immediately returns false. If
2617 // splitting is possible, a SplitPoint object is initialized with all the
2618 // data that must be copied to the helper threads (the current position and
2619 // search stack, alpha, beta, the search depth, etc.), and we tell our
2620 // helper threads that they have been assigned work. This will cause them
2621 // to instantly leave their idle loops and call sp_search_pv(). When all
2622 // threads have returned from sp_search_pv (or, equivalently, when
2623 // splitPoint->cpus becomes 0), split() returns true.
2625 bool split(const Position &p, SearchStack *sstck, int ply,
2626 Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2627 MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2630 assert(sstck != NULL);
2631 assert(ply >= 0 && ply < PLY_MAX);
2632 assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2633 assert(!pvNode || *alpha < *beta);
2634 assert(*beta <= VALUE_INFINITE);
2635 assert(depth > Depth(0));
2636 assert(master >= 0 && master < ActiveThreads);
2637 assert(ActiveThreads > 1);
2639 SplitPoint *splitPoint;
2644 // If no other thread is available to help us, or if we have too many
2645 // active split points, don't split:
2646 if(!idle_thread_exists(master) ||
2647 Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2648 lock_release(&MPLock);
2652 // Pick the next available split point object from the split point stack:
2653 splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2654 Threads[master].activeSplitPoints++;
2656 // Initialize the split point object:
2657 splitPoint->parent = Threads[master].splitPoint;
2658 splitPoint->finished = false;
2659 splitPoint->ply = ply;
2660 splitPoint->depth = depth;
2661 splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2662 splitPoint->beta = *beta;
2663 splitPoint->pvNode = pvNode;
2664 splitPoint->dcCandidates = dcCandidates;
2665 splitPoint->bestValue = *bestValue;
2666 splitPoint->master = master;
2667 splitPoint->mp = mp;
2668 splitPoint->moves = *moves;
2669 splitPoint->cpus = 1;
2670 splitPoint->pos.copy(p);
2671 splitPoint->parentSstack = sstck;
2672 for(i = 0; i < ActiveThreads; i++)
2673 splitPoint->slaves[i] = 0;
2675 // Copy the current position and the search stack to the master thread:
2676 memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2677 Threads[master].splitPoint = splitPoint;
2679 // Make copies of the current position and search stack for each thread:
2680 for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2682 if(thread_is_available(i, master)) {
2683 memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2684 Threads[i].splitPoint = splitPoint;
2685 splitPoint->slaves[i] = 1;
2689 // Tell the threads that they have work to do. This will make them leave
2691 for(i = 0; i < ActiveThreads; i++)
2692 if(i == master || splitPoint->slaves[i]) {
2693 Threads[i].workIsWaiting = true;
2694 Threads[i].idle = false;
2695 Threads[i].stop = false;
2698 lock_release(&MPLock);
2700 // Everything is set up. The master thread enters the idle loop, from
2701 // which it will instantly launch a search, because its workIsWaiting
2702 // slot is 'true'. We send the split point as a second parameter to the
2703 // idle loop, which means that the main thread will return from the idle
2704 // loop when all threads have finished their work at this split point
2705 // (i.e. when // splitPoint->cpus == 0).
2706 idle_loop(master, splitPoint);
2708 // We have returned from the idle loop, which means that all threads are
2709 // finished. Update alpha, beta and bestvalue, and return:
2711 if(pvNode) *alpha = splitPoint->alpha;
2712 *beta = splitPoint->beta;
2713 *bestValue = splitPoint->bestValue;
2714 Threads[master].stop = false;
2715 Threads[master].idle = false;
2716 Threads[master].activeSplitPoints--;
2717 Threads[master].splitPoint = splitPoint->parent;
2718 lock_release(&MPLock);
2724 // wake_sleeping_threads() wakes up all sleeping threads when it is time
2725 // to start a new search from the root.
2727 void wake_sleeping_threads() {
2728 if(ActiveThreads > 1) {
2729 for(int i = 1; i < ActiveThreads; i++) {
2730 Threads[i].idle = true;
2731 Threads[i].workIsWaiting = false;
2733 #if !defined(_MSC_VER)
2734 pthread_mutex_lock(&WaitLock);
2735 pthread_cond_broadcast(&WaitCond);
2736 pthread_mutex_unlock(&WaitLock);
2738 for(int i = 1; i < THREAD_MAX; i++)
2739 SetEvent(SitIdleEvent[i]);
2745 // init_thread() is the function which is called when a new thread is
2746 // launched. It simply calls the idle_loop() function with the supplied
2747 // threadID. There are two versions of this function; one for POSIX threads
2748 // and one for Windows threads.
2750 #if !defined(_MSC_VER)
2752 void *init_thread(void *threadID) {
2753 idle_loop(*(int *)threadID, NULL);
2759 DWORD WINAPI init_thread(LPVOID threadID) {
2760 idle_loop(*(int *)threadID, NULL);