Files

1115 lines
36 KiB
C++

#include "search.h"
#include "movegen.h"
#include <algorithm>
#include <cmath>
#include "datagen.h"
#include "benchmark.h"
#include "types.h"
#include "tunables.h"
#include "movepicker.h"
#include "wdl.h"
#include "termcolor.hpp"
#include <iomanip>
namespace SEARCH {
static WDLTriplet GetRoundedWDL(int score, Board& board) {
WDLTriplet wdl = getWDL(score, board);
wdl.wins = (wdl.wins + 5) / 10;
wdl.losses = (wdl.losses + 5) / 10;
wdl.draws = 100 - wdl.wins - wdl.losses;
if (wdl.draws < 0) {
if (wdl.wins >= wdl.losses) {
wdl.wins += wdl.draws;
} else {
wdl.losses += wdl.draws;
}
wdl.draws = 0;
}
return wdl;
}
void InitLMRTable() {
for (int i = 0; i < 2; i++) {
const double base = i ? lmrBaseQuiet : lmrBaseNoisy;
const double divisor = i ? lmrDivisorQuiet : lmrDivisorNoisy;
for (int depth = 0; depth <= MAX_DEPTH; depth++) {
for (int move = 0; move < MAX_MOVES; move++) {
if (depth == 0 || move == 0) {
lmrTable[i][depth][move] = 0;
} else {
lmrTable[i][depth][move] = std::floor(base + std::log(depth) * std::log(move) / divisor);
}
}
}
}
}
#ifdef TUNING
void InitSEEPieceValues() {
SEEPieceValues = {
seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0
};
}
void RefreshTunableCaches() {
InitLMRTable();
InitSEEPieceValues();
}
#endif
int16_t ContHistory::GetNPly(Board& board, Move& move, SearchContext* ctx, int ply, int n) {
int prevType = ctx->ss[ply-n].pieceType;
int prevTo = ctx->ss[ply-n].moveTo;
int pieceType = board.GetPieceType(move.MoveFrom());
int to = move.MoveTo();
bool otherColor = ctx->ss[ply-n].side;
return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to];
}
static int AdjustEval(Board &board, SearchContext* ctx, int eval) {
int corrhist = ctx->corrhist.GetAllHist(board);
int mateFound = MATE_SCORE - MAX_DEPTH;
int adjusted = eval + corrhist / CORRHIST_GRAIN;
const int scaleNumerator = std::max(0, fiftyMoveScaleBase - board.halfMoves);
adjusted = adjusted * scaleNumerator / fiftyMoveScaleBase;
return std::clamp(adjusted, -mateFound + 1, mateFound - 1);
}
static bool IsTwoFold(Board &board, SearchContext* ctx) {
for (int i = 0; i < board.positionIndex; i++) {
if (ctx->positionHistory[i] == board.hashKey) {
return true;
}
}
return false;
}
static bool IsFifty(Board &board) {
return (board.halfMoves >= 100);
}
static bool IsInsuffMat(Board &board) {
return (board.occupied.PopCount() <= 3
&& !(board.pieces[Pawn] | board.pieces[Queen] | board.pieces[Rook]));
}
bool IsDraw(Board &board, SearchContext* ctx) {
return IsFifty(board) || IsInsuffMat(board) || IsTwoFold(board, ctx);
}
template <bool isPV>
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, bool improving, bool corrplexity, bool ttpv, bool ttpvFailLow, SearchContext* ctx) {
int reduction = 0;
reduction = lmrTable[move.IsQuiet()][depth][moveSeen] * 1024;
if (cutnode)
reduction += lmrCutnode;
if constexpr (isPV)
reduction -= lmrIsPV;
if (!improving)
reduction += lmrImproving;
if (corrplexity)
reduction -= lmrCorrplexity;
if (ttpv)
reduction -= lmrTTPV;
if (ttpvFailLow)
reduction += lmrTTPVFailLow;
int historyReduction = 0;
if (move.IsQuiet()) {
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom());
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo());
historyReduction = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()][sourceThreatened][targetThreatened];
if (ply > 0) {
historyReduction += ctx->conthist.GetNPly(board, move, ctx, ply, 1);
if (ply > 1)
historyReduction += ctx->conthist.GetNPly(board, move, ctx, ply, 2);
}
} else if (move.IsCapture()) {
int attackerType = board.GetPieceType(move.MoveFrom());
int targetType = board.GetPieceType(move.MoveTo());
if (move.GetFlags() == epCapture) {
targetType = Pawn;
}
historyReduction = ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()];
}
historyReduction = historyReduction / lmrHistoryDivisor;
reduction -= historyReduction * 1024;
reduction /= 1024;
return std::clamp(reduction, -1, depth - 1);
}
bool SEE(Board& board, Move& move, int threshold) {
int from = move.MoveFrom();
int to = move.MoveTo();
int flags = move.GetFlags();
int nextVictim = board.GetPieceType(from);
if (move.IsPromo()) {
nextVictim = move.GetPromoPiece();
}
int balance = MoveEstimatedValue(board, move) - threshold;
if (balance < 0) return 0;
balance -= SEEPieceValues[nextVictim];
if (balance >= 0) return 1;
Bitboard bishops = board.pieces[Bishop] | board.pieces[Queen];
Bitboard rooks = board.pieces[Rook] | board.pieces[Queen];
Bitboard occupied = board.occupied;
occupied.PopBit(from);
occupied.SetBit(to);
if (flags == epCapture)
occupied.SetBit(board.enPassantTarget);
Bitboard attackers = board.AttacksTo(to, occupied) & occupied;
bool color = !board.sideToMove;
while (true) {
Bitboard myAttackers = attackers & board.colors[color];
if (!myAttackers) break;
for (nextVictim = Pawn; nextVictim <= Queen; nextVictim++) {
if (myAttackers & board.pieces[nextVictim])
break;
}
occupied.PopBit(Bitboard(myAttackers & board.pieces[nextVictim]).getLS1BIndex());
if (nextVictim == Pawn || nextVictim == Bishop || nextVictim == Queen)
attackers |= MOVEGEN::getBishopAttack(to, occupied) & bishops;
if (nextVictim == Rook || nextVictim == Queen)
attackers |= MOVEGEN::getRookAttack(to, occupied) & rooks;
attackers &= occupied;
color = !color;
balance = -balance - 1 - SEEPieceValues[nextVictim];
if (balance >= 0) {
if (nextVictim == King && (attackers & board.colors[color]))
color = !color;
break;
}
}
return board.sideToMove != color;
}
template <searchMode mode>
static bool ShouldStop(SearchContext* ctx) {
if constexpr (mode == normal) {
if (ctx->nodes % 1024 == 0) {
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
searchStopped.store(true, std::memory_order_relaxed);
return true;
}
}
} else if constexpr (mode == nodesMode) {
if (ctx->nodes > ctx->nodesToGo) {
searchStopped.store(true, std::memory_order_relaxed);
return true;
}
} else if constexpr (mode == datagen) {
if (ctx->nodes > DATAGEN::HARD_NODES) {
searchStopped.store(true, std::memory_order_relaxed);
return true;
}
}
return false;
}
static bool IsDecisive(int score) {
return std::abs(score) > WIN_SCORE;
}
static bool IsLoss(int score) {
return score < -WIN_SCORE;
}
template <searchMode mode>
static inline int StaticEval(Board& board, SearchContext* ctx, int ply) {
board.UpdateAccumulator(ctx->accStack, ply);
#ifdef ACC_VERIFY
{
ACC::AccumulatorPair ref;
board.RefreshAccumulator(ref);
if (ref.white != ctx->accStack.cur[ply]->white || ref.black != ctx->accStack.cur[ply]->black) {
std::cerr << "ACC MISMATCH ply " << ply << " fen " << board.GetFen() << std::endl;
std::abort();
}
}
#endif
return NNUE::net.Evaluate(board, *ctx->accStack.cur[ply], mode == datagen);
}
template <bool isPV, searchMode mode>
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) {
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return StaticEval<mode>(board, ctx, ply);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
int bestScore = AdjustEval(board, ctx, StaticEval<mode>(board, ctx, ply));
ctx->ss[ply].eval = bestScore;
TTEntry entry;
bool ttHit = false;
entry = ctx->TT->GetEntry(board.hashKey);
if (entry.hashKey == PackHashKey(board.hashKey) && entry.depth > 0) {
ttHit = true;
switch (entry.nodeType) {
case PV:
return entry.score;
case CutNode:
if (entry.score >= beta)
return entry.score;
break;
case AllNode:
if (entry.score <= alpha)
return entry.score;
break;
}
}
const bool ttpv = isPV | entry.ttpv;
if (ttHit) {
switch (entry.nodeType) {
case PV:
bestScore = entry.score;
break;
case CutNode:
if (entry.score > bestScore)
bestScore = entry.score;
break;
case AllNode:
if (entry.score < bestScore)
bestScore = entry.score;
break;
}
}
if (bestScore >= beta) {
return bestScore;
}
if (alpha < bestScore) {
alpha = bestScore;
}
const int fpScore = bestScore + qsFPMargin;
MovePicker<Noisy> mp(board, ctx, ply, entry.bestMove);
SearchResults results;
int nodeType = AllNode;
const bool inCheck = board.InCheck();
Move currMove;
while ((currMove = mp.Next())) {
if (!IsLoss(bestScore)) {
if (!inCheck && currMove.IsCapture() &&
fpScore <= alpha && !SEE(board, currMove, 1)) {
bestScore = std::max(bestScore, fpScore);
continue;
}
if (!SEE(board, currMove, seeQsThreshold))
continue;
}
if (!board.IsLegal(currMove)) continue;
Board copy = board;
copy.MakeMove(currMove);
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
ctx->TT->PrefetchEntry(copy.hashKey);
int score = -Quiescence<isPV, mode>(copy, -beta, -alpha, ply + 1, ctx).score;
if (score >= beta) {
if (searchStopped.load(std::memory_order_relaxed)) return 0;
ctx->TT->WriteEntry(board.hashKey, 0, score, CutNode, currMove, ttpv);
return score;
}
bestScore = std::max(score, bestScore);
if (score > alpha) {
nodeType = PV;
alpha = score;
results.bestMove = currMove;
}
}
results.score = bestScore;
if (searchStopped.load(std::memory_order_relaxed)) return 0;
ctx->TT->WriteEntry(board.hashKey, 0, results.score, nodeType, results.bestMove, ttpv);
return results;
}
template <bool isPV, searchMode mode>
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext* ctx, bool cutnode) {
if (ShouldStop<mode>(ctx)) return 0;
if (ply + 1 >= MAX_DEPTH)
return StaticEval<mode>(board, ctx, ply);
if (ply > ctx->seldepth)
ctx->seldepth = ply;
ctx->pvLine.SetLength(ply);
if (ply && (IsDraw(board, ctx))) return 0;
TTEntry entry;
if (!ctx->excluded)
entry = ctx->TT->GetEntry(board.hashKey);
const bool ttHit = entry.hashKey == PackHashKey(board.hashKey) && entry.depth >= depth;
const bool ttpv = isPV | entry.ttpv;
if constexpr (!isPV) {
if (ttHit) {
if (((entry.nodeType == PV) ||
(entry.nodeType == AllNode && entry.score <= alpha) ||
(entry.nodeType == CutNode && entry.score >= beta))) {
return SearchResults(entry.score, entry.bestMove);
}
}
}
if (depth <= 0) return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx);
int rawEval = StaticEval<mode>(board, ctx, ply);
const int staticEval = AdjustEval(board, ctx, rawEval);
ctx->ss[ply].eval = staticEval;
int ttAdjustedEval = staticEval;
const bool inCheck = board.InCheck();
if (!ctx->excluded && !inCheck && ttHit &&
((entry.nodeType == PV) ||
(entry.nodeType == AllNode && entry.score <= staticEval) ||
(entry.nodeType == CutNode && entry.score >= staticEval))) {
ttAdjustedEval = entry.score;
}
bool corrplexity = std::abs(rawEval - staticEval) > 70;
const bool improving = [&]
{
if (inCheck)
return false;
if (ply > 1 && ctx->ss[ply - 2].eval != ScoreNone)
return staticEval > ctx->ss[ply - 2].eval;
if (ply > 3 && ctx->ss[ply - 4].eval != ScoreNone)
return staticEval > ctx->ss[ply - 4].eval;
return true;
}();
if (!inCheck && !ctx->excluded) {
if (ply) {
int margin = rfpBase + rfpMargin * (depth - improving);
if (!ttpv && ttAdjustedEval - margin >= beta && depth < 7) {
return !IsDecisive(ttAdjustedEval) && !IsDecisive(beta)
? ((ttAdjustedEval + beta) / 2)
: ttAdjustedEval;
}
if (!isPV && depth <= 3 && staticEval + razoringScalar * depth < alpha && entry.nodeType != CutNode) {
return Quiescence<isPV, mode>(board, alpha, beta, ply, ctx).score;
}
if (ply > ctx->minNmpPly && ttAdjustedEval >= beta + nmpBetaMargin) {
if (depth > 1 && !board.InPossibleZug()) {
Board copy = board;
copy.MakeMove(Move());
const int reduction = 4 + improving + depth / 3 + entry.bestMove.IsCapture();
ctx->TT->PrefetchEntry(copy.hashKey);
int score = -PVS<false, mode>(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score;
if (searchStopped.load(std::memory_order_relaxed)) return 0;
if (score >= beta) {
if (depth <= 14 || ctx->minNmpPly > 0) {
return score > MATE_SCORE - MAX_DEPTH ? beta : score;
}
ctx->minNmpPly = ply + (depth - reduction) * 3 / 4;
const auto verifResults = PVS<false, mode>(copy, depth - reduction, beta - 1, beta, ply + 1, ctx, true);
ctx->minNmpPly = 0;
if (verifResults.score >= beta) {
return verifResults;
}
}
}
}
}
}
const int probcutBeta = beta + probcutBetaMargin;
const int probcutDepth = std::max(depth - 3, 1);
if (depth >= 7 && std::abs(beta) < MATE_SCORE - MAX_DEPTH
&& (!entry.bestMove || !entry.bestMove.IsQuiet())
&& !(ttHit && entry.depth >= probcutDepth && entry.score < probcutBeta)) {
MovePicker<Noisy> mp(board, ctx, ply, entry.bestMove);
const int seeThreshold = (probcutBeta - staticEval) * 15 / 16;
Move currMove;
while ((currMove = mp.Next())) {
if (ctx->excluded == currMove)
continue;
if (!SEE(board, currMove, seeThreshold))
continue;
if (!board.IsLegal(currMove)) continue;
Board copy = board;
copy.MakeMove(currMove);
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
ctx->nodes++;
int score = -Quiescence<isPV, mode>(copy, -probcutBeta, -probcutBeta + 1, ply + 1, ctx).score;
if (score >= probcutBeta) {
score = -PVS<isPV, mode>(copy, probcutDepth - 1, -probcutBeta, -probcutBeta + 1,
ply + 1, ctx, !cutnode).score;
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
if (score >= probcutBeta) {
ctx->TT->WriteEntry(board.hashKey, probcutDepth, score, CutNode, currMove, ttpv);
return score;
}
}
}
MovePicker<All> mp(board, ctx, ply, entry.bestMove);
int score = -inf;
int nodeType = AllNode;
SearchResults results(-inf);
int moveSeen = 0;
std::array<Move, MAX_MOVES> seenQuiets;
std::array<Move, MAX_MOVES> seenCaptures;
int seenQuietsCount = 0;
int seenCapturesCount = 0;
ctx->killerMoves[ply + 1] = Move();
Move currMove;
while ((currMove = mp.Next())) {
if (ctx->excluded == currMove)
continue;
bool notMated = results.score > (-MATE_SCORE + MAX_DEPTH);
int lmrDepth = depth - lmrTable[currMove.IsQuiet()][depth][moveSeen];
if (currMove.IsQuiet() && notMated) {
int lmpThreshold = 7 + depth * depth * (1 + improving);
if (moveSeen >= lmpThreshold) {
continue;
}
}
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, currMove.MoveFrom());
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, currMove.MoveTo());
int historyScore = ctx->history[board.sideToMove][currMove.MoveFrom()][currMove.MoveTo()][sourceThreatened][targetThreatened];
if (ply > 0) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 1);
if (ply > 1) historyScore += ctx->conthist.GetNPly(board, currMove, ctx, ply, 2);
int margin = fpMargin * (lmrDepth + improving) + historyScore / 32;
if (!isPV && ply && currMove.IsQuiet()
&& lmrDepth <= 7 && staticEval + margin < alpha && notMated && !board.GivesDirectCheck(currMove)) {
continue;
}
int SEEThreshold = currMove.IsQuiet() ? seeQuietThreshold * depth : seeNoisyThreshold * depth * depth;
if (ply && depth <= 10 && notMated && !SEE(board, currMove, SEEThreshold))
continue;
if (!board.IsLegal(currMove)) continue;
Board copy = board;
copy.MakeMove(currMove);
ctx->nodes++;
ctx->TT->PrefetchEntry(copy.hashKey);
int extension = 0;
if (ply && ply < ctx->rootDepth * 2 && currMove == entry.bestMove && ctx->excluded == 0) {
if (depth >= 8
&& ttHit
&& entry.depth >= depth - 3
&& entry.nodeType != AllNode)
{
const int sBeta = std::max(-inf + 1, entry.score - depth * 2);
const int sDepth = (depth - 1) / 2;
ctx->excluded = currMove;
const int singularScore = PVS<false, mode>(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score;
ctx->excluded = Move();
if (singularScore < sBeta) {
extension++;
if constexpr (!isPV) {
if (singularScore <= sBeta - 1 - doubleExtMargin) {
extension++;
}
}
}
else if (sBeta >= beta) {
return sBeta;
}
else if (entry.score >= beta) {
extension--;
} else if (cutnode) {
extension--;
}
} else if (depth <= 7 && !inCheck && staticEval <= alpha - ldseMargin && entry.nodeType == CutNode) {
extension++;
}
}
cutnode |= extension < 0;
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
ctx->ss[ply].moveTo = currMove.MoveTo();
ctx->ss[ply].side = board.sideToMove;
if (copy.positionIndex >= ctx->positionHistory.size()) {
ctx->positionHistory.resize(copy.positionIndex + 100);
}
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
int newDepth = depth + (copy.InCheck() && !ctx->excluded) - 1 + extension;
U64 nodesBeforeSearch = ctx->nodes;
if (depth >= 2 && moveSeen >= 2 + (2 * isPV)) {
const bool ttpvFailLow = ttpv && ttHit && entry.score <= alpha;
int reductions = GetReductions<isPV>(board, currMove, depth, moveSeen, ply, cutnode, improving, corrplexity, ttpv, ttpvFailLow, ctx);
int reduced = newDepth - reductions;
score = -PVS<false, mode>(copy, reduced, -alpha - 1, -alpha, ply + 1, ctx, true).score;
if (score > alpha && reduced < newDepth) {
const bool goDeeper = score > results.score + lmrDeeperBase + 4 * newDepth;
const bool goShallower = score < results.score + newDepth;
newDepth += goDeeper - goShallower;
score = -PVS<false, mode>(copy, newDepth, -alpha - 1, -alpha, ply + 1, ctx, !cutnode).score;
}
} else if (!isPV || moveSeen > 0) {
score = -PVS<false, mode>(copy, newDepth, -alpha - 1, -alpha, ply + 1, ctx, !cutnode).score;
}
if (isPV && (moveSeen == 0 || score > alpha)) {
score = -PVS<true, mode>(copy, newDepth, -beta, -alpha, ply + 1, ctx, false).score;
}
moveSeen++;
if (!ply) {
ctx->nodesTable[currMove % 4096] += ctx->nodes - nodesBeforeSearch;
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
if (currMove != 0 && currMove.IsQuiet()) {
seenQuiets[seenQuietsCount] = currMove;
seenQuietsCount++;
} else if (currMove != 0 && currMove.IsCapture()) {
seenCaptures[seenCapturesCount] = currMove;
seenCapturesCount++;
}
results.score = std::max(score, results.score);
if (score > alpha) {
nodeType = PV;
alpha = score;
results.bestMove = currMove;
ctx->pvLine.SetMove(ply, currMove);
}
if (score >= beta) {
const int bonusDepth = depth + (!inCheck && staticEval <= alpha);
int historyBonus = historyBonusMultiplier * bonusDepth - historyBonusSub;
int historyMalus = historyMalusMultiplier * bonusDepth - historyMalusSub;
int contHistoryBonus = contHistoryBonusMultiplier * bonusDepth - contHistoryBonusSub;
int contHistoryMalus = contHistoryMalusMultiplier * bonusDepth - contHistoryMalusSub;
int captHistoryBonus = captHistoryBonusMultiplier * bonusDepth - captHistoryBonusSub;
int captHistoryMalus = captHistoryMalusMultiplier * bonusDepth - captHistoryMalusSub;
auto UpdateCaptHist = [&](Move move, int bonus) {
int movingPiece = board.GetPieceType(move.MoveFrom());
int capturedPiece = move.GetFlags() == epCapture ? Pawn : board.GetPieceType(move.MoveTo());
ctx->capthist.Update(board.sideToMove, movingPiece, capturedPiece, move.MoveTo(), bonus);
};
auto UpdateContHistNPly = [&](int n) {
int prevType = ctx->ss[ply - n].pieceType;
int prevTo = ctx->ss[ply - n].moveTo;
bool otherColor = ctx->ss[ply - n].side;
int pieceType = ctx->ss[ply].pieceType;
int to = ctx->ss[ply].moveTo;
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, contHistoryBonus);
for (int i = 0; i < seenQuietsCount - 1; i++) {
int pt = board.GetPieceType(seenQuiets[i].MoveFrom());
int t = seenQuiets[i].MoveTo();
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pt, t, -contHistoryMalus);
}
};
if (!currMove.IsCapture()) {
ctx->killerMoves[ply] = currMove;
ctx->history.Update(board.sideToMove, currMove, sourceThreatened, targetThreatened, historyBonus);
if (ply > 0) UpdateContHistNPly(1);
if (ply > 1) UpdateContHistNPly(2);
for (int i = 0; i < seenQuietsCount - 1; i++) {
sourceThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveFrom());
targetThreatened = board.IsSquareThreatened(board.sideToMove, seenQuiets[i].MoveTo());
ctx->history.Update(board.sideToMove, seenQuiets[i], sourceThreatened, targetThreatened, -historyMalus);
}
} else {
UpdateCaptHist(currMove, captHistoryBonus);
}
for (int i = 0; i < seenCapturesCount - currMove.IsCapture(); i++) {
UpdateCaptHist(seenCaptures[i], -captHistoryMalus);
}
if (!ctx->excluded && !inCheck && currMove.IsQuiet() && score > staticEval) {
int corrHistBonus = std::clamp(score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
}
if (!ctx->excluded)
ctx->TT->WriteEntry(board.hashKey, depth, score, CutNode, currMove, ttpv);
return score;
}
}
if (moveSeen == 0) {
if (ctx->excluded) return alpha;
return inCheck ? -MATE_SCORE + ply : 0;
}
if (searchStopped.load(std::memory_order_relaxed)) return 0;
if (!ctx->excluded) {
if (!inCheck && ((results.bestMove.IsQuiet() || !results.bestMove))
&& !(nodeType == AllNode && results.score >= staticEval)) {
int corrHistBonus = std::clamp(results.score - staticEval, -CORRHIST_LIMIT, CORRHIST_LIMIT);
ctx->corrhist.UpdateAll(board, depth, corrHistBonus);
}
ctx->TT->WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove, ttpv);
}
return results;
}
class AspirationWindow {
public:
int delta = aspInitialDelta;
int alpha = -inf;
int beta = inf;
void WidenDown() {
alpha -= delta;
delta *= 2;
}
void WidenUp() {
beta += delta;
delta *= 2;
}
void Set(int score) {
delta = aspInitialDelta;
alpha = score - delta;
beta = score + delta;
}
};
static double ScaleTime(SearchContext *ctx, Move &move) {
double notBmNodesFraction =
ctx->nodesTable[move % 4096] / double(ctx->nodes);
double nodeScalingFactor = (1.5f - notBmNodesFraction) * 1.35f;
return nodeScalingFactor;
}
template <searchMode mode>
static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
int fullTime = board.sideToMove ? params.btime : params.wtime;
int inc = board.sideToMove ? params.binc : params.winc;
int movesToGo = params.movesToGo ? params.movesToGo : 20;
SearchResults safeResults;
safeResults.score = -inf;
int toDepth = MAX_DEPTH;
if constexpr (mode == bench) {
toDepth = BENCH_DEPTH;
}
AspirationWindow aw;
int elapsed = 0;
double nodeScaling = 1;
ctx->sw.Restart();
for (int depth = 1; depth <= toDepth; depth++) {
ctx->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
int softTime = ctx->timeToSearch * 0.65 * nodeScaling;
ctx->seldepth = 0;
ctx->rootDepth = depth;
SearchResults currentResults = PVS<true, mode>(board, depth, aw.alpha, aw.beta, 0, ctx, false);
elapsed = ctx->sw.GetElapsedMS();
if (depth > 6) {
nodeScaling = ScaleTime(ctx, currentResults.bestMove);
}
if (aw.alpha != -inf && currentResults.score <= aw.alpha) {
aw.WidenDown();
depth--;
continue;
}
if (aw.beta != inf && currentResults.score >= aw.beta) {
aw.WidenUp();
depth--;
continue;
}
aw.Set(currentResults.score);
if (searchStopped.load(std::memory_order_relaxed)) {
break;
} else {
if (currentResults.bestMove) {
safeResults = currentResults;
}
if constexpr (mode == normal || mode == nodesMode) {
if (ctx->doPrint)
PrintSearchInfo(board, ctx, safeResults, depth, elapsed);
if constexpr (mode == normal) {
if (ctx->sw.GetElapsedMS() >= softTime) {
searchStopped.store(true, std::memory_order_relaxed);
break;
}
}
} else if constexpr (mode == datagen) {
if (ctx->nodes >= DATAGEN::SOFT_NODES) {
searchStopped.store(true, std::memory_order_relaxed);
break;
}
}
}
}
return safeResults;
}
template <searchMode mode>
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) {
if constexpr (mode == bench || mode == datagen) {
searchStopped.store(false, std::memory_order_relaxed);
ctx->TT->IncreaseAge();
}
board.MarkAccumulatorDirty();
ctx->accStack.finny.Reset();
ctx->seldepth = 0;
ctx->nodesTable = {};
if constexpr (mode != bench) {
ctx->nodes = 0;
if constexpr (mode == nodesMode) {
ctx->nodesToGo = params.nodes;
}
}
ctx->pvLine.Clear();
SearchResults results = ID<mode>(board, params, ctx);
if constexpr (mode != normal && mode != nodesMode) return results;
if (ctx->doPrint) {
std::cout << "bestmove ";
results.bestMove.PrintMove();
std::cout << std::endl;
}
return results;
}
int MoveEstimatedValue(Board& board, Move& move) {
int pieceType = board.GetPieceType(move.MoveTo());
int value = pieceType != nullPieceType ? SEEPieceValues[pieceType] : 0;
if (move.IsPromo()) {
int promoPiece = move.GetPromoPiece();
value += SEEPieceValues[promoPiece] - SEEPieceValues[Pawn];
} else if (move.GetFlags() == epCapture) {
value = SEEPieceValues[Pawn];
} else if (move.GetFlags() == queenCastle || move.GetFlags() == kingCastle) {
value = 0;
}
return value;
}
void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed) {
WDLTriplet wdl = getWDL(results.score, board);
const bool isMateScore = std::abs(results.score) + MAX_DEPTH >= MATE_SCORE;
const int normalizedScore = isMateScore ? results.score : scaleEval(results.score, board);
if (UCIEnabled) {
std::cout << "info ";
std::cout << "depth " << depth;
std::cout << " seldepth " << ctx->seldepth;
std::cout << " time " << elapsed;
std::cout << " score ";
if (isMateScore) {
int mateIn = (MATE_SCORE - (std::abs(results.score) - 1)) / 2;
mateIn = results.score < 0 ? mateIn * -1 : mateIn;
std::cout << "mate " << mateIn;
} else {
std::cout << "cp " << normalizedScore;
}
if (UCIShowWDL) {
std::cout << " wdl " << wdl.wins << ' ' << wdl.draws << ' ' << wdl.losses;
}
std::cout << " nodes " << ctx->nodes << " nps " << int(ctx->nodes/ctx->sw.GetElapsedSec());
std::cout << " hashfull " << ctx->TT->GetUsedPercentage();
std::cout << " pv ";
ctx->pvLine.Print(0, depth % 2 == 0);
std::cout << std::endl;
} else {
if (depth % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
std::stringstream depthStr;
depthStr << depth << '/' << ctx->seldepth;
std::cout << std::setw(6) << std::left << depthStr.str();
std::stringstream timeStr;
if (elapsed >= 1000) {
timeStr << std::fixed << std::setprecision(1) << (elapsed / 1000.0) << "s";
} else {
timeStr << elapsed << "ms";
}
std::cout << std::setw(10) << std::right << timeStr.str();
std::stringstream scoreStr;
bool isMate = false;
int mateIn = 0;
if (isMateScore) {
isMate = true;
mateIn = (MATE_SCORE - (std::abs(results.score) - 1)) / 2;
mateIn = results.score < 0 ? mateIn * -1 : mateIn;
if (mateIn < 0) {
scoreStr << "-M" << std::abs(mateIn);
} else {
scoreStr << "+M" << mateIn;
}
} else {
scoreStr << std::showpos << std::fixed << std::setprecision(2)
<< (normalizedScore / 100.0) << std::noshowpos;
}
if (isMate) {
if (mateIn > 0) {
std::cout << termcolor::bright_green;
} else {
std::cout << termcolor::bright_red;
}
} else {
if (results.score > 0) {
std::cout << termcolor::green;
} else if (results.score < 0) {
std::cout << termcolor::red;
}
}
std::cout << std::setw(9) << std::right << scoreStr.str();
std::cout << termcolor::reset;
if (depth % 2 == 0) {
std::cout << termcolor::color<247>;
} else {
std::cout << termcolor::color<251>;
}
WDLTriplet displayWDL = GetRoundedWDL(results.score, board);
std::stringstream wdlStr;
wdlStr << displayWDL.wins << "W "
<< displayWDL.draws << "D "
<< displayWDL.losses << "L";
std::cout << std::setw(14) << std::right << wdlStr.str();
std::stringstream hashfullStr;
hashfullStr << "TT: " << (ctx->TT->GetUsedPercentage() + 5) / 10 << '%';
std::cout << std::setw(10) << std::right << hashfullStr.str();
std::stringstream nodesStr;
if (ctx->nodes >= 1000000) {
nodesStr << std::fixed << std::setprecision(1) << (ctx->nodes / 1000000.0) << "M";
} else if (ctx->nodes >= 1000) {
nodesStr << std::fixed << std::setprecision(1) << (ctx->nodes / 1000.0) << "k";
} else {
nodesStr << ctx->nodes;
}
std::cout << std::setw(11) << std::right << nodesStr.str();
int nps = int(ctx->nodes/ctx->sw.GetElapsedSec());
std::stringstream npsStr;
if (nps >= 1000000) {
npsStr << std::fixed << std::setprecision(1) << (nps / 1000000.0) << "M/s";
} else if (nps >= 1000) {
npsStr << std::fixed << std::setprecision(1) << (nps / 1000.0) << "k/s";
} else {
npsStr << nps << "/s";
}
std::cout << std::setw(12) << std::right << npsStr.str();
std::cout << " ";
ctx->pvLine.Print(0, depth % 2 == 0);
std::cout << termcolor::reset << std::endl;
}
}
template SearchResults PVS<true, searchMode::bench>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults PVS<false, searchMode::bench>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults PVS<true, searchMode::normal>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults PVS<false, searchMode::normal>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults PVS<true, searchMode::datagen>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults PVS<false, searchMode::datagen>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
template SearchResults SearchPosition<normal>(Board &board, SearchParams params, SearchContext* ctx);
template SearchResults SearchPosition<bench>(Board &board, SearchParams params, SearchContext* ctx);
template SearchResults SearchPosition<datagen>(Board &board, SearchParams params, SearchContext* ctx);
template SearchResults SearchPosition<nodesMode>(Board &board, SearchParams params, SearchContext* ctx);
}