-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.cpp
More file actions
371 lines (338 loc) · 10.8 KB
/
search.cpp
File metadata and controls
371 lines (338 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
#include "search.h"
#include "eval.h"
#include "movepick.h"
#include "timeman.h"
#include "uci.h"
#include <atomic>
#include <iostream>
#include <moves_io.h>
#include <position.h>
#include <printers.h>
using namespace chess;
namespace engine {
TranspositionTable search::tt(16);
std::atomic<bool> stopSearch{false};
void search::stop() { stopSearch.store(true, std::memory_order_relaxed); }
bool search::isStopped() { return stopSearch; }
struct Session {
timeman::TimeManagement tm;
timeman::LimitsType tc;
int seldepth = 0;
uint64_t nodes = 0;
chess::Move pv[MAX_PLY][MAX_PLY];
};
namespace { // SF
void update_pv(Move *pv, Move move, const Move *childPv) {
for (*pv++ = move; childPv && *childPv != Move::none();)
*pv++ = *childPv++;
*pv = Move::none();
}
// Adjusts a mate or TB score from "plies to mate from the root" to
// "plies to mate from the current position". Standard scores are unchanged.
// The function is called before storing a value in the transposition table.
Value value_to_tt(Value v, int ply) {
return is_win(v) ? v + ply : is_loss(v) ? v - ply : v;
}
// Inverse of value_to_tt(): it adjusts a mate or TB score from the
// transposition table (which refers to the plies to mate/be mated from current
// position) to "plies to mate/be mated (TB win/loss) from the root". However,
// to avoid potentially false mate or TB scores related to the 50 moves rule and
// the graph history interaction, we return the highest non-TB score instead.
Value value_from_tt(Value v, int ply, int r50c) {
if (!is_valid(v))
return VALUE_NONE;
// handle TB win or better
if (is_win(v)) {
// Downgrade a potentially false mate score
if (v >= VALUE_MATE_IN_MAX_PLY && VALUE_MATE - v > 100 - r50c)
return VALUE_TB_WIN_IN_MAX_PLY - 1;
// Downgrade a potentially false TB score.
if (VALUE_TB - v > 100 - r50c)
return VALUE_TB_WIN_IN_MAX_PLY - 1;
return v - ply;
}
// handle TB loss or worse
if (is_loss(v)) {
// Downgrade a potentially false mate score.
if (v <= VALUE_MATED_IN_MAX_PLY && VALUE_MATE + v > 100 - r50c)
return VALUE_TB_LOSS_IN_MAX_PLY + 1;
// Downgrade a potentially false TB score.
if (VALUE_TB + v > 100 - r50c)
return VALUE_TB_LOSS_IN_MAX_PLY + 1;
return v + ply;
}
return v;
}
} // namespace
Value qsearch(Board &board, Value alpha, Value beta, Session &session,
int ply = 0) {
session.nodes++;
session.seldepth = std::max(session.seldepth, ply);
int standPat = eval::eval(board);
if (session.tm.elapsed() >= session.tm.optimum() ||
stopSearch.load(std::memory_order_relaxed))
return standPat;
Value maxScore = standPat;
if (maxScore >= beta)
return maxScore;
if (maxScore > alpha)
alpha = maxScore;
Movelist moves;
board.legals<MoveGenType::CAPTURE>(moves);
for (Move move : moves) {
board.doMove(move);
Value score = qsearch(board, -beta, -alpha, session, ply + 1);
board.undoMove();
if (score == VALUE_NONE)
return VALUE_NONE;
score = -score;
if (score >= beta)
return score;
if (score > maxScore)
maxScore = score;
if (score > alpha)
alpha = score;
}
return maxScore;
}
Value doSearch(Board &board, int depth, Value alpha, Value beta,
Session &session, int ply = 0) {
// TLE or exceeded depth limit
if (ply >= MAX_PLY - 1)
return eval::eval(board);
if (depth <= 0) {
session.nodes++;
return qsearch(board, alpha, beta, session, ply);
}
if (session.tm.elapsed() >= session.tm.optimum() ||
stopSearch.load(std::memory_order_relaxed))
return qsearch(board, alpha, beta, session, ply);
Value alphaOrig = alpha;
// Reset PV
std::fill(std::begin(session.pv[ply]), std::end(session.pv[ply]),
Move::none());
std::fill(std::begin(session.pv[ply + 1]), std::end(session.pv[ply + 1]),
Move::none());
if (board.is_draw(3) || board.is_insufficient_material()) {
session.nodes++;
session.pv[ply][0] = Move::none();
return 0;
}
session.seldepth = std::max(session.seldepth, ply);
uint64_t hash = board.hash();
Move preferred = Move::none();
if (TTEntry *entry = search::tt.lookup(hash)) {
if (entry->getDepth() >= depth) {
Value ttScore =
value_from_tt(entry->getScore(), ply, board.rule50_count());
TTFlag flag = entry->getFlag();
if (flag == TTFlag::EXACT) {
session.pv[ply][0] = Move(entry->getMove());
session.pv[ply][1] = Move::none();
return ttScore;
}
if (flag == TTFlag::LOWERBOUND && ttScore >= beta) {
session.pv[ply][0] = Move(entry->getMove());
session.pv[ply][1] = Move::none();
return ttScore;
}
if (flag == TTFlag::UPPERBOUND && ttScore <= alpha) {
session.pv[ply][0] = Move(entry->getMove());
session.pv[ply][1] = Move::none();
return ttScore;
}
}
preferred = Move(entry->getMove());
}
Value maxScore = -VALUE_INFINITE;
Movelist moves;
board.legals(moves);
if (!moves.size()) {
session.pv[ply][0] = Move::none();
return board.checkers() ? -MATE(ply) : 0;
}
movepick::orderMoves(board, moves, preferred, ply);
if (bool useNMP = depth >= 3 && !board.checkers() && ply > 0) {
int R = 2 + depth / 6;
uint64_t hash_ = board.hash();
board.doNullMove();
Value score =
doSearch(board, depth - 1 - R, -beta, -beta + 1, session, ply + 1);
score = -score;
board.undoMove();
if (score >= beta)
return score;
}
for (size_t i = 0; i < moves.size(); ++i) {
Move move = moves[i];
bool isCapture = board.isCapture(move);
bool givesCheck = board.givesCheck(move) != CheckType::NO_CHECK;
// --- LMR reduction ---
int reduction = 0;
if (i >= 3 && depth >= 3 && !isCapture && !givesCheck) {
reduction = 1 + (int)(i / 6) + (depth / 8);
// history heuristic: good moves get reduced less
if (movepick::historyHeuristic[(int)move.from()][(int)move.to()] > 0)
reduction--;
reduction = std::max(0, reduction);
reduction = std::min(reduction, depth - 2);
}
board.doMove(move);
Value score;
if (i == 0) {
uint64_t hash_ = board.hash();
// --- First move: full window (PVS root move) ---
score = doSearch(board, depth - 1, -beta, -alpha, session, ply + 1);
if (score == VALUE_NONE) {
board.undoMove();
return VALUE_NONE;
}
score = -score;
} else {
uint64_t hash_ = board.hash();
// --- Null-window search (PVS + LMR) ---
score = doSearch(board, depth - 1 - reduction, -alpha - 1, -alpha,
session, ply + 1);
if (score == VALUE_NONE) {
board.undoMove();
return VALUE_NONE;
}
score = -score;
// --- Re-search if it improves alpha ---
if (score > alpha) {
score = doSearch(board, depth - 1, -beta, -alpha, session, ply + 1);
if (score == VALUE_NONE) {
board.undoMove();
return VALUE_NONE;
}
score = -score;
}
}
board.undoMove();
if (score > maxScore) {
maxScore = score;
update_pv(session.pv[ply], move, session.pv[ply + 1]);
}
if (score > alpha) {
alpha = score;
if (!isCapture)
movepick::historyHeuristic[(int)move.from()][(int)move.to()] +=
depth * depth;
}
if (alpha >= beta) {
// killer moves
if (!isCapture) {
if (movepick::killerMoves[ply][0] != move) {
movepick::killerMoves[ply][1] = movepick::killerMoves[ply][0];
movepick::killerMoves[ply][0] = move;
}
}
break;
}
if (session.tm.elapsed() >= session.tm.optimum() ||
stopSearch.load(std::memory_order_relaxed))
return maxScore;
}
if (maxScore != -VALUE_INFINITE) {
TTFlag flag;
if (maxScore <= alphaOrig)
flag = TTFlag::UPPERBOUND;
else if (maxScore >= beta)
flag = TTFlag::LOWERBOUND;
else
flag = TTFlag::EXACT;
search::tt.store(hash, session.pv[ply][0], value_to_tt(maxScore, ply),
depth, flag);
}
return maxScore;
}
void search::search(const chess::Board &board,
const timeman::LimitsType timecontrol) {
stopSearch = false;
static double originalTimeAdjust = -1;
Session session;
session.tc = timecontrol;
session.tm.init(session.tc, board.sideToMove(), 0, originalTimeAdjust);
InfoFull lastInfo{};
chess::Move lastPV[MAX_PLY]{};
for (int i = 1; i < timecontrol.depth; i++) {
for (int _ = 0; _ < 64; _++)
for (int j = 0; j < 64; j++) {
movepick::historyHeuristic[_][j] /= 2;
// since MAX_PLY=64
session.pv[_][j] = Move::none();
}
auto board_ = board;
Value score_ =
doSearch(board_, i, -VALUE_INFINITE, VALUE_INFINITE, session);
if (session.tm.elapsed() >= session.tm.optimum() ||
stopSearch.load(std::memory_order_relaxed) || score_ == VALUE_NONE)
break;
InfoFull info{};
info.depth = i;
info.selDepth = session.seldepth;
info.hashfull = tt.hashfull();
info.nodes = session.nodes;
info.nps = session.nodes * 1000 /
std::max(session.tm.elapsed(), (timeman::TimePoint)1);
info.timeMs = session.tm.elapsed();
info.multiPV = 1;
info.score = score_;
TTEntry *entry = tt.lookup(board.hash());
if (entry)
switch (entry->getFlag()) {
case LOWERBOUND:
info.bound = "lowerbound";
break;
case UPPERBOUND:
info.bound = "upperbound";
break;
default:
break;
}
std::string pv = "";
for (Move *m = session.pv[0]; *m != Move::none(); m++)
pv += chess::uci::moveToUci(*m, board.chess960()) + " ";
info.pv = pv;
report(info);
lastInfo = info;
std::copy(session.pv[0], &session.pv[0][MAX_PLY], lastPV);
}
if (lastPV[0].is_ok())
report(chess::uci::moveToUci(lastPV[0]));
else {
// try to TT probe it
TTEntry *entry = tt.lookup(board.hash());
if (entry && entry->getMove() != Move::none().raw())
report(chess::uci::moveToUci(Move(entry->getMove()), board.chess960()));
else {
Movelist moves;
board.legals(moves);
if (moves.size()) {
Board board_ = board;
Move best = moves[0];
Value bestScore = -VALUE_INFINITE;
for (Move move : moves) {
board_.doMove(move);
Value score = -eval::eval(board_);
if (score > bestScore) {
bestScore = score;
best = move;
}
board_.undoMove();
}
InfoFull info{};
info.depth = 1;
info.nodes = 1;
info.score = 0;
info.multiPV = 1;
info.pv = std::string(chess::uci::moveToUci(best, board.chess960()));
report(info);
report(chess::uci::moveToUci(best, board.chess960()));
} else {
report("0000");
}
}
}
}
} // namespace engine