X-Git-Url: https://git.sesse.net/?p=stockfish;a=blobdiff_plain;f=src%2Fsearch.cpp;h=98bf24a828e7174e48d4687785b7579b81e3406f;hp=c8c8d4bda672a45fba916c8ad48168e9c3bcba30;hb=77eec9f9cb50e742151273da6e4cd2847fe9ec1f;hpb=2a203d8d6fb067461db55bcf3ade747dca9492b7 diff --git a/src/search.cpp b/src/search.cpp index c8c8d4bd..98bf24a8 100644 --- a/src/search.cpp +++ b/src/search.cpp @@ -176,6 +176,9 @@ namespace { // and near frontier nodes. const Value FutilityMarginQS = Value(0x80); + // Each move futility margin is decreased + const Value IncrementalFutilityMargin = Value(0x8); + // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply const Value FutilityMargins[12] = { Value(0x100), Value(0x120), Value(0x200), Value(0x220), Value(0x250), Value(0x270), // 4 ply 4.5 ply 5 ply 5.5 ply 6 ply 6.5 ply @@ -189,9 +192,6 @@ namespace { // Remaining depth: 1 ply 1.5 ply 2 ply 2.5 ply 3 ply 3.5 ply const Value RazorApprMargins[6] = { Value(0x520), Value(0x300), Value(0x300), Value(0x300), Value(0x300), Value(0x300) }; - // The main transposition table - TranspositionTable TT; - /// Variables initialized by UCI options @@ -277,7 +277,7 @@ namespace { Value id_loop(const Position& pos, Move searchMoves[]); Value root_search(Position& pos, SearchStack ss[], RootMoveList& rml, Value alpha, Value beta); Value search_pv(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID); - Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID); + Value search(Position& pos, SearchStack ss[], Value beta, Depth depth, int ply, bool allowNullmove, int threadID, Move forbiddenMove = MOVE_NONE); Value qsearch(Position& pos, SearchStack ss[], Value alpha, Value beta, Depth depth, int ply, int threadID); void sp_search(SplitPoint* sp, int threadID); void sp_search_pv(SplitPoint* sp, int threadID); @@ -291,7 +291,6 @@ namespace { 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); void update_killers(Move m, SearchStack& ss); @@ -302,6 +301,7 @@ namespace { void ponderhit(); void print_current_line(SearchStack ss[], int ply, int threadID); void wait_for_stop_or_ponderhit(); + void init_ss_array(SearchStack ss[]); void idle_loop(int threadID, SplitPoint* waitSp); void init_split_point_stack(); @@ -310,8 +310,10 @@ namespace { bool thread_is_available(int slave, int master); bool idle_thread_exists(int master); bool split(const Position& pos, SearchStack* ss, int ply, - Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves, - MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode); + Value *alpha, Value *beta, Value *bestValue, + const Value futilityValue, const Value approximateValue, + Depth depth, int *moves, + MovePicker *mp, int master, bool pvNode); void wake_sleeping_threads(); #if !defined(_MSC_VER) @@ -327,6 +329,37 @@ namespace { //// Functions //// + +/// perft() is our utility to verify move generation is bug free. All the +/// legal moves up to given depth are generated and counted and the sum returned. + +int perft(Position& pos, Depth depth) +{ + Move move; + int sum = 0; + MovePicker mp = MovePicker(pos, MOVE_NONE, depth, H); + + // If we are at the last ply we don't need to do and undo + // the moves, just to count them. + if (depth <= OnePly) // Replace with '<' to test also qsearch + { + while (mp.get_next_move()) sum++; + return sum; + } + + // Loop through all legal moves + CheckInfo ci(pos); + while ((move = mp.get_next_move()) != MOVE_NONE) + { + StateInfo st; + pos.do_move(move, st, ci, pos.move_is_check(move, ci)); + sum += perft(pos, depth - OnePly); + pos.undo_move(move); + } + return sum; +} + + /// 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(). It returns false @@ -414,6 +447,7 @@ bool think(const Position& pos, bool infinite, bool ponder, int side_to_move, read_weights(pos.side_to_move()); + // Set the number of active threads int newActiveThreads = get_option_value_int("Threads"); if (newActiveThreads != ActiveThreads) { @@ -447,7 +481,8 @@ bool think(const Position& pos, bool infinite, bool ponder, int side_to_move, if (movesToGo == 1) { MaxSearchTime = myTime / 2; - AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500); + AbsoluteMaxSearchTime = + (myTime > 3000)? (myTime - 500) : ((myTime * 3) / 4); } else { MaxSearchTime = myTime / Min(movesToGo, 20); AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3); @@ -471,10 +506,13 @@ bool think(const Position& pos, bool infinite, bool ponder, int side_to_move, NodesBetweenPolls = Min(MaxNodes, 30000); InfiniteSearch = true; // HACK } + else if (myTime && myTime < 1000) + NodesBetweenPolls = 1000; + else if (myTime && myTime < 5000) + NodesBetweenPolls = 5000; else NodesBetweenPolls = 30000; - // Write information to search log file if (UseLogFile) LogFile << "Searching: " << pos.to_fen() << std::endl @@ -492,9 +530,9 @@ bool think(const Position& pos, bool infinite, bool ponder, int side_to_move, { Value v = id_loop(pos, searchMoves); loseOnTime = ( UseLSNFiltering - && myTime < LSNTime - && myIncrement == 0 - && v < -LSNValue); + && myTime < LSNTime + && myIncrement == 0 + && v < -LSNValue); } else { @@ -627,14 +665,19 @@ namespace { // searchMoves are verified, copied, scored and sorted RootMoveList rml(p, searchMoves); + // Print RootMoveList c'tor startup scoring to the standard output, + // so that we print information also for iteration 1. + std::cout << "info depth " << 1 << "\ninfo depth " << 1 + << " score " << value_to_string(rml.get_move_score(0)) + << " time " << current_search_time() + << " nodes " << nodes_searched() + << " nps " << nps() + << " pv " << rml.get_move(0) << "\n"; + // Initialize TT.new_search(); H.clear(); - for (int i = 0; i < 3; i++) - { - ss[i].init(i); - ss[i].initKillers(); - } + init_ss_array(ss); IterationInfo[1] = IterationInfoType(rml.get_move_score(0), rml.get_move_score(0)); Iteration = 1; @@ -822,7 +865,7 @@ namespace { Value oldAlpha = alpha; Value value; - Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move()); + CheckInfo ci(pos); // Loop through all the moves in the root move list for (int i = 0; i < rml.move_count() && !AbortSearch; i++) @@ -858,12 +901,14 @@ namespace { << " currmovenumber " << i + 1 << std::endl; // Decide search depth for this move + bool moveIsCheck = pos.move_is_check(move); + bool captureOrPromotion = pos.move_is_capture_or_promotion(move); bool dangerous; - ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous); + ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous); newDepth = (Iteration - 2) * OnePly + ext + InitialDepth; // Make the move, and search it - pos.do_move(move, st, dcCandidates); + pos.do_move(move, st, ci, moveIsCheck); if (i < MultiPV) { @@ -883,15 +928,29 @@ namespace { } else { - value = -search(pos, ss, -alpha, newDepth, 1, true, 0); + if ( newDepth >= 3*OnePly + && i >= MultiPV + LMRPVMoves + && !dangerous + && !captureOrPromotion + && !move_is_castle(move)) + { + ss[0].reduction = OnePly; + value = -search(pos, ss, -alpha, newDepth-OnePly, 1, true, 0); + } else + value = alpha + 1; // Just to trigger next condition + if (value > alpha) { - // 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. - FailHigh = true; - value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0); + value = -search(pos, ss, -alpha, newDepth, 1, true, 0); + if (value > alpha) + { + // 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. + FailHigh = true; + value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0); + } } } @@ -925,6 +984,7 @@ namespace { // Update PV rml.set_move_score(i, value); update_pv(ss, 0); + TT.extract_pv(pos, ss[0].pv, PLY_MAX); rml.set_move_pv(i, ss[0].pv); if (MultiPV == 1) @@ -938,6 +998,8 @@ namespace { // Print search information to the standard output std::cout << "info depth " << Iteration << " score " << value_to_string(value) + << ((value >= beta)? + " lowerbound" : ((value <= alpha)? " upperbound" : "")) << " time " << current_search_time() << " nodes " << nodes_searched() << " nps " << nps() @@ -949,7 +1011,10 @@ namespace { std::cout << std::endl; if (UseLogFile) - LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv) + LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, + ((value >= beta)? VALUE_TYPE_LOWER + : ((value <= alpha)? VALUE_TYPE_UPPER : VALUE_TYPE_EXACT)), + ss[0].pv) << std::endl; if (value > alpha) @@ -1001,6 +1066,17 @@ namespace { assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); + Move movesSearched[256]; + EvalInfo ei; + StateInfo st; + const TTEntry* tte; + Move ttMove, move; + Depth ext, newDepth; + Value oldAlpha, value; + bool isCheck, mateThreat, singleReply, moveIsCheck, captureOrPromotion, dangerous; + int moveCount = 0; + Value bestValue = -VALUE_INFINITE; + if (depth < OnePly) return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID); @@ -1015,13 +1091,11 @@ namespace { if (pos.is_draw()) return VALUE_DRAW; - EvalInfo ei; - if (ply >= PLY_MAX - 1) - return evaluate(pos, ei, threadID); + return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID); // Mate distance pruning - Value oldAlpha = alpha; + oldAlpha = alpha; alpha = Max(value_mated_in(ply), alpha); beta = Min(value_mate_in(ply+1), beta); if (alpha >= beta) @@ -1029,8 +1103,8 @@ namespace { // Transposition table lookup. At PV nodes, we don't use the TT for // pruning, but only for move ordering. - const TTEntry* tte = TT.retrieve(pos.get_key()); - Move ttMove = (tte ? tte->move() : MOVE_NONE); + tte = TT.retrieve(pos.get_key()); + 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) @@ -1041,16 +1115,11 @@ namespace { // Initialize a MovePicker object for the current position, and prepare // to search all moves + isCheck = pos.is_check(); + mateThreat = pos.has_mate_threat(opposite_color(pos.side_to_move())); + CheckInfo ci(pos); MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]); - Move move, movesSearched[256]; - int moveCount = 0; - Value value, bestValue = -VALUE_INFINITE; - Bitboard dcCandidates = mp.discovered_check_candidates(); - Color us = pos.side_to_move(); - bool isCheck = pos.is_check(); - bool mateThreat = pos.has_mate_threat(opposite_color(us)); - // Loop through all legal moves until no moves remain or a beta cutoff // occurs. while ( alpha < beta @@ -1059,20 +1128,18 @@ namespace { { 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); + singleReply = (isCheck && mp.number_of_evasions() == 1); + moveIsCheck = pos.move_is_check(move, ci); + captureOrPromotion = pos.move_is_capture_or_promotion(move); movesSearched[moveCount++] = ss[ply].currentMove = move; // Decide the new search depth - bool dangerous; - Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous); - Depth newDepth = depth - OnePly + ext; + ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous); + newDepth = depth - OnePly + ext; // Make and search the move - StateInfo st; - pos.do_move(move, st, dcCandidates); + pos.do_move(move, st, ci, moveIsCheck); if (moveCount == 1) // The first move in list is the PV value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID); @@ -1080,11 +1147,10 @@ namespace { { // 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 + if ( depth >= 3*OnePly && moveCount >= LMRPVMoves && !dangerous - && !moveIsCapture - && !move_is_promotion(move) + && !captureOrPromotion && !move_is_castle(move) && !move_is_killer(move, ss[ply])) { @@ -1146,8 +1212,8 @@ namespace { && idle_thread_exists(threadID) && !AbortSearch && !thread_should_stop(threadID) - && split(pos, ss, ply, &alpha, &beta, &bestValue, depth, - &moveCount, &mp, dcCandidates, threadID, true)) + && split(pos, ss, ply, &alpha, &beta, &bestValue, VALUE_NONE, VALUE_NONE, + depth, &moveCount, &mp, threadID, true)) break; } @@ -1167,13 +1233,13 @@ namespace { else if (bestValue >= beta) { BetaCounter.add(pos.side_to_move(), depth, threadID); - Move m = ss[ply].pv[ply]; - if (ok_to_history(pos, m)) // Only non capture moves are considered + move = ss[ply].pv[ply]; + if (!pos.move_is_capture_or_promotion(move)) { - update_history(pos, m, depth, movesSearched, moveCount); - update_killers(m, ss[ply]); + update_history(pos, move, depth, movesSearched, moveCount); + update_killers(move, ss[ply]); } - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m); + TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move); } else TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EXACT, depth, ss[ply].pv[ply]); @@ -1185,12 +1251,24 @@ namespace { // 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) { + int ply, bool allowNullmove, int threadID, Move forbiddenMove) { assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE); assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); + Move movesSearched[256]; + EvalInfo ei; + StateInfo st; + const TTEntry* tte; + Move ttMove, move; + Depth ext, newDepth; + Value approximateEval, nullValue, value, futilityValue, futilityValueScaled; + bool isCheck, useFutilityPruning, singleReply, moveIsCheck, captureOrPromotion, dangerous; + bool mateThreat = false; + int moveCount = 0; + Value bestValue = -VALUE_INFINITE; + if (depth < OnePly) return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); @@ -1205,10 +1283,8 @@ namespace { if (pos.is_draw()) return VALUE_DRAW; - EvalInfo ei; - if (ply >= PLY_MAX - 1) - return evaluate(pos, ei, threadID); + return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID); // Mate distance pruning if (value_mated_in(ply) >= beta) @@ -1217,9 +1293,15 @@ namespace { if (value_mate_in(ply + 1) < beta) return beta - 1; + // Position key calculation + Key posKey = pos.get_key(); + + if (forbiddenMove != MOVE_NONE) + posKey ^= Position::zobExclusion; + // Transposition table lookup - const TTEntry* tte = TT.retrieve(pos.get_key()); - Move ttMove = (tte ? tte->move() : MOVE_NONE); + tte = TT.retrieve(posKey); + ttMove = (tte ? tte->move() : MOVE_NONE); if (tte && ok_to_use_TT(tte, depth, beta, ply)) { @@ -1227,9 +1309,8 @@ namespace { return value_from_tt(tte->value(), ply); } - Value approximateEval = quick_evaluate(pos); - bool mateThreat = false; - bool isCheck = pos.is_check(); + approximateEval = quick_evaluate(pos); + isCheck = pos.is_check(); // Null move search if ( allowNullmove @@ -1241,18 +1322,20 @@ namespace { { ss[ply].currentMove = MOVE_NULL; - StateInfo st; pos.do_null_move(st); - Value nullValue = -search(pos, ss, -(beta-1), depth-4*OnePly, ply+1, false, threadID); + // Null move dynamic reduction based on depth + int R = (depth >= 5 * OnePly ? 4 : 3); + + // Null move dynamic reduction based on value + if (approximateEval - beta > PawnValueMidgame) + R++; + + nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID); pos.undo_null_move(); - if (value_is_mate(nullValue)) - { - /* Do not return unproven mates */ - } - else if (nullValue >= beta) + if (nullValue >= beta) { if (depth < 6 * OnePly) return beta; @@ -1286,8 +1369,9 @@ namespace { && ttMove == MOVE_NONE && !pos.has_pawn_on_7th(pos.side_to_move())) { - Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID); - if (v < beta - RazorMargins[int(depth) - 2]) + Value rbeta = beta - RazorMargins[int(depth) - 2]; + Value v = qsearch(pos, ss, rbeta-1, rbeta, Depth(0), ply, threadID); + if (v < rbeta) return v; } @@ -1302,14 +1386,16 @@ namespace { // Initialize a MovePicker object for the current position, and prepare // to search all moves. MovePicker mp = MovePicker(pos, ttMove, depth, H, &ss[ply]); + CheckInfo ci(pos); + futilityValue = VALUE_NONE; + useFutilityPruning = depth < SelectiveDepth && !isCheck; - Move move, movesSearched[256]; - int moveCount = 0; - Value value, bestValue = -VALUE_INFINITE; - Bitboard dcCandidates = mp.discovered_check_candidates(); - Value futilityValue = VALUE_NONE; - bool useFutilityPruning = depth < SelectiveDepth - && !isCheck; + // Avoid calling evaluate() if we already have the score in TT + if (tte && (tte->type() & VALUE_TYPE_EVAL)) + futilityValue = value_from_tt(tte->value(), ply) + FutilityMargins[int(depth) - 2]; + + // Move count pruning limit + const int MCLimit = 3 + (1 << (3*int(depth)/8)); // Loop through all legal moves until no moves remain or a beta cutoff // occurs. @@ -1319,26 +1405,76 @@ namespace { { 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); + if (move == forbiddenMove) + continue; + + singleReply = (isCheck && mp.number_of_evasions() == 1); + moveIsCheck = pos.move_is_check(move, ci); + captureOrPromotion = pos.move_is_capture_or_promotion(move); movesSearched[moveCount++] = ss[ply].currentMove = move; // Decide the new search depth - bool dangerous; - Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous); - Depth newDepth = depth - OnePly + ext; + ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, singleReply, mateThreat, &dangerous); + newDepth = depth - OnePly + ext; // Futility pruning if ( useFutilityPruning && !dangerous - && !moveIsCapture - && !move_is_promotion(move)) + && !captureOrPromotion + && move != ttMove) { + //std::cout << std::endl; + //for (int d = 2; d < 14; d++) + // std::cout << d << ", " << 64*(1+bitScanReverse32(d*d)) << std::endl; + + //std::cout << std::endl; +/* + 64*(1+bitScanReverse32(d*d)) + + 2 -> 256 - 256 + 3 -> 288 - 320 + 4 -> 512 - 384 + 5 -> 544 - 384 + 6 -> 592 - 448 + 7 -> 624 - 448 + 8 -> 672 - 512 + 9 -> 704 - 512 + 10 -> 832 - 512 + 11 -> 864 - 512 + 12 -> 928 - 576 + 13 -> 960 - 576 + + 300 + 2*(1 << (3*d/4)) + + 2 -> 256 - 304 + 3 -> 288 - 308 + 4 -> 512 - 316 + 5 -> 544 - 316 + 6 -> 592 - 332 + 7 -> 624 - 364 + 8 -> 672 - 428 + 9 -> 704 - 428 + 10 -> 832 - 556 + 11 -> 864 - 812 + 12 -> 928 - 1324 + 13 -> 960 - 1324 + + + 3 + (1 << (3*int(depth)/8)) + + 1 * onePly - > moveCount >= 4 + 2 * onePly - > moveCount >= 5 + 3 * onePly - > moveCount >= 7 + 4 * onePly - > moveCount >= 11 + 5 * onePly - > moveCount >= 11 + 6 * onePly - > moveCount >= 19 + 7 * onePly - > moveCount >= 35 +*/ // History pruning. See ok_to_prune() definition - if ( moveCount >= 2 + int(depth) - && ok_to_prune(pos, move, ss[ply].threatMove, depth)) + if ( moveCount >= MCLimit + && ok_to_prune(pos, move, ss[ply].threatMove, depth) + && bestValue > value_mated_in(PLY_MAX)) continue; // Value based pruning @@ -1346,28 +1482,28 @@ namespace { { if (futilityValue == VALUE_NONE) futilityValue = evaluate(pos, ei, threadID) - + FutilityMargins[int(depth) - 2]; + + 64*(2+bitScanReverse32(int(depth) * int(depth))); + + futilityValueScaled = futilityValue - moveCount * IncrementalFutilityMargin; - if (futilityValue < beta) + if (futilityValueScaled < beta) { - if (futilityValue > bestValue) - bestValue = futilityValue; + if (futilityValueScaled > bestValue) + bestValue = futilityValueScaled; continue; } } } // Make and search the move - StateInfo st; - pos.do_move(move, st, dcCandidates); + pos.do_move(move, st, ci, moveIsCheck); // 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 >= 3*OnePly && moveCount >= LMRNonPVMoves && !dangerous - && !moveIsCapture - && !move_is_promotion(move) + && !captureOrPromotion && !move_is_castle(move) && !move_is_killer(move, ss[ply])) { @@ -1405,15 +1541,15 @@ namespace { && idle_thread_exists(threadID) && !AbortSearch && !thread_should_stop(threadID) - && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount, - &mp, dcCandidates, threadID, false)) + && split(pos, ss, ply, &beta, &beta, &bestValue, futilityValue, approximateEval, + depth, &moveCount, &mp, 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) - return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW); + return (forbiddenMove == MOVE_NONE ? (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW) : beta - 1); // If the search is not aborted, update the transposition table, // history counters, and killer moves. @@ -1421,17 +1557,17 @@ namespace { return bestValue; if (bestValue < beta) - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE); + TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, depth, MOVE_NONE); else { BetaCounter.add(pos.side_to_move(), depth, threadID); - Move m = ss[ply].pv[ply]; - if (ok_to_history(pos, m)) // Only non capture moves are considered + move = ss[ply].pv[ply]; + if (!pos.move_is_capture_or_promotion(move)) { - update_history(pos, m, depth, movesSearched, moveCount); - update_killers(m, ss[ply]); + update_history(pos, move, depth, movesSearched, moveCount); + update_killers(move, ss[ply]); } - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, m); + TT.store(posKey, value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, depth, move); } assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE); @@ -1453,6 +1589,15 @@ namespace { assert(ply >= 0 && ply < PLY_MAX); assert(threadID >= 0 && threadID < ActiveThreads); + EvalInfo ei; + StateInfo st; + Move ttMove, move; + Value staticValue, bestValue, value, futilityValue; + bool isCheck, enoughMaterial, moveIsCheck; + const TTEntry* tte = NULL; + int moveCount = 0; + bool pvNode = (beta - alpha != 1); + // Initialize, and make an early exit in case of an aborted search, // an instant draw, maximum ply reached, etc. init_node(ss, ply, threadID); @@ -1465,8 +1610,6 @@ namespace { return VALUE_DRAW; // Transposition table lookup, only when not in PV - TTEntry* tte = NULL; - bool pvNode = (beta - alpha != 1); if (!pvNode) { tte = TT.retrieve(pos.get_key()); @@ -1477,18 +1620,16 @@ namespace { return value_from_tt(tte->value(), ply); } } - Move ttMove = (tte ? tte->move() : MOVE_NONE); + ttMove = (tte ? tte->move() : MOVE_NONE); // Evaluate the position statically - EvalInfo ei; - Value staticValue; - bool isCheck = pos.is_check(); + isCheck = pos.is_check(); ei.futilityMargin = Value(0); // Manually initialize futilityMargin if (isCheck) staticValue = -VALUE_INFINITE; - else if (tte && tte->type() == VALUE_TYPE_EVAL) + else if (tte && (tte->type() & VALUE_TYPE_EVAL)) { // Use the cached evaluation score if possible assert(ei.futilityMargin == Value(0)); @@ -1498,18 +1639,18 @@ namespace { else staticValue = evaluate(pos, ei, threadID); - if (ply == PLY_MAX - 1) - return evaluate(pos, ei, threadID); + if (ply >= PLY_MAX - 1) + return pos.is_check() ? quick_evaluate(pos) : evaluate(pos, ei, threadID); // Initialize "stand pat score", and return it immediately if it is // at least beta. - Value bestValue = staticValue; + bestValue = staticValue; if (bestValue >= beta) { // Store the score to avoid a future costly evaluation() call if (!isCheck && !tte && ei.futilityMargin == 0) - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EVAL, Depth(-127*OnePly), MOVE_NONE); + TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_EV_LO, Depth(-127*OnePly), MOVE_NONE); return bestValue; } @@ -1521,11 +1662,8 @@ namespace { // to search the moves. Because the depth is <= 0 here, only captures, // queen promotions and checks (only if depth == 0) will be generated. MovePicker mp = MovePicker(pos, ttMove, depth, H); - Move move; - int moveCount = 0; - Bitboard dcCandidates = mp.discovered_check_candidates(); - Color us = pos.side_to_move(); - bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame; + CheckInfo ci(pos); + enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame; // Loop through the moves until no moves remain or a beta cutoff // occurs. @@ -1537,20 +1675,23 @@ namespace { moveCount++; ss[ply].currentMove = move; + moveIsCheck = pos.move_is_check(move, ci); + // Futility pruning if ( enoughMaterial && !isCheck && !pvNode + && !moveIsCheck + && move != ttMove && !move_is_promotion(move) - && !pos.move_is_check(move, dcCandidates) && !pos.move_is_passed_pawn_push(move)) { - Value futilityValue = staticValue - + Max(pos.midgame_value_of_piece_on(move_to(move)), - pos.endgame_value_of_piece_on(move_to(move))) - + (move_is_ep(move) ? PawnValueEndgame : Value(0)) - + FutilityMarginQS - + ei.futilityMargin; + futilityValue = staticValue + + Max(pos.midgame_value_of_piece_on(move_to(move)), + pos.endgame_value_of_piece_on(move_to(move))) + + (move_is_ep(move) ? PawnValueEndgame : Value(0)) + + FutilityMarginQS + + ei.futilityMargin; if (futilityValue < alpha) { @@ -1562,14 +1703,14 @@ namespace { // Don't search captures and checks with negative SEE values if ( !isCheck + && move != ttMove && !move_is_promotion(move) && pos.see_sign(move) < 0) continue; - // Make and search the move. - StateInfo st; - pos.do_move(move, st, dcCandidates); - Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID); + // Make and search the move + pos.do_move(move, st, ci, moveIsCheck); + value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID); pos.undo_move(move); assert(value > -VALUE_INFINITE && value < VALUE_INFINITE); @@ -1588,25 +1729,29 @@ namespace { // 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! + if (!moveCount && pos.is_check()) // Mate! return value_mated_in(ply); assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE); // Update transposition table - Move m = ss[ply].pv[ply]; + move = ss[ply].pv[ply]; if (!pvNode) { + // If bestValue isn't changed it means it is still the static evaluation of + // the node, so keep this info to avoid a future costly evaluation() call. + ValueType type = (bestValue == staticValue && !ei.futilityMargin ? VALUE_TYPE_EV_UP : VALUE_TYPE_UPPER); Depth d = (depth == Depth(0) ? Depth(0) : Depth(-1)); + if (bestValue < beta) - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_UPPER, d, MOVE_NONE); + TT.store(pos.get_key(), value_to_tt(bestValue, ply), type, d, MOVE_NONE); else - TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, m); + TT.store(pos.get_key(), value_to_tt(bestValue, ply), VALUE_TYPE_LOWER, d, move); } // Update killers only for good check moves - if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered - update_killers(m, ss[ply]); + if (alpha >= beta && !pos.move_is_capture_or_promotion(move)) + update_killers(move, ss[ply]); return bestValue; } @@ -1626,6 +1771,7 @@ namespace { assert(ActiveThreads > 1); Position pos = Position(sp->pos); + CheckInfo ci(pos); SearchStack* ss = sp->sstack[threadID]; Value value; Move move; @@ -1639,8 +1785,8 @@ namespace { { assert(move_is_ok(move)); - bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates); - bool moveIsCapture = pos.move_is_capture(move); + bool moveIsCheck = pos.move_is_check(move, ci); + bool captureOrPromotion = pos.move_is_capture_or_promotion(move); lock_grab(&(sp->lock)); int moveCount = ++sp->moves; @@ -1650,28 +1796,53 @@ namespace { // Decide the new search depth. bool dangerous; - Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous); + Depth ext = extension(pos, move, false, captureOrPromotion, moveIsCheck, false, false, &dangerous); Depth newDepth = sp->depth - OnePly + ext; // Prune? if ( useFutilityPruning && !dangerous - && !moveIsCapture - && !move_is_promotion(move) - && moveCount >= 2 + int(sp->depth) - && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth)) - continue; + && !captureOrPromotion) + { + // History pruning. See ok_to_prune() definition + if ( moveCount >= 2 + int(sp->depth) + && ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth) + && sp->bestValue > value_mated_in(PLY_MAX)) + continue; + + // Value based pruning + if (sp->approximateEval < sp->beta) + { + if (sp->futilityValue == VALUE_NONE) + { + EvalInfo ei; + sp->futilityValue = evaluate(pos, ei, threadID) + + FutilityMargins[int(sp->depth) - 2]; + } + + if (sp->futilityValue < sp->beta) + { + if (sp->futilityValue > sp->bestValue) // Less then 1% of cases + { + lock_grab(&(sp->lock)); + if (sp->futilityValue > sp->bestValue) + sp->bestValue = sp->futilityValue; + lock_release(&(sp->lock)); + } + continue; + } + } + } // Make and search the move. StateInfo st; - pos.do_move(move, st, sp->dcCandidates); + pos.do_move(move, st, ci, moveIsCheck); // 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 ( !dangerous && moveCount >= LMRNonPVMoves - && !moveIsCapture - && !move_is_promotion(move) + && !captureOrPromotion && !move_is_castle(move) && !move_is_killer(move, ss[sp->ply])) { @@ -1694,21 +1865,24 @@ namespace { break; // New best move? - lock_grab(&(sp->lock)); - if (value > sp->bestValue && !thread_should_stop(threadID)) + if (value > sp->bestValue) // Less then 2% of cases { - sp->bestValue = value; - if (sp->bestValue >= sp->beta) + lock_grab(&(sp->lock)); + if (value > sp->bestValue && !thread_should_stop(threadID)) { - 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->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; - } + sp->finished = true; + } + } + lock_release(&(sp->lock)); } - lock_release(&(sp->lock)); } lock_grab(&(sp->lock)); @@ -1741,6 +1915,7 @@ namespace { assert(ActiveThreads > 1); Position pos = Position(sp->pos); + CheckInfo ci(pos); SearchStack* ss = sp->sstack[threadID]; Value value; Move move; @@ -1749,8 +1924,8 @@ namespace { && !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 moveIsCheck = pos.move_is_check(move, ci); + bool captureOrPromotion = pos.move_is_capture_or_promotion(move); assert(move_is_ok(move)); @@ -1762,19 +1937,18 @@ namespace { // Decide the new search depth. bool dangerous; - Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous); + Depth ext = extension(pos, move, true, captureOrPromotion, moveIsCheck, false, false, &dangerous); Depth newDepth = sp->depth - OnePly + ext; // Make and search the move. StateInfo st; - pos.do_move(move, st, sp->dcCandidates); + pos.do_move(move, st, ci, moveIsCheck); // 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 ( !dangerous && moveCount >= LMRPVMoves - && !moveIsCapture - && !move_is_promotion(move) + && !captureOrPromotion && !move_is_castle(move) && !move_is_killer(move, ss[sp->ply])) { @@ -1915,15 +2089,15 @@ namespace { bool includeAllMoves = (searchMoves[0] == MOVE_NONE); // Generate all legal moves - int lm_count = generate_legal_moves(pos, mlist); + MoveStack* last = generate_moves(pos, mlist); // Add each move to the moves[] array - for (int i = 0; i < lm_count; i++) + for (MoveStack* cur = mlist; cur != last; cur++) { bool includeMove = includeAllMoves; for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++) - includeMove = (searchMoves[k] == mlist[i].move); + includeMove = (searchMoves[k] == cur->move); if (!includeMove) continue; @@ -1931,8 +2105,9 @@ namespace { // Find a quick score for the move StateInfo st; SearchStack ss[PLY_MAX_PLUS_2]; + init_ss_array(ss); - moves[count].move = mlist[i].move; + moves[count].move = cur->move; pos.do_move(moves[count].move, st); moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE, Depth(0), 1, 0); pos.undo_move(moves[count].move); @@ -2103,7 +2278,9 @@ namespace { // the second move is assumed to be a move from the current position. bool connected_moves(const Position& pos, Move m1, Move m2) { + Square f1, t1, f2, t2; + Piece p; assert(move_is_ok(m1)); assert(move_is_ok(m2)); @@ -2129,31 +2306,32 @@ namespace { return true; // Case 4: The destination square for m2 is attacked by the moving piece in m1 - if (pos.piece_attacks_square(pos.piece_on(t1), t1, t2)) + p = pos.piece_on(t1); + if (bit_is_set(pos.attacks_from(p, t1), t2)) return true; // Case 5: Discovered check, checking piece is the piece moved in m1 - if ( piece_is_slider(pos.piece_on(t1)) + if ( piece_is_slider(p) && bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2) - && !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())), t2)) + && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2)) { Bitboard occ = pos.occupied_squares(); Color us = pos.side_to_move(); Square ksq = pos.king_square(us); clear_bit(&occ, f2); - if (pos.type_of_piece_on(t1) == BISHOP) + if (type_of_piece(p) == BISHOP) { if (bit_is_set(bishop_attacks_bb(ksq, occ), t1)) return true; } - else if (pos.type_of_piece_on(t1) == ROOK) + else if (type_of_piece(p) == ROOK) { if (bit_is_set(rook_attacks_bb(ksq, occ), t1)) return true; } else { - assert(pos.type_of_piece_on(t1) == QUEEN); + assert(type_of_piece(p) == QUEEN); if (bit_is_set(queen_attacks_bb(ksq, occ), t1)) return true; } @@ -2195,38 +2373,42 @@ namespace { // extended, as example because the corresponding UCI option is set to zero, // the move is marked as 'dangerous' so, at least, we avoid to prune it. - Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check, - bool singleReply, bool mateThreat, bool* dangerous) { + Depth extension(const Position& pos, Move m, bool pvNode, bool captureOrPromotion, + bool check, bool singleReply, bool mateThreat, bool* dangerous) { assert(m != MOVE_NONE); Depth result = Depth(0); - *dangerous = check || singleReply || mateThreat; + *dangerous = check | singleReply | mateThreat; - if (check) - result += CheckExtension[pvNode]; + if (*dangerous) + { + if (check) + result += CheckExtension[pvNode]; - if (singleReply) - result += SingleReplyExtension[pvNode]; + if (singleReply) + result += SingleReplyExtension[pvNode]; - if (mateThreat) - result += MateThreatExtension[pvNode]; + if (mateThreat) + result += MateThreatExtension[pvNode]; + } if (pos.type_of_piece_on(move_from(m)) == PAWN) { - if (pos.move_is_pawn_push_to_7th(m)) + Color c = pos.side_to_move(); + if (relative_rank(c, move_to(m)) == RANK_7) { result += PawnPushTo7thExtension[pvNode]; *dangerous = true; } - if (pos.move_is_passed_pawn_push(m)) + if (pos.pawn_is_passed(c, move_to(m))) { result += PassedPawnExtension[pvNode]; *dangerous = true; } } - if ( capture + if ( captureOrPromotion && pos.type_of_piece_on(move_to(m)) != PAWN && ( pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) - pos.midgame_value_of_piece_on(move_to(m)) == Value(0)) @@ -2238,7 +2420,7 @@ namespace { } if ( pvNode - && capture + && captureOrPromotion && pos.type_of_piece_on(move_to(m)) != PAWN && pos.see_sign(m) >= 0) { @@ -2272,9 +2454,8 @@ namespace { assert(move_is_ok(m)); assert(threat == MOVE_NONE || move_is_ok(threat)); - assert(!move_is_promotion(m)); assert(!pos.move_is_check(m)); - assert(!pos.move_is_capture(m)); + assert(!pos.move_is_capture_or_promotion(m)); assert(!pos.move_is_passed_pawn_push(m)); assert(d >= OnePly); @@ -2336,15 +2517,6 @@ namespace { } - // ok_to_history() returns true if a move m can be stored - // in history. Should be a non capturing move nor a promotion. - - bool ok_to_history(const Position& pos, Move m) { - - return !pos.move_is_capture(m) && !move_is_promotion(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. @@ -2356,7 +2528,7 @@ namespace { for (int i = 0; i < moveCount - 1; i++) { assert(m != movesSearched[i]); - if (ok_to_history(pos, movesSearched[i])) + if (!pos.move_is_capture_or_promotion(movesSearched[i])) H.failure(pos.piece_on(move_from(movesSearched[i])), move_to(movesSearched[i])); } } @@ -2376,6 +2548,7 @@ namespace { ss.killers[0] = m; } + // 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. @@ -2522,6 +2695,18 @@ namespace { } + // init_ss_array() does a fast reset of the first entries of a SearchStack array + + void init_ss_array(SearchStack ss[]) { + + for (int i = 0; i < 3; i++) + { + ss[i].init(i); + ss[i].initKillers(); + } + } + + // wait_for_stop_or_ponderhit() is called when the maximum depth is reached // while the program is pondering. The point is to work around a wrinkle in // the UCI protocol: When pondering, the engine is not allowed to give a @@ -2699,8 +2884,9 @@ namespace { // splitPoint->cpus becomes 0), split() returns true. bool split(const Position& p, SearchStack* sstck, int ply, - Value* alpha, Value* beta, Value* bestValue, Depth depth, int* moves, - MovePicker* mp, Bitboard dcCandidates, int master, bool pvNode) { + Value* alpha, Value* beta, Value* bestValue, const Value futilityValue, + const Value approximateEval, Depth depth, int* moves, + MovePicker* mp, int master, bool pvNode) { assert(p.is_ok()); assert(sstck != NULL); @@ -2737,8 +2923,9 @@ namespace { splitPoint->alpha = pvNode? *alpha : (*beta - 1); splitPoint->beta = *beta; splitPoint->pvNode = pvNode; - splitPoint->dcCandidates = dcCandidates; splitPoint->bestValue = *bestValue; + splitPoint->futilityValue = futilityValue; + splitPoint->approximateEval = approximateEval; splitPoint->master = master; splitPoint->mp = mp; splitPoint->moves = *moves;