X-Git-Url: https://git.sesse.net/?p=stockfish;a=blobdiff_plain;f=src%2Fsearch.cpp;h=d19c9a9015423192991319e4e6b910db955c4e8e;hp=4c33d263dc6aa42f2deb812b299bec99a943367d;hb=13d1776a983c8b6b8ee2ed83ef7d2a4a5caf93a9;hpb=9ec12da028948744317db3feaf11e90441e7fe9c diff --git a/src/search.cpp b/src/search.cpp index 4c33d263..d19c9a90 100644 --- a/src/search.cpp +++ b/src/search.cpp @@ -1,17 +1,18 @@ /* - Glaurung, a UCI chess playing engine. - Copyright (C) 2004-2008 Tord Romstad + Stockfish, a UCI chess playing engine derived from Glaurung 2.1 + Copyright (C) 2004-2008 Tord Romstad (Glaurung author) + Copyright (C) 2008 Marco Costalba - Glaurung is free software: you can redistribute it and/or modify + Stockfish is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - - Glaurung is distributed in the hope that it will be useful, + + Stockfish is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - + You should have received a copy of the GNU General Public License along with this program. If not, see . */ @@ -22,7 +23,6 @@ //// #include -#include #include #include #include @@ -51,10 +51,11 @@ namespace { // root move, we store a score, a node count, and a PV (really a refutation // in the case of moves which fail low). - class RootMove { + struct RootMove { - public: RootMove(); + bool operator<(const RootMove&); // used to sort + Move move; Value score; int64_t nodes, cumulativeNodes; @@ -69,20 +70,19 @@ namespace { public: RootMoveList(Position &pos, Move searchMoves[]); - Move get_move(int moveNum) const; - Value get_move_score(int moveNum) const; - void set_move_score(int moveNum, Value score); - void set_move_nodes(int moveNum, int64_t nodes); + inline Move get_move(int moveNum) const; + inline Value get_move_score(int moveNum) const; + inline void set_move_score(int moveNum, Value score); + inline void set_move_nodes(int moveNum, int64_t nodes); void set_move_pv(int moveNum, const Move pv[]); - Move get_move_pv(int moveNum, int i) const; - int64_t get_move_cumulative_nodes(int moveNum); - int move_count() const; + inline Move get_move_pv(int moveNum, int i) const; + inline int64_t get_move_cumulative_nodes(int moveNum) const; + inline int move_count() const; Move scan_for_easy_move() const; - void sort(); + inline void sort(); void sort_multipv(int n); private: - static bool compare_root_moves(const RootMove &rm1, const RootMove &rm2); static const int MaxRootMoves = 500; RootMove moves[MaxRootMoves]; int count; @@ -153,6 +153,12 @@ namespace { Depth RazorDepth = 4*OnePly; Value RazorMargin = Value(0x300); + // Last seconds noise filtering (LSN) + bool UseLSNFiltering = false; + bool looseOnTime = false; + int LSNTime = 4 * 1000; // In milliseconds + Value LSNValue = Value(0x200); + // Extensions. Array index 0 is used at non-PV nodes, index 1 at PV nodes. Depth CheckExtension[2] = {OnePly, OnePly}; Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2}; @@ -181,7 +187,7 @@ namespace { // Time managment variables int SearchStartTime; int MaxNodes, MaxDepth; - int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime; + int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime, TimeAdvantage; Move BestRootMove, PonderMove, EasyMove; int RootMoveNumber; bool InfiniteSearch; @@ -221,7 +227,7 @@ namespace { /// Functions - void id_loop(const Position &pos, Move searchMoves[]); + Value id_loop(const Position &pos, Move searchMoves[]); Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml); Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID); @@ -240,6 +246,10 @@ namespace { bool singleReply, bool mateThreat); bool ok_to_do_nullmove(const Position &pos); bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d); + bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply); + bool ok_to_history(const Position &pos, Move m); + void update_history(const Position& pos, Move m, Depth depth, + Move movesSearched[], int moveCount); bool fail_high_ply_1(); int current_search_time(); @@ -266,7 +276,7 @@ namespace { #else DWORD WINAPI init_thread(LPVOID threadID); #endif - + } @@ -292,13 +302,13 @@ History H; // Should be made local? //// Functions //// -/// think() is the external interface to Glaurung's search, and is called when +/// think() is the external interface to Stockfish's search, and is called when /// the program receives the UCI 'go' command. It initializes various /// search-related global variables, and calls root_search() -void think(const Position &pos, bool infinite, bool ponder, int time, - int increment, int movesToGo, int maxDepth, int maxNodes, - int maxTime, Move searchMoves[]) { +void think(const Position &pos, bool infinite, bool ponder, int side_to_move, + int time[], int increment[], int movesToGo, int maxDepth, + int maxNodes, int maxTime, Move searchMoves[]) { // Look for a book move: if(!infinite && !ponder && get_option_value_bool("OwnBook")) { @@ -338,7 +348,7 @@ void think(const Position &pos, bool infinite, bool ponder, int time, TT.set_size(get_option_value_int("Hash")); if(button_was_pressed("Clear Hash")) TT.clear(); - PonderingEnabled = get_option_value_int("Ponder"); + PonderingEnabled = get_option_value_bool("Ponder"); MultiPV = get_option_value_int("MultiPV"); CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)")); @@ -353,7 +363,7 @@ void think(const Position &pos, bool infinite, bool ponder, int time, Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)")); PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)")); - PassedPawnExtension[0] = + PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)")); PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)")); @@ -391,26 +401,22 @@ void think(const Position &pos, bool infinite, bool ponder, int time, RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly; RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin")); + UseLSNFiltering = get_option_value_bool("LSN filtering"); + LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000; + LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin")); + MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly; MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point"); read_weights(pos.side_to_move()); - + int newActiveThreads = get_option_value_int("Threads"); if(newActiveThreads != ActiveThreads) { ActiveThreads = newActiveThreads; init_eval(ActiveThreads); } - // Write information to search log file: - if(UseLogFile) { - LogFile << "Searching: " << pos.to_fen() << '\n'; - LogFile << "infinite: " << infinite << " ponder: " << ponder - << " time: " << time << " increment: " << increment - << " moves to go: " << movesToGo << '\n'; - } - // Wake up sleeping threads: wake_sleeping_threads(); @@ -418,24 +424,30 @@ void think(const Position &pos, bool infinite, bool ponder, int time, assert(thread_is_available(i, 0)); // Set thinking time: + int myTime = time[side_to_move]; + int myIncrement = increment[side_to_move]; + int oppTime = time[1 - side_to_move]; + + TimeAdvantage = myTime - oppTime; + if(!movesToGo) { // Sudden death time control if(increment) { - MaxSearchTime = time / 30 + increment; - AbsoluteMaxSearchTime = Max(time / 4, increment - 100); + MaxSearchTime = myTime / 30 + myIncrement; + AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100); } else { // Blitz game without increment - MaxSearchTime = time / 40; - AbsoluteMaxSearchTime = time / 8; + MaxSearchTime = myTime / 40; + AbsoluteMaxSearchTime = myTime / 8; } } else { // (x moves) / (y minutes) if(movesToGo == 1) { - MaxSearchTime = time / 2; - AbsoluteMaxSearchTime = Min(time / 2, time - 500); + MaxSearchTime = myTime / 2; + AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500); } else { - MaxSearchTime = time / Min(movesToGo, 20); - AbsoluteMaxSearchTime = Min((4 * time) / movesToGo, time / 3); + MaxSearchTime = myTime / Min(movesToGo, 20); + AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3); } } if(PonderingEnabled) { @@ -456,13 +468,36 @@ void think(const Position &pos, bool infinite, bool ponder, int time, else NodesBetweenPolls = 30000; + + // Write information to search log file: + if(UseLogFile) { + LogFile << "Searching: " << pos.to_fen() << '\n'; + LogFile << "infinite: " << infinite << " ponder: " << ponder + << " time: " << myTime << " increment: " << myIncrement + << " moves to go: " << movesToGo << '\n'; + } + // We're ready to start thinking. Call the iterative deepening loop // function: - id_loop(pos, searchMoves); + if (!looseOnTime) + { + Value v = id_loop(pos, searchMoves); + looseOnTime = ( UseLSNFiltering + && myTime < LSNTime + && myIncrement == 0 + && v < -LSNValue); + } + else + { + looseOnTime = false; // reset for next match + while (SearchStartTime + myTime + 1000 > get_system_time()) + ; // wait here + id_loop(pos, searchMoves); // to fail gracefully + } if(UseLogFile) LogFile.close(); - + if(Quit) { OpeningBook.close(); stop_threads(); @@ -492,7 +527,7 @@ void init_threads() { lock_init(&IOLock, NULL); init_split_point_stack(); - + #if !defined(_MSC_VER) pthread_mutex_init(&WaitLock, NULL); pthread_cond_init(&WaitCond, NULL); @@ -560,7 +595,7 @@ namespace { // been consumed, the user stops the search, or the maximum search depth is // reached. - void id_loop(const Position &pos, Move searchMoves[]) { + Value id_loop(const Position &pos, Move searchMoves[]) { Position p(pos); SearchStack ss[PLY_MAX_PLUS_2]; @@ -631,6 +666,10 @@ namespace { BestMoveChangesByIteration[Iteration] * (MaxSearchTime / 2) + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3); + // If we need some more and we are in time advantage take it. + if (ExtraSearchTime > 0 && TimeAdvantage > 2 * MaxSearchTime) + ExtraSearchTime += MaxSearchTime / 2; + // Stop search if most of MaxSearchTime is consumed at the end of the // iteration. We probably don't have enough time to search the first // move at the next iteration anyway. @@ -645,7 +684,7 @@ namespace { } } - // Write PV to transposition table, in case the relevant entries have + // Write PV to transposition table, in case the relevant entries have // been overwritten during the search: TT.insert_pv(p, ss[0].pv); @@ -680,6 +719,7 @@ namespace { LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1]) << '\n'; LogFile << std::endl; } + return rml.get_move_score(0); } @@ -712,7 +752,7 @@ namespace { if(current_search_time() >= 1000) std::cout << "info currmove " << move << " currmovenumber " << i + 1 << std::endl; - + // Decide search depth for this move: ext = extension(pos, move, true, pos.move_is_check(move), false, false); newDepth = (Iteration-2)*OnePly + ext + InitialDepth; @@ -734,7 +774,7 @@ namespace { else { value = -search(pos, ss, -alpha, newDepth, 1, true, 0); if(value > alpha) { - // Fail high! Set the boolean variable FailHigh to true, and + // Fail high! Set the boolean variable FailHigh to true, and // re-search the move with a big window. The variable FailHigh is // used for time managment: We try to avoid aborting the search // prematurely during a fail high research. @@ -753,7 +793,7 @@ namespace { if(AbortSearch) break; - // Remember the node count for this move. The node counts are used to + // Remember the node count for this move. The node counts are used to // sort the root moves at the next iteration. rml.set_move_nodes(i, nodes_searched() - nodes); @@ -770,7 +810,7 @@ namespace { rml.set_move_pv(i, ss[0].pv); if(MultiPV == 1) { - // We record how often the best move has been changed in each + // We record how often the best move has been changed in each // iteration. This information is used for time managment: When // the best move changes frequently, we allocate some more time. if(i > 0) @@ -826,6 +866,7 @@ namespace { Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID) { + assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE); assert(beta > alpha && beta <= VALUE_INFINITE); assert(ply >= 0 && ply < PLY_MAX); @@ -837,185 +878,194 @@ namespace { // an instant draw, maximum ply reached, etc. Value oldAlpha = alpha; - if(AbortSearch || thread_should_stop(threadID)) - return Value(0); + if (AbortSearch || thread_should_stop(threadID)) + return Value(0); - if(depth < OnePly) - return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID); + if (depth < OnePly) + return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID); init_node(pos, ss, ply, threadID); - if(pos.is_draw()) - return VALUE_DRAW; + if (pos.is_draw()) + return VALUE_DRAW; - if(ply >= PLY_MAX - 1) - return evaluate(pos, ei, threadID); + if (ply >= PLY_MAX - 1) + return evaluate(pos, ei, threadID); // Mate distance pruning alpha = Max(value_mated_in(ply), alpha); beta = Min(value_mate_in(ply+1), beta); - if(alpha >= beta) - return alpha; + if (alpha >= beta) + return alpha; // Transposition table lookup. At PV nodes, we don't use the TT for - // pruning, but only for move ordering. - Value ttValue; - Depth ttDepth; - Move ttMove = MOVE_NONE; - ValueType ttValueType; - - TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType); - - // Internal iterative deepening. - if(UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly) { - search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID); - ttMove = ss[ply].pv[ply]; + // pruning, but only for move ordering. + const TTEntry* tte = TT.retrieve(pos); + + Move ttMove = (tte ? tte->move() : MOVE_NONE); + + // Go with internal iterative deepening if we don't have a TT move + if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly) + { + search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID); + ttMove = ss[ply].pv[ply]; } // Initialize a MovePicker object for the current position, and prepare // to search all moves: MovePicker mp = MovePicker(pos, true, ttMove, ss[ply].mateKiller, ss[ply].killer1, ss[ply].killer2, depth); + Move move, movesSearched[256]; int moveCount = 0; Value value, bestValue = -VALUE_INFINITE; Bitboard dcCandidates = mp.discovered_check_candidates(); - bool mateThreat = - MateThreatExtension[1] > Depth(0) - && pos.has_mate_threat(opposite_color(pos.side_to_move())); + bool mateThreat = MateThreatExtension[1] > Depth(0) + && pos.has_mate_threat(opposite_color(pos.side_to_move())); // Loop through all legal moves until no moves remain or a beta cutoff // occurs. - while(alpha < beta && !thread_should_stop(threadID) - && (move = mp.get_next_move()) != MOVE_NONE) { - UndoInfo u; - Depth ext, newDepth; + while ( alpha < beta + && (move = mp.get_next_move()) != MOVE_NONE + && !thread_should_stop(threadID)) + { + assert(move_is_ok(move)); + + bool fewMoves = (depth <= OnePly && mp.number_of_moves() < 4); bool singleReply = (pos.is_check() && mp.number_of_moves() == 1); bool moveIsCheck = pos.move_is_check(move, dcCandidates); bool moveIsCapture = pos.move_is_capture(move); bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move); - - assert(move_is_ok(move)); + movesSearched[moveCount++] = ss[ply].currentMove = move; - ss[ply].currentMoveCaptureValue = move_is_ep(move)? + ss[ply].currentMoveCaptureValue = move_is_ep(move) ? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move)); - // Decide the new search depth. - ext = extension(pos, move, true, moveIsCheck, singleReply, mateThreat); - newDepth = depth - OnePly + ext; + // Decide the new search depth + Depth ext = extension(pos, move, true, moveIsCheck, singleReply || fewMoves, mateThreat); + Depth newDepth = depth - OnePly + ext; - // Make and search the move. + // Make and search the move + UndoInfo u; pos.do_move(move, u, dcCandidates); - - if(moveCount == 1) - value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID); - else { - if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRPVMoves - && !moveIsCapture && !move_promotion(move) - && !moveIsPassedPawnPush && !move_is_castle(move) - && move != ss[ply].killer1 && move != ss[ply].killer2) { - ss[ply].reduction = OnePly; - value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, - threadID); + + if (moveCount == 1) // The first move in list is the PV + value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID); + else + { + // Try to reduce non-pv search depth by one ply if move seems not problematic, + // if the move fails high will be re-searched at full depth. + if ( depth >= 2*OnePly + && ext == Depth(0) + && moveCount >= LMRPVMoves + && !moveIsCapture + && !move_promotion(move) + && !moveIsPassedPawnPush + && !move_is_castle(move) + && move != ss[ply].killer1 + && move != ss[ply].killer2) + { + ss[ply].reduction = OnePly; + value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID); } - else value = alpha + 1; - if(value > alpha) { - ss[ply].reduction = Depth(0); - value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID); - if(value > alpha && value < beta) { - if(ply == 1 && RootMoveNumber == 1) - // When the search fails high at ply 1 while searching the first - // move at the root, set the flag failHighPly1. This is used for - // time managment: We don't want to stop the search early in - // such cases, because resolving the fail high at ply 1 could - // result in a big drop in score at the root. - Threads[threadID].failHighPly1 = true; - value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, - threadID); - Threads[threadID].failHighPly1 = false; + else + value = alpha + 1; // Just to trigger next condition + + if (value > alpha) // Go with full depth pv search + { + ss[ply].reduction = Depth(0); + value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID); + if (value > alpha && value < beta) + { + // When the search fails high at ply 1 while searching the first + // move at the root, set the flag failHighPly1. This is used for + // time managment: We don't want to stop the search early in + // such cases, because resolving the fail high at ply 1 could + // result in a big drop in score at the root. + if (ply == 1 && RootMoveNumber == 1) + Threads[threadID].failHighPly1 = true; + + // A fail high occurred. Re-search at full window (pv search) + value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID); + Threads[threadID].failHighPly1 = false; } } } pos.undo_move(move, u); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); - + // New best move? - if(value > bestValue) { - bestValue = value; - if(value > alpha) { - alpha = value; - update_pv(ss, ply); - if(value == value_mate_in(ply + 1)) - ss[ply].mateKiller = move; - } - // If we are at ply 1, and we are searching the first root move at - // ply 0, set the 'Problem' variable if the score has dropped a lot - // (from the computer's point of view) since the previous iteration: - if(Iteration >= 2 && - -value <= ValueByIteration[Iteration-1] - ProblemMargin) - Problem = true; + if (value > bestValue) + { + bestValue = value; + if (value > alpha) + { + alpha = value; + update_pv(ss, ply); + if (value == value_mate_in(ply + 1)) + ss[ply].mateKiller = move; + } + // If we are at ply 1, and we are searching the first root move at + // ply 0, set the 'Problem' variable if the score has dropped a lot + // (from the computer's point of view) since the previous iteration: + if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin) + Problem = true; } // Split? - if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth - && Iteration <= 99 && idle_thread_exists(threadID) - && !AbortSearch && !thread_should_stop(threadID) - && split(pos, ss, ply, &alpha, &beta, &bestValue, depth, - &moveCount, &mp, dcCandidates, threadID, true)) - break; + if ( ActiveThreads > 1 + && bestValue < beta + && depth >= MinimumSplitDepth + && Iteration <= 99 + && idle_thread_exists(threadID) + && !AbortSearch + && !thread_should_stop(threadID) + && split(pos, ss, ply, &alpha, &beta, &bestValue, depth, + &moveCount, &mp, dcCandidates, threadID, true)) + break; } // All legal moves have been searched. A special case: If there were // no legal moves, it must be mate or stalemate: - if(moveCount == 0) { - if(pos.is_check()) - return value_mated_in(ply); - else - return VALUE_DRAW; - } + if (moveCount == 0) + return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW); + + // If the search is not aborted, update the transposition table, + // history counters, and killer moves. + if (AbortSearch || thread_should_stop(threadID)) + return bestValue; + + if (bestValue <= oldAlpha) + TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER); - // If the search is not aborted, update the transposition table, - // history counters, and killer moves. This code is somewhat messy, - // and definitely needs to be cleaned up. FIXME - if(!AbortSearch && !thread_should_stop(threadID)) { - if(bestValue <= oldAlpha) - TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, - VALUE_TYPE_UPPER); - else if(bestValue >= beta) { + else if (bestValue >= beta) + { Move m = ss[ply].pv[ply]; - if(pos.square_is_empty(move_to(m)) && !move_promotion(m) && - !move_is_ep(m)) { - for(int i = 0; i < moveCount - 1; i++) - if(pos.square_is_empty(move_to(movesSearched[i])) - && !move_promotion(movesSearched[i]) - && !move_is_ep(movesSearched[i])) - H.failure(pos.piece_on(move_from(movesSearched[i])), - movesSearched[i]); - - H.success(pos.piece_on(move_from(m)), m, depth); - - if(m != ss[ply].killer1) { - ss[ply].killer2 = ss[ply].killer1; - ss[ply].killer1 = m; - } + if (ok_to_history(pos, m)) // Only non capture moves are considered + { + update_history(pos, m, depth, movesSearched, moveCount); + if (m != ss[ply].killer1) + { + ss[ply].killer2 = ss[ply].killer1; + ss[ply].killer1 = m; + } } TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER); - } - else - TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], - VALUE_TYPE_EXACT); } + else + TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT); return bestValue; } - + // search() is the search function for zero-width nodes. Value search(Position &pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID) { + assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE); assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); @@ -1024,231 +1074,241 @@ namespace { // Initialize, and make an early exit in case of an aborted search, // an instant draw, maximum ply reached, etc. - if(AbortSearch || thread_should_stop(threadID)) - return Value(0); + if (AbortSearch || thread_should_stop(threadID)) + return Value(0); - if(depth < OnePly) - return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); + if (depth < OnePly) + return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); init_node(pos, ss, ply, threadID); - if(pos.is_draw()) - return VALUE_DRAW; + if (pos.is_draw()) + return VALUE_DRAW; - if(ply >= PLY_MAX - 1) - return evaluate(pos, ei, threadID); + if (ply >= PLY_MAX - 1) + return evaluate(pos, ei, threadID); // Mate distance pruning - if(value_mated_in(ply) >= beta) - return beta; - if(value_mate_in(ply+1) < beta) - return beta-1; + if (value_mated_in(ply) >= beta) + return beta; + + if (value_mate_in(ply + 1) < beta) + return beta - 1; // Transposition table lookup - bool ttFound; - Value ttValue; - Depth ttDepth; - Move ttMove = MOVE_NONE; - ValueType ttValueType; - - ttFound = TT.retrieve(pos, &ttValue, &ttDepth, &ttMove, &ttValueType); - if(ttFound) { - ttValue = value_from_tt(ttValue, ply); - if(ttDepth >= depth - || ttValue >= Max(value_mate_in(100), beta) - || ttValue < Min(value_mated_in(100), beta)) { - if((is_lower_bound(ttValueType) && ttValue >= beta) || - (is_upper_bound(ttValueType) && ttValue < beta)) { - ss[ply].currentMove = ttMove; - return ttValue; - } - } + const TTEntry* tte = TT.retrieve(pos); + + Move ttMove = (tte ? tte->move() : MOVE_NONE); + + if (tte && ok_to_use_TT(tte, depth, beta, ply)) + { + ss[ply].currentMove = ttMove; // can be MOVE_NONE ? + return value_from_tt(tte->value(), ply); } Value approximateEval = quick_evaluate(pos); bool mateThreat = false; // Null move search - if(!pos.is_check() && allowNullmove && ok_to_do_nullmove(pos) - && approximateEval >= beta - NullMoveMargin) { - UndoInfo u; - Value nullValue; - - ss[ply].currentMove = MOVE_NULL; - pos.do_null_move(u); - nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, - threadID); - pos.undo_null_move(u); - - if(nullValue >= beta) { - if(depth >= 6 * OnePly) { // Do zugzwang verification search - Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID); - if(v >= beta) - return beta; + if ( allowNullmove + && !pos.is_check() + && ok_to_do_nullmove(pos) + && approximateEval >= beta - NullMoveMargin) + { + ss[ply].currentMove = MOVE_NULL; + + UndoInfo u; + pos.do_null_move(u); + Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID); + pos.undo_null_move(u); + + if (nullValue >= beta) + { + if (depth < 6 * OnePly) + return beta; + + // Do zugzwang verification search + Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID); + if (v >= beta) + return beta; + } else { + // The null move failed low, which means that we may be faced with + // some kind of threat. If the previous move was reduced, check if + // the move that refuted the null move was somehow connected to the + // move which was reduced. If a connection is found, return a fail + // low score (which will cause the reduced move to fail high in the + // parent node, which will trigger a re-search with full depth). + if (nullValue == value_mated_in(ply + 2)) + mateThreat = true; + + ss[ply].threatMove = ss[ply + 1].currentMove; + if ( depth < ThreatDepth + && ss[ply - 1].reduction + && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove)) + return beta - 1; } - else - return beta; - } - else { - // The null move failed low, which means that we may be faced with - // some kind of threat. If the previous move was reduced, check if - // the move that refuted the null move was somehow connected to the - // move which was reduced. If a connection is found, return a fail - // low score (which will cause the reduced move to fail high in the - // parent node, which will trigger a re-search with full depth). - if(nullValue == value_mated_in(ply+2)) - mateThreat = true; - ss[ply].threatMove = ss[ply+1].currentMove; - if(depth < ThreatDepth && ss[ply-1].reduction && - connected_moves(pos, ss[ply-1].currentMove, ss[ply].threatMove)) - return beta - 1; - } } - // Razoring: - else if(depth < RazorDepth && approximateEval < beta - RazorMargin && - evaluate(pos, ei, threadID) < beta - RazorMargin) { - Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); - if(v < beta) - return v; + // Null move search not allowed, try razoring + else if ( (approximateEval < beta - RazorMargin && depth < RazorDepth) + ||(approximateEval < beta - PawnValueMidgame && depth <= OnePly)) + { + Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); + if (v < beta) + return v; } - // Internal iterative deepening - if(UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly && - evaluate(pos, ei, threadID) >= beta - IIDMargin) { - search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID); - ttMove = ss[ply].pv[ply]; + // Go with internal iterative deepening if we don't have a TT move + if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly && + evaluate(pos, ei, threadID) >= beta - IIDMargin) + { + search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID); + ttMove = ss[ply].pv[ply]; } // Initialize a MovePicker object for the current position, and prepare // to search all moves: MovePicker mp = MovePicker(pos, false, ttMove, ss[ply].mateKiller, ss[ply].killer1, ss[ply].killer2, depth); + Move move, movesSearched[256]; int moveCount = 0; - Value value, bestValue = -VALUE_INFINITE, futilityValue = VALUE_NONE; + Value value, bestValue = -VALUE_INFINITE; Bitboard dcCandidates = mp.discovered_check_candidates(); + Value futilityValue = VALUE_NONE; bool isCheck = pos.is_check(); - bool useFutilityPruning = - UseFutilityPruning && depth < SelectiveDepth && !isCheck; + bool useFutilityPruning = UseFutilityPruning + && depth < SelectiveDepth + && !isCheck; // Loop through all legal moves until no moves remain or a beta cutoff // occurs. - while(bestValue < beta && !thread_should_stop(threadID) - && (move = mp.get_next_move()) != MOVE_NONE) { - UndoInfo u; - Depth ext, newDepth; + while ( bestValue < beta + && (move = mp.get_next_move()) != MOVE_NONE + && !thread_should_stop(threadID)) + { + assert(move_is_ok(move)); + bool singleReply = (isCheck && mp.number_of_moves() == 1); bool moveIsCheck = pos.move_is_check(move, dcCandidates); bool moveIsCapture = pos.move_is_capture(move); bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move); - assert(move_is_ok(move)); movesSearched[moveCount++] = ss[ply].currentMove = move; - // Decide the new search depth. - ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat); - newDepth = depth - OnePly + ext; + // Decide the new search depth + Depth ext = extension(pos, move, false, moveIsCheck, singleReply, mateThreat); + Depth newDepth = depth - OnePly + ext; // Futility pruning - if(useFutilityPruning && ext == Depth(0) && !moveIsCapture && - !moveIsPassedPawnPush && !move_promotion(move)) { - - if(moveCount >= 2 + int(depth) - && ok_to_prune(pos, move, ss[ply].threatMove, depth)) - continue; - - if(depth < 3 * OnePly && approximateEval < beta) { - if(futilityValue == VALUE_NONE) - futilityValue = evaluate(pos, ei, threadID) - + ((depth < 2 * OnePly)? FutilityMargin1 : FutilityMargin2); - if(futilityValue < beta) { - if(futilityValue > bestValue) - bestValue = futilityValue; - continue; + if ( useFutilityPruning + && ext == Depth(0) + && !moveIsCapture + && !moveIsPassedPawnPush + && !move_promotion(move)) + { + if ( moveCount >= 2 + int(depth) + && ok_to_prune(pos, move, ss[ply].threatMove, depth)) + continue; + + if (depth < 3 * OnePly && approximateEval < beta) + { + if (futilityValue == VALUE_NONE) + futilityValue = evaluate(pos, ei, threadID) + + (depth < 2 * OnePly ? FutilityMargin1 : FutilityMargin2); + + if (futilityValue < beta) + { + if (futilityValue > bestValue) + bestValue = futilityValue; + continue; + } } - } } - // Make and search the move. + // Make and search the move + UndoInfo u; pos.do_move(move, u, dcCandidates); - - if(depth >= 2*OnePly && ext == Depth(0) && moveCount >= LMRNonPVMoves - && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush - && !move_is_castle(move) - && move != ss[ply].killer1 && move != ss[ply].killer2) { - ss[ply].reduction = OnePly; - value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, - threadID); + + // Try to reduce non-pv search depth by one ply if move seems not problematic, + // if the move fails high will be re-searched at full depth. + if ( depth >= 2*OnePly + && ext == Depth(0) + && moveCount >= LMRNonPVMoves + && !moveIsCapture + && !move_promotion(move) + && !moveIsPassedPawnPush + && !move_is_castle(move) + && move != ss[ply].killer1 + && move != ss[ply].killer2) + { + ss[ply].reduction = OnePly; + value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID); } else - value = beta; - if(value >= beta) { - ss[ply].reduction = Depth(0); - value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID); + value = beta; // Just to trigger next condition + + if (value >= beta) // Go with full depth non-pv search + { + ss[ply].reduction = Depth(0); + value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID); } pos.undo_move(move, u); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); - + // New best move? - if(value > bestValue) { + if (value > bestValue) + { bestValue = value; - if(value >= beta) - update_pv(ss, ply); - if(value == value_mate_in(ply + 1)) - ss[ply].mateKiller = move; + if (value >= beta) + update_pv(ss, ply); + + if (value == value_mate_in(ply + 1)) + ss[ply].mateKiller = move; } // Split? - if(ActiveThreads > 1 && bestValue < beta && depth >= MinimumSplitDepth - && Iteration <= 99 && idle_thread_exists(threadID) - && !AbortSearch && !thread_should_stop(threadID) - && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount, - &mp, dcCandidates, threadID, false)) + if ( ActiveThreads > 1 + && bestValue < beta + && depth >= MinimumSplitDepth + && Iteration <= 99 + && idle_thread_exists(threadID) + && !AbortSearch + && !thread_should_stop(threadID) + && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount, + &mp, dcCandidates, threadID, false)) break; } // All legal moves have been searched. A special case: If there were // no legal moves, it must be mate or stalemate: - if(moveCount == 0) { - if(pos.is_check()) - return value_mated_in(ply); - else - return VALUE_DRAW; - } + if (moveCount == 0) + return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW); // If the search is not aborted, update the transposition table, - // history counters, and killer moves. This code is somewhat messy, - // and definitely needs to be cleaned up. FIXME - if(!AbortSearch && !thread_should_stop(threadID)) { - if(bestValue < beta) - TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, - VALUE_TYPE_UPPER); - else { + // history counters, and killer moves. + if (AbortSearch || thread_should_stop(threadID)) + return bestValue; + + if (bestValue < beta) + TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER); + else + { Move m = ss[ply].pv[ply]; - - if(pos.square_is_empty(move_to(m)) && !move_promotion(m) && - !move_is_ep(m)) { - for(int i = 0; i < moveCount - 1; i++) - if(pos.square_is_empty(move_to(movesSearched[i])) - && !move_promotion(movesSearched[i]) - && !move_is_ep(movesSearched[i])) - H.failure(pos.piece_on(move_from(movesSearched[i])), - movesSearched[i]); - H.success(pos.piece_on(move_from(m)), m, depth); - - if(m != ss[ply].killer1) { - ss[ply].killer2 = ss[ply].killer1; - ss[ply].killer1 = m; - } + if (ok_to_history(pos, m)) // Only non capture moves are considered + { + update_history(pos, m, depth, movesSearched, moveCount); + if (m != ss[ply].killer1) + { + ss[ply].killer2 = ss[ply].killer1; + ss[ply].killer1 = m; + } } TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER); - } } - return bestValue; } - + // qsearch() is the quiescence search function, which is called by the main // search function when the remaining depth is zero (or, to be more precise, @@ -1256,8 +1316,6 @@ namespace { Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID) { - Value staticValue, bestValue, value; - EvalInfo ei; assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE); assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE); @@ -1265,32 +1323,38 @@ namespace { assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); - // Initialize, and make an early exit in case of an aborted search, + EvalInfo ei; + + // Initialize, and make an early exit in case of an aborted search, // an instant draw, maximum ply reached, etc. - if(AbortSearch || thread_should_stop(threadID)) - return Value(0); + if (AbortSearch || thread_should_stop(threadID)) + return Value(0); init_node(pos, ss, ply, threadID); - if(pos.is_draw()) - return VALUE_DRAW; + if (pos.is_draw()) + return VALUE_DRAW; + + // Transposition table lookup + const TTEntry* tte = TT.retrieve(pos); + if (tte && ok_to_use_TT(tte, depth, beta, ply)) + return value_from_tt(tte->value(), ply); // Evaluate the position statically: - staticValue = evaluate(pos, ei, threadID); + Value staticValue = evaluate(pos, ei, threadID); - if(ply == PLY_MAX - 1) return staticValue; + if (ply == PLY_MAX - 1) + return staticValue; // Initialize "stand pat score", and return it immediately if it is // at least beta. - if(pos.is_check()) - bestValue = -VALUE_INFINITE; - else { - bestValue = staticValue; - if(bestValue >= beta) + Value bestValue = (pos.is_check() ? -VALUE_INFINITE : staticValue); + + if (bestValue >= beta) return bestValue; - if(bestValue > alpha) + + if (bestValue > alpha) alpha = bestValue; - } // Initialize a MovePicker object for the current position, and prepare // to search the moves. Because the depth is <= 0 here, only captures, @@ -1302,67 +1366,80 @@ namespace { Bitboard dcCandidates = mp.discovered_check_candidates(); bool isCheck = pos.is_check(); - // Loop through the moves until no moves remain or a beta cutoff + // Loop through the moves until no moves remain or a beta cutoff // occurs. - while(alpha < beta && ((move = mp.get_next_move()) != MOVE_NONE)) { - UndoInfo u; + while ( alpha < beta + && (move = mp.get_next_move()) != MOVE_NONE) + { + assert(move_is_ok(move)); + bool moveIsCheck = pos.move_is_check(move, dcCandidates); bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move); - assert(move_is_ok(move)); - moveCount++; ss[ply].currentMove = move; // Futility pruning - if(UseQSearchFutilityPruning && !isCheck && !moveIsCheck && - !move_promotion(move) && !moveIsPassedPawnPush && - beta - alpha == 1 && - pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) { - Value futilityValue = - staticValue - + Max(pos.midgame_value_of_piece_on(move_to(move)), - pos.endgame_value_of_piece_on(move_to(move))) - + FutilityMargin0 - + ei.futilityMargin; - if(futilityValue < alpha) { - if(futilityValue > bestValue) - bestValue = futilityValue; - continue; - } + if ( UseQSearchFutilityPruning + && !isCheck + && !moveIsCheck + && !move_promotion(move) + && !moveIsPassedPawnPush + && beta - alpha == 1 + && pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame) + { + Value futilityValue = staticValue + + Max(pos.midgame_value_of_piece_on(move_to(move)), + pos.endgame_value_of_piece_on(move_to(move))) + + FutilityMargin0 + + ei.futilityMargin; + + if (futilityValue < alpha) + { + if (futilityValue > bestValue) + bestValue = futilityValue; + continue; + } } // Don't search captures and checks with negative SEE values. - if(!isCheck && !move_promotion(move) && - pos.midgame_value_of_piece_on(move_from(move)) > - pos.midgame_value_of_piece_on(move_to(move)) && - pos.see(move) < 0) - continue; + if ( !isCheck + && !move_promotion(move) + && (pos.midgame_value_of_piece_on(move_from(move)) > + pos.midgame_value_of_piece_on(move_to(move))) + && pos.see(move) < 0) + continue; // Make and search the move. + UndoInfo u; pos.do_move(move, u, dcCandidates); - value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID); + Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID); pos.undo_move(move, u); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); // New best move? - if(value > bestValue) { - bestValue = value; - if(value > alpha) { - alpha = value; - update_pv(ss, ply); - } - } + if (value > bestValue) + { + bestValue = value; + if (value > alpha) + { + alpha = value; + update_pv(ss, ply); + } + } } // All legal moves have been searched. A special case: If we're in check - // and no legal moves were found, it is checkmate: - if(pos.is_check() && moveCount == 0) // Mate! - return value_mated_in(ply); + // and no legal moves were found, it is checkmate: + if (pos.is_check() && moveCount == 0) // Mate! + return value_mated_in(ply); assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE); + // Update transposition table + TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT); + return bestValue; } @@ -1374,82 +1451,97 @@ namespace { // splitting, we don't have to repeat all this work in sp_search(). We // also don't need to store anything to the hash table here: This is taken // care of after we return from the split point. - + void sp_search(SplitPoint *sp, int threadID) { + assert(threadID >= 0 && threadID < ActiveThreads); assert(ActiveThreads > 1); - + Position pos = Position(sp->pos); SearchStack *ss = sp->sstack[threadID]; Value value; Move move; - int moveCount = sp->moves; bool isCheck = pos.is_check(); - bool useFutilityPruning = - UseFutilityPruning && sp->depth < SelectiveDepth && !isCheck; + bool useFutilityPruning = UseFutilityPruning + && sp->depth < SelectiveDepth + && !isCheck; + + while ( sp->bestValue < sp->beta + && !thread_should_stop(threadID) + && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) + { + assert(move_is_ok(move)); - while(sp->bestValue < sp->beta && !thread_should_stop(threadID) - && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) { - UndoInfo u; - Depth ext, newDepth; bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates); bool moveIsCapture = pos.move_is_capture(move); bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move); - assert(move_is_ok(move)); - lock_grab(&(sp->lock)); - sp->moves++; - moveCount = sp->moves; + int moveCount = ++sp->moves; lock_release(&(sp->lock)); ss[sp->ply].currentMove = move; // Decide the new search depth. - ext = extension(pos, move, false, moveIsCheck, false, false); - newDepth = sp->depth - OnePly + ext; + Depth ext = extension(pos, move, false, moveIsCheck, false, false); + Depth newDepth = sp->depth - OnePly + ext; // Prune? - if(useFutilityPruning && ext == Depth(0) && !moveIsCapture - && !moveIsPassedPawnPush && !move_promotion(move) - && moveCount >= 2 + int(sp->depth) - && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)) + if ( useFutilityPruning + && ext == Depth(0) + && !moveIsCapture + && !moveIsPassedPawnPush + && !move_promotion(move) + && moveCount >= 2 + int(sp->depth) + && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)) continue; // Make and search the move. + UndoInfo u; pos.do_move(move, u, sp->dcCandidates); - if(ext == Depth(0) && moveCount >= LMRNonPVMoves - && !moveIsCapture && !move_promotion(move) && !moveIsPassedPawnPush - && !move_is_castle(move) - && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) { - ss[sp->ply].reduction = OnePly; - value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, - true, threadID); + + // Try to reduce non-pv search depth by one ply if move seems not problematic, + // if the move fails high will be re-searched at full depth. + if ( ext == Depth(0) + && moveCount >= LMRNonPVMoves + && !moveIsCapture + && !moveIsPassedPawnPush + && !move_promotion(move) + && !move_is_castle(move) + && move != ss[sp->ply].killer1 + && move != ss[sp->ply].killer2) + { + ss[sp->ply].reduction = OnePly; + value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID); } else - value = sp->beta; - if(value >= sp->beta) { - ss[sp->ply].reduction = Depth(0); - value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, - threadID); + value = sp->beta; // Just to trigger next condition + + if (value >= sp->beta) // Go with full depth non-pv search + { + ss[sp->ply].reduction = Depth(0); + value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID); } pos.undo_move(move, u); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); - if(thread_should_stop(threadID)) - break; - + if (thread_should_stop(threadID)) + break; + // New best move? lock_grab(&(sp->lock)); - if(value > sp->bestValue && !thread_should_stop(threadID)) { - sp->bestValue = value; - if(sp->bestValue >= sp->beta) { - sp_update_pv(sp->parentSstack, ss, sp->ply); - for(int i = 0; i < ActiveThreads; i++) - if(i != threadID && (i == sp->master || sp->slaves[i])) - Threads[i].stop = true; - sp->finished = true; + if (value > sp->bestValue && !thread_should_stop(threadID)) + { + sp->bestValue = value; + if (sp->bestValue >= sp->beta) + { + sp_update_pv(sp->parentSstack, ss, sp->ply); + for (int i = 0; i < ActiveThreads; i++) + if (i != threadID && (i == sp->master || sp->slaves[i])) + Threads[i].stop = true; + + sp->finished = true; } } lock_release(&(sp->lock)); @@ -1459,10 +1551,10 @@ namespace { // If this is the master thread and we have been asked to stop because of // a beta cutoff higher up in the tree, stop all slave threads: - if(sp->master == threadID && thread_should_stop(threadID)) - for(int i = 0; i < ActiveThreads; i++) - if(sp->slaves[i]) - Threads[i].stop = true; + if (sp->master == threadID && thread_should_stop(threadID)) + for (int i = 0; i < ActiveThreads; i++) + if (sp->slaves[i]) + Threads[i].stop = true; sp->cpus--; sp->slaves[threadID] = 0; @@ -1478,21 +1570,21 @@ namespace { // don't have to repeat all this work in sp_search_pv(). We also don't // need to store anything to the hash table here: This is taken care of // after we return from the split point. - + void sp_search_pv(SplitPoint *sp, int threadID) { + assert(threadID >= 0 && threadID < ActiveThreads); assert(ActiveThreads > 1); - + Position pos = Position(sp->pos); SearchStack *ss = sp->sstack[threadID]; Value value; Move move; - int moveCount = sp->moves; - while(sp->alpha < sp->beta && !thread_should_stop(threadID) - && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) { - UndoInfo u; - Depth ext, newDepth; + while ( sp->alpha < sp->beta + && !thread_should_stop(threadID) + && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE) + { bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates); bool moveIsCapture = pos.move_is_capture(move); bool moveIsPassedPawnPush = pos.move_is_passed_pawn_push(move); @@ -1503,74 +1595,88 @@ namespace { PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move)); lock_grab(&(sp->lock)); - sp->moves++; - moveCount = sp->moves; + int moveCount = ++sp->moves; lock_release(&(sp->lock)); ss[sp->ply].currentMove = move; - + // Decide the new search depth. - ext = extension(pos, move, true, moveIsCheck, false, false); - newDepth = sp->depth - OnePly + ext; + Depth ext = extension(pos, move, true, moveIsCheck, false, false); + Depth newDepth = sp->depth - OnePly + ext; // Make and search the move. + UndoInfo u; pos.do_move(move, u, sp->dcCandidates); - if(ext == Depth(0) && moveCount >= LMRPVMoves && !moveIsCapture - && !move_promotion(move) && !moveIsPassedPawnPush - && !move_is_castle(move) - && move != ss[sp->ply].killer1 && move != ss[sp->ply].killer2) { - ss[sp->ply].reduction = OnePly; - value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, - true, threadID); + + // Try to reduce non-pv search depth by one ply if move seems not problematic, + // if the move fails high will be re-searched at full depth. + if ( ext == Depth(0) + && moveCount >= LMRPVMoves + && !moveIsCapture + && !moveIsPassedPawnPush + && !move_promotion(move) + && !move_is_castle(move) + && move != ss[sp->ply].killer1 + && move != ss[sp->ply].killer2) + { + ss[sp->ply].reduction = OnePly; + value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID); } else - value = sp->alpha + 1; - if(value > sp->alpha) { - ss[sp->ply].reduction = Depth(0); - value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, - threadID); - if(value > sp->alpha && value < sp->beta) { - if(sp->ply == 1 && RootMoveNumber == 1) - // When the search fails high at ply 1 while searching the first - // move at the root, set the flag failHighPly1. This is used for - // time managment: We don't want to stop the search early in - // such cases, because resolving the fail high at ply 1 could - // result in a big drop in score at the root. - Threads[threadID].failHighPly1 = true; - value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, - sp->ply+1, threadID); - Threads[threadID].failHighPly1 = false; + value = sp->alpha + 1; // Just to trigger next condition + + if (value > sp->alpha) // Go with full depth non-pv search + { + ss[sp->ply].reduction = Depth(0); + value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID); + + if (value > sp->alpha && value < sp->beta) + { + // When the search fails high at ply 1 while searching the first + // move at the root, set the flag failHighPly1. This is used for + // time managment: We don't want to stop the search early in + // such cases, because resolving the fail high at ply 1 could + // result in a big drop in score at the root. + if (sp->ply == 1 && RootMoveNumber == 1) + Threads[threadID].failHighPly1 = true; + + value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID); + Threads[threadID].failHighPly1 = false; } } pos.undo_move(move, u); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); - if(thread_should_stop(threadID)) - break; - + if (thread_should_stop(threadID)) + break; + // New best move? lock_grab(&(sp->lock)); - if(value > sp->bestValue && !thread_should_stop(threadID)) { - sp->bestValue = value; - if(value > sp->alpha) { - sp->alpha = value; - sp_update_pv(sp->parentSstack, ss, sp->ply); - if(value == value_mate_in(sp->ply + 1)) - ss[sp->ply].mateKiller = move; - if(value >= sp->beta) { - for(int i = 0; i < ActiveThreads; i++) - if(i != threadID && (i == sp->master || sp->slaves[i])) - Threads[i].stop = true; - sp->finished = true; - } + if (value > sp->bestValue && !thread_should_stop(threadID)) + { + sp->bestValue = value; + if (value > sp->alpha) + { + sp->alpha = value; + sp_update_pv(sp->parentSstack, ss, sp->ply); + if (value == value_mate_in(sp->ply + 1)) + ss[sp->ply].mateKiller = move; + + if(value >= sp->beta) + { + for(int i = 0; i < ActiveThreads; i++) + if(i != threadID && (i == sp->master || sp->slaves[i])) + Threads[i].stop = true; + + sp->finished = true; + } } // If we are at ply 1, and we are searching the first root move at // ply 0, set the 'Problem' variable if the score has dropped a lot // (from the computer's point of view) since the previous iteration: - if(Iteration >= 2 && - -value <= ValueByIteration[Iteration-1] - ProblemMargin) - Problem = true; + if (Iteration >= 2 && -value <= ValueByIteration[Iteration-1] - ProblemMargin) + Problem = true; } lock_release(&(sp->lock)); } @@ -1579,16 +1685,16 @@ namespace { // If this is the master thread and we have been asked to stop because of // a beta cutoff higher up in the tree, stop all slave threads: - if(sp->master == threadID && thread_should_stop(threadID)) - for(int i = 0; i < ActiveThreads; i++) - if(sp->slaves[i]) - Threads[i].stop = true; + if (sp->master == threadID && thread_should_stop(threadID)) + for (int i = 0; i < ActiveThreads; i++) + if (sp->slaves[i]) + Threads[i].stop = true; sp->cpus--; sp->slaves[threadID] = 0; lock_release(&(sp->lock)); - } + } /// The RootMove class @@ -1598,7 +1704,19 @@ namespace { RootMove::RootMove() { nodes = cumulativeNodes = 0ULL; } - + + // RootMove::operator<() is the comparison function used when + // sorting the moves. A move m1 is considered to be better + // than a move m2 if it has a higher score, or if the moves + // have equal score but m1 has the higher node count. + + bool RootMove::operator<(const RootMove& m) { + + if (score != m.score) + return (score < m.score); + + return nodes <= m.nodes; + } /// The RootMoveList class @@ -1627,7 +1745,7 @@ namespace { SearchStack ss[PLY_MAX_PLUS_2]; moves[count].move = mlist[i].move; - moves[count].nodes = 0ULL; + moves[count].nodes = 0ULL; pos.do_move(moves[count].move, u); moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0); @@ -1643,19 +1761,19 @@ namespace { // Simple accessor methods for the RootMoveList class - Move RootMoveList::get_move(int moveNum) const { + inline Move RootMoveList::get_move(int moveNum) const { return moves[moveNum].move; } - Value RootMoveList::get_move_score(int moveNum) const { + inline Value RootMoveList::get_move_score(int moveNum) const { return moves[moveNum].score; } - void RootMoveList::set_move_score(int moveNum, Value score) { + inline void RootMoveList::set_move_score(int moveNum, Value score) { moves[moveNum].score = score; } - - void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) { + + inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) { moves[moveNum].nodes = nodes; moves[moveNum].cumulativeNodes += nodes; } @@ -1667,15 +1785,15 @@ namespace { moves[moveNum].pv[j] = MOVE_NONE; } - Move RootMoveList::get_move_pv(int moveNum, int i) const { + inline Move RootMoveList::get_move_pv(int moveNum, int i) const { return moves[moveNum].pv[i]; } - int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) { + inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const { return moves[moveNum].cumulativeNodes; } - - int RootMoveList::move_count() const { + + inline int RootMoveList::move_count() const { return count; } @@ -1690,58 +1808,44 @@ namespace { Move RootMoveList::scan_for_easy_move() const { - Value bestMoveValue = this->get_move_score(0); - for(int i = 1; i < this->move_count(); i++) - if(this->get_move_score(i) >= bestMoveValue - EasyMoveMargin) - return MOVE_NONE; - return this->get_move(0); - } + assert(count); + if (count == 1) + return get_move(0); + + // moves are sorted so just consider the best and the second one + if (get_move_score(0) > get_move_score(1) + EasyMoveMargin) + return get_move(0); + + return MOVE_NONE; + } // RootMoveList::sort() sorts the root move list at the beginning of a new // iteration. - void RootMoveList::sort() { - for(int i = 1; i < count; i++) { - RootMove rm = moves[i]; - int j; - for(j = i; j > 0 && compare_root_moves(moves[j-1], rm); j--) - moves[j] = moves[j-1]; - moves[j] = rm; - } + inline void RootMoveList::sort() { + + sort_multipv(count - 1); // all items } // RootMoveList::sort_multipv() sorts the first few moves in the root move - // list by their scores and depths. It is used to order the different PVs + // list by their scores and depths. It is used to order the different PVs // correctly in MultiPV mode. void RootMoveList::sort_multipv(int n) { - for(int i = 1; i <= n; i++) { + + for (int i = 1; i <= n; i++) + { RootMove rm = moves[i]; int j; - for(j = i; j > 0 && moves[j-1].score < rm.score; j--) - moves[j] = moves[j-1]; + for (j = i; j > 0 && moves[j-1] < rm; j--) + moves[j] = moves[j-1]; moves[j] = rm; } } - // RootMoveList::compare_root_moves() is the comparison function used by - // RootMoveList::sort when sorting the moves. A move m1 is considered to - // be better than a move m2 if it has a higher score, or if the moves have - // equal score but m1 has the higher node count. - - bool RootMoveList::compare_root_moves(const RootMove &rm1, - const RootMove &rm2) { - - if (rm1.score != rm2.score) - return (rm1.score < rm2.score); - - return rm1.nodes <= rm2.nodes; - } - - // init_search_stack() initializes a search stack at the beginning of a // new search from the root. @@ -1794,7 +1898,7 @@ namespace { // update_pv() is called whenever a search returns a value > alpha. It // updates the PV in the SearchStack object corresponding to the current // node. - + void update_pv(SearchStack ss[], int ply) { assert(ply >= 0 && ply < PLY_MAX); @@ -1885,8 +1989,8 @@ namespace { return false; } - - + + // extension() decides whether a move should be searched with normal depth, // or with extended depth. Certain classes of moves (checking moves, in // particular) are searched with bigger depth than ordinary moves. @@ -1972,7 +2076,7 @@ namespace { // Case 4: Don't prune moves with good history. if(!H.ok_to_prune(pos.piece_on(move_from(m)), m, d)) return false; - + // Case 5: If the moving piece in the threatened move is a slider, don't // prune safe moves which block its ray. if(!PruneBlockingMoves && threat != MOVE_NONE @@ -1982,12 +2086,52 @@ namespace { return true; } - + + + // ok_to_use_TT() returns true if a transposition table score + // can be used at a given point in search. + + bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) { + + Value v = value_from_tt(tte->value(), ply); + + return ( tte->depth() >= depth + || v >= Max(value_mate_in(100), beta) + || v < Min(value_mated_in(100), beta)) + + && ( (is_lower_bound(tte->type()) && v >= beta) + || (is_upper_bound(tte->type()) && v < beta)); + } + + + // ok_to_history() returns true if a move m can be stored + // in history. Should be a non capturing move. + + bool ok_to_history(const Position& pos, Move m) { + + return pos.square_is_empty(move_to(m)) + && !move_promotion(m) + && !move_is_ep(m); + } + + + // update_history() registers a good move that produced a beta-cutoff + // in history and marks as failures all the other moves of that ply. + + void update_history(const Position& pos, Move m, Depth depth, + Move movesSearched[], int moveCount) { + + H.success(pos.piece_on(move_from(m)), m, depth); + + for (int i = 0; i < moveCount - 1; i++) + if (ok_to_history(pos, movesSearched[i]) && m != movesSearched[i]) + H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]); + } // fail_high_ply_1() checks if some thread is currently resolving a fail // high at ply 1 at the node below the first root node. This information // is used for time managment. - + bool fail_high_ply_1() { for(int i = 0; i < ActiveThreads; i++) if(Threads[i].failHighPly1) @@ -2017,62 +2161,70 @@ namespace { // search. void poll() { - int t, data; - static int lastInfoTime; - t = current_search_time(); + static int lastInfoTime; + int t = current_search_time(); // Poll for input - data = Bioskey(); - if(data) { - char input[256]; - if(fgets(input, 255, stdin) == NULL) - strcpy(input, "quit\n"); - if(strncmp(input, "quit", 4) == 0) { - AbortSearch = true; - PonderSearch = false; - Quit = true; - } - else if(strncmp(input, "stop", 4) == 0) { - AbortSearch = true; - PonderSearch = false; - } - else if(strncmp(input, "ponderhit", 9) == 0) - ponderhit(); + if (Bioskey()) + { + // We are line oriented, don't read single chars + std::string command; + if (!std::getline(std::cin, command)) + command = "quit"; + + if (command == "quit") + { + AbortSearch = true; + PonderSearch = false; + Quit = true; + } + else if(command == "stop") + { + AbortSearch = true; + PonderSearch = false; + } + else if(command == "ponderhit") + ponderhit(); } - // Print search information - if(t < 1000) - lastInfoTime = 0; - else if(lastInfoTime > t) - // HACK: Must be a new search where we searched less than - // NodesBetweenPolls nodes during the first second of search. - lastInfoTime = 0; - else if(t - lastInfoTime >= 1000) { - lastInfoTime = t; - lock_grab(&IOLock); - std::cout << "info nodes " << nodes_searched() << " nps " << nps() - << " time " << t << " hashfull " << TT.full() << std::endl; - lock_release(&IOLock); - if(ShowCurrentLine) - Threads[0].printCurrentLine = true; - } + if (t < 1000) + lastInfoTime = 0; + + else if (lastInfoTime > t) + // HACK: Must be a new search where we searched less than + // NodesBetweenPolls nodes during the first second of search. + lastInfoTime = 0; + else if (t - lastInfoTime >= 1000) + { + lastInfoTime = t; + lock_grab(&IOLock); + if (dbg_show_mean) + dbg_print_mean(); + + if (dbg_show_hit_rate) + dbg_print_hit_rate(); + + std::cout << "info nodes " << nodes_searched() << " nps " << nps() + << " time " << t << " hashfull " << TT.full() << std::endl; + lock_release(&IOLock); + if (ShowCurrentLine) + Threads[0].printCurrentLine = true; + } // Should we stop the search? - if(!PonderSearch && Iteration >= 2 && - (!InfiniteSearch && (t > AbsoluteMaxSearchTime || - (RootMoveNumber == 1 && - t > MaxSearchTime + ExtraSearchTime) || - (!FailHigh && !fail_high_ply_1() && !Problem && - t > 6*(MaxSearchTime + ExtraSearchTime))))) - AbortSearch = true; + if (PonderSearch) + return; - if(!PonderSearch && ExactMaxTime && t >= ExactMaxTime) - AbortSearch = true; + bool overTime = t > AbsoluteMaxSearchTime + || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime) + || ( !FailHigh && !fail_high_ply_1() && !Problem + && t > 6*(MaxSearchTime + ExtraSearchTime)); - if(!PonderSearch && Iteration >= 3 && MaxNodes - && nodes_searched() >= MaxNodes) - AbortSearch = true; + if ( (Iteration >= 2 && (!InfiniteSearch && overTime)) + || (ExactMaxTime && t >= ExactMaxTime) + || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes)) + AbortSearch = true; } @@ -2096,7 +2248,7 @@ namespace { // print_current_line() prints the current line of search for a given // thread. Called when the UCI option UCI_ShowCurrLine is 'true'. - + void print_current_line(SearchStack ss[], int ply, int threadID) { assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); @@ -2121,14 +2273,14 @@ namespace { // "bestmove" before the GUI sends it a "stop" or "ponderhit" command. // We simply wait here until one of these commands is sent, and return, // after which the bestmove and pondermove will be printed (in id_loop()). - + void wait_for_stop_or_ponderhit() { std::string command; while(true) { if(!std::getline(std::cin, command)) command = "quit"; - + if(command == "quit") { OpeningBook.close(); stop_threads(); @@ -2140,7 +2292,7 @@ namespace { } } - + // idle_loop() is where the threads are parked when they have no work to do. // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint // object for which the current thread is the master. @@ -2148,7 +2300,7 @@ namespace { void idle_loop(int threadID, SplitPoint *waitSp) { assert(threadID >= 0 && threadID < THREAD_MAX); - Threads[threadID].running = true; + Threads[threadID].running = true; while(true) { if(AllThreadsShouldExit && threadID != 0) @@ -2206,7 +2358,7 @@ namespace { for(int i = 0; i < THREAD_MAX; i++) for(int j = 0; j < MaxActiveSplitPoints; j++) lock_destroy(&(SplitPointStack[i][j].lock)); - } + } // thread_should_stop() checks whether the thread with a given threadID has @@ -2216,7 +2368,7 @@ namespace { bool thread_should_stop(int threadID) { assert(threadID >= 0 && threadID < ActiveThreads); - + SplitPoint *sp; if(Threads[threadID].stop) @@ -2229,7 +2381,7 @@ namespace { return true; } return false; - } + } // thread_is_available() checks whether the thread with threadID "slave" is @@ -2244,7 +2396,7 @@ namespace { assert(slave >= 0 && slave < ActiveThreads); assert(master >= 0 && master < ActiveThreads); assert(ActiveThreads > 1); - + if(!Threads[slave].idle || slave == master) return false; @@ -2263,14 +2415,14 @@ namespace { return false; } - + // idle_thread_exists() tries to find an idle thread which is available as // a slave for the thread with threadID "master". bool idle_thread_exists(int master) { assert(master >= 0 && master < ActiveThreads); assert(ActiveThreads > 1); - + for(int i = 0; i < ActiveThreads; i++) if(thread_is_available(i, master)) return true; @@ -2408,20 +2560,20 @@ namespace { #endif } } - + // init_thread() is the function which is called when a new thread is // launched. It simply calls the idle_loop() function with the supplied // threadID. There are two versions of this function; one for POSIX threads // and one for Windows threads. - + #if !defined(_MSC_VER) void *init_thread(void *threadID) { idle_loop(*(int *)threadID, NULL); return NULL; } - + #else DWORD WINAPI init_thread(LPVOID threadID) {