io-chess
UCI chess engine
Loading...
Searching...
No Matches
Negamax.h
Go to the documentation of this file.
1#pragma once
2
12
13#include "../eval/IEvaluator.h"
16#include "ISearch.h"
17#include "TT.h"
18#include "TimeManager.h"
19#include <array>
20#include <chrono>
21
22#include "MovePicker.h"
23#include "SearchHeuristics.h"
24
33class Negamax : public ISearch {
34 // Grant MovePicker access to heap-allocated heuristics
35 friend class MovePicker;
36
37private:
40
41 // LAZY SMP: Shared State
42 std::shared_ptr<SearchSharedData> shared_;
45
46 // Thread-local statistics
47 uint64_t localNodes_ = 0;
48 uint64_t localTbHits_ = 0;
49 uint64_t localTtHits_ = 0;
51 static constexpr uint64_t NODE_FLUSH_INTERVAL = 1024;
52
53 // Time management
56 float lastEvalCp_ = 0.0f;
57
58 // Iteration state tracking
60 int lastScore_ = 0;
62 int scoreDrops_ = 0;
63 std::array<uint64_t, 4096> rootNodeCounts_{};
64 uint64_t searchNodes_ = 0;
65
66 std::unique_ptr<SearchHeuristics> h_;
67
73 uint64_t getPawnKey(const Board& board) const;
74
81 uint64_t getNonPawnKey(const Board& board, Color c) const;
82
83 // Search context tracking arrays
84 std::array<Move, SearchConstants::MAX_PLY> prevMove_;
85 std::array<Piece, SearchConstants::MAX_PLY> prevPiece_{};
86 std::array<int, SearchConstants::MAX_PLY> pvLength_;
87 std::array<int, SearchConstants::MAX_PLY> evalHistory_{};
88
89 int currentIter_ = 0;
90
91 std::vector<Move> searchMoves_;
92
94
96
97public:
108 std::shared_ptr<SearchSharedData> shared, bool isMainThread,
109 int threadId = 0);
110
111 Move startSearch(Board &root, const SearchParams &params) override;
112
113 void stop() override {
114 if (shared_)
115 shared_->stop = true;
116 }
117
118 bool isSearching() const override { return shared_ && !shared_->stop; }
119
120 void setInfoCallback(InfoCallback callback) override {
121 infoCallback_ = callback;
122 }
123
124 uint64_t getNodes() const override {
125 return shared_ ? shared_->totalNodes.load(std::memory_order_relaxed) : 0;
126 }
127
128private:
144 int alphaBeta(Board &board, int depth, int alpha, int beta, int ply,
145 bool allowNull, int extensions, bool prevWasCapture = false, bool cutnode = false, Move excludedMove = Move(0));
146
158 int quiescence(Board &board, int alpha, int beta, int ply);
159
174 bool canLazySkip(const Board &board, int depth, int alpha, int beta, int ply,
175 int fastScore, Bound &outBound, bool prevWasCapture,
176 bool pvNode);
177
188 int scoreMoveFast(const Move &move, const Board &board, Move ttMove, int ply,
189 bool isCapture);
190
197 void updateKillers(Move move, int ply);
198
207 void updateHistory(const Board& board, Move move, int bonus, int ply);
208
209 friend class MovePicker;
210
220 int see(const Board &board, Move move) const;
221
225 int pieceValue(PieceType pt) const;
226
237 int applyCorrHist(int rawEval, const Board &board, int ply) const;
238
239 // Extension condition checkers
240 bool isPassedPawn(const Board &board, Square sq, Color side) const;
241 bool isPawnPush7th(const Board &board, Move move) const;
242
243 // Time management helpers
244 void syncTimeToShared();
245 bool shouldStop() const;
246 int64_t elapsedMs() const;
247 bool shouldStopIteration(int depth, int score, Move bestMove) const;
248
249 // General utilities
250 bool isCapture(const Board &board, Move move) const;
251 bool isDraw(const Board &board) const;
252 int mateScore(int ply) const;
253 bool isMateScore(int score) const {
254 return std::abs(score) >= SearchConstants::MATE_IN_MAX - SearchConstants::MAX_PLY;
255 }
256
260 void clearState();
261
266};
Abstract interface for board evaluation algorithms.
Search interface and shared data structures.
std::function< void(int depth, int score, int nodes, int nps, const std::vector< Move > &pv)> InfoCallback
Callback function type for sending UCI 'info' updates during search.
Definition ISearch.h:145
Move selection and ordering for the search algorithm.
Search data structures.
Hand-crafted evaluation function for testing and fallback.
Transposition Table implementation using a 3+1 Cluster Architecture.
Bound
Represents the type of score stored in the Transposition Table.
Definition TT.h:21
Syzygy tablebase probing via Fathom.
Sophisticated time allocation and management for the chess engine.
chess::Move Move
Alias for chess::Move.
Definition Types.h:15
chess::PieceType PieceType
Alias for chess::PieceType.
Definition Types.h:20
chess::Color Color
Alias for chess::Color.
Definition Types.h:17
chess::Square Square
Alias for chess::Square.
Definition Types.h:18
chess::Board Board
Alias for chess::Board.
Definition Types.h:14
Abstract interface for evaluators.
Definition IEvaluator.h:25
Abstract interface for search algorithms.
Definition ISearch.h:155
IEvaluator & evalCtx_
Reference to the thread-local evaluator.
Definition Negamax.h:38
bool shouldStop() const
Definition Negamax.cpp:1915
uint64_t searchNodes_
Total nodes searched during the current search session.
Definition Negamax.h:64
int threadId_
Unique ID for this thread (used for move ordering diversity).
Definition Negamax.h:44
uint64_t getNodes() const override
Retrieves the total number of nodes evaluated by the search algorithm.
Definition Negamax.h:124
Move startSearch(Board &root, const SearchParams &params) override
Starts the search process on the given root board.
Definition Negamax.cpp:205
int64_t elapsedMs() const
Definition Negamax.cpp:1947
int applyCorrHist(int rawEval, const Board &board, int ply) const
Applies historical corrections to the raw neural network evaluation.
Definition Negamax.cpp:766
Negamax(IEvaluator &eval, TranspositionTable &table, std::shared_ptr< SearchSharedData > shared, bool isMainThread, int threadId=0)
Constructs a new Negamax search instance.
Definition Negamax.cpp:105
uint64_t localTbHits_
Tablebase hits by this thread.
Definition Negamax.h:48
int currentIter_
The current depth iteration in Iterative Deepening.
Definition Negamax.h:89
int localSelDepth_
Maximum selective depth reached by this thread.
Definition Negamax.h:50
void flushLocalSearchStats()
Flushes local statistics (nodes, hits) to the global shared atomic counters.
Definition Negamax.cpp:178
bool isMainThread_
True if this is the primary search thread.
Definition Negamax.h:43
void setInfoCallback(InfoCallback callback) override
Sets the callback function for periodic information updates.
Definition Negamax.h:120
int bestMoveChanges_
Count of how many times the best move changed at root.
Definition Negamax.h:61
int quiescence(Board &board, int alpha, int beta, int ply)
Quiescence search to resolve tactical sequences before static evaluation.
Definition Negamax.cpp:1596
std::vector< Move > searchMoves_
Restricts the search to only these root moves (used for 'searchmoves' command).
Definition Negamax.h:91
uint64_t getNonPawnKey(const Board &board, Color c) const
Computes a hash key based on non-pawn pieces of a given color.
Definition Negamax.cpp:754
void stop() override
Asynchronously signals the search to stop immediately.
Definition Negamax.h:113
std::array< int, SearchConstants::MAX_PLY > pvLength_
Tracks the length of the principal variation at each ply.
Definition Negamax.h:86
int scoreMoveFast(const Move &move, const Board &board, Move ttMove, int ply, bool isCapture)
Scores a move rapidly for sorting during move generation.
std::array< Piece, SearchConstants::MAX_PLY > prevPiece_
Records the piece that moved at each ply.
Definition Negamax.h:85
bool isMateScore(int score) const
Definition Negamax.h:253
TranspositionTable & tt_
Reference to the global transposition table.
Definition Negamax.h:39
float lastEvalCp_
Last evaluation score in centipawns (used for time decisions).
Definition Negamax.h:56
void clearState()
Resets transient state arrays and variables before starting a new search.
Definition Negamax.cpp:117
bool isPassedPawn(const Board &board, Square sq, Color side) const
Definition Negamax.cpp:2124
uint64_t getPawnKey(const Board &board) const
Computes a hash key based on the pawn structure.
Definition Negamax.cpp:743
bool canLazySkip(const Board &board, int depth, int alpha, int beta, int ply, int fastScore, Bound &outBound, bool prevWasCapture, bool pvNode)
Determines if the position can bypass a full neural network evaluation.
Definition Negamax.cpp:659
int alphaBeta(Board &board, int depth, int alpha, int beta, int ply, bool allowNull, int extensions, bool prevWasCapture=false, bool cutnode=false, Move excludedMove=Move(0))
The core recursive Alpha-Beta search function.
Definition Negamax.cpp:795
int lastScore_
Score returned in the previous iteration.
Definition Negamax.h:60
std::array< Move, SearchConstants::MAX_PLY > prevMove_
Records the move made at each ply to reach the current state.
Definition Negamax.h:84
bool isCapture(const Board &board, Move move) const
Definition Negamax.cpp:1963
void updateHistory(const Board &board, Move move, int bonus, int ply)
Updates history and continuation history heuristics based on search results.
Definition Negamax.cpp:1830
TimeManager timeManager_
Manages time limits and soft/hard stops.
Definition Negamax.h:54
static constexpr uint64_t NODE_FLUSH_INTERVAL
How often to flush local stats to the shared global counters.
Definition Negamax.h:51
TimeManager::TimeAllocation timeAlloc_
Pre-calculated time allocation constraints.
Definition Negamax.h:55
std::array< int, SearchConstants::MAX_PLY > evalHistory_
Tracks static evaluation history for pruning thresholds.
Definition Negamax.h:87
bool isDraw(const Board &board) const
Definition Negamax.cpp:1967
bool isSearching() const override
Checks if the search algorithm is currently running.
Definition Negamax.h:118
SimpleEvalContext simpleEval_
A fast, simple evaluator used for pre-NN filtering or lazy evaluation.
Definition Negamax.h:95
friend class MovePicker
MovePicker requires access to scoreMoveFast and heuristics.
Definition Negamax.h:35
std::unique_ptr< SearchHeuristics > h_
Heap-allocated structure containing large arrays for search heuristics.
Definition Negamax.h:66
bool isPawnPush7th(const Board &board, Move move) const
Definition Negamax.cpp:2156
void updateKillers(Move move, int ply)
Updates killer move heuristics when a quiet move causes a beta cutoff.
Definition Negamax.cpp:1823
int mateScore(int ply) const
Definition Negamax.cpp:1980
uint64_t localNodes_
Nodes searched by this thread.
Definition Negamax.h:47
uint64_t localTtHits_
TT hits by this thread.
Definition Negamax.h:49
InfoCallback infoCallback_
Callback function to output search progress to the UCI protocol.
Definition Negamax.h:93
int see(const Board &board, Move move) const
Static Exchange Evaluation (SEE) for a move.
Definition Negamax.cpp:1992
void syncTimeToShared()
Definition Negamax.cpp:1871
Move lastBestMove_
Best move found in the previous iterative deepening iteration.
Definition Negamax.h:59
std::shared_ptr< SearchSharedData > shared_
Shared state for thread coordination.
Definition Negamax.h:42
int scoreDrops_
Count of significant evaluation drops at root.
Definition Negamax.h:62
int pieceValue(PieceType pt) const
Returns the base material value of a piece type for SEE calculations.
Definition Negamax.cpp:2119
bool shouldStopIteration(int depth, int score, Move bestMove) const
Definition Negamax.cpp:1878
std::array< uint64_t, 4096 > rootNodeCounts_
Number of nodes spent evaluating each root move.
Definition Negamax.h:63
Classical, non-neural evaluation context.
Definition SimpleEvalContext.h:53
Handles adaptive time allocation during search.
Definition TimeManager.h:28
The main Transposition Table.
Definition TT.h:145
constexpr int MATE_IN_MAX
Threshold to detect mating sequences.
Definition Types.h:36
constexpr int MAX_PLY
Maximum supported plies from root.
Definition Types.h:49
Parameters defining the constraints for a search operation.
Definition ISearch.h:125
Recommended time limits for the current move.
Definition TimeManager.h:46