-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.c
521 lines (472 loc) · 19.4 KB
/
search.c
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
#include "search.h"
// Search statistics; set by last call to search()
searchstats sstats;
// Local functions
int mtd_f(board *b, int ply);
//int abq_multithread(board *b, int alpha, int beta, int ply, int centiply_extension, bool allow_extensions, bool side_to_move_in_check);
void *abq_multithread_entrypoint(void *param);
int abq(board *b, int alpha, int beta, int ply, int centiply_extension, bool allow_extensions, bool side_to_move_in_check);
int relative_evaluation(board *b);
int capture_move_comparator(const board *board, const move *a, const move *b);
void clear_stats() {
sstats.time = 0;
sstats.depth = 0;
sstats.nodes_searched = 0;
sstats.qnodes_searched = 0;
sstats.qnode_aborts = 0;
sstats.ttable_inserts = 0;
sstats.ttable_insert_failures = 0;
sstats.ttable_hits = 0;
sstats.ttable_misses = 0;
sstats.ttable_overwrites = 0;
}
// Compute the amount of time to spend on the next move
// Some parameters might be -1 if they do not apply
int time_use(board *b, int time_left, int increment, int movestogo) {
if (time_left <= 0) return 100; // Oops!
// Algorithm for remaining move estimation based on:
// http://facta.junis.ni.ac.rs/acar/acar200901/acar2009-07.pdf
// Slightly more aggresive time managment because of overhead after search
// Calculate the total value of material
int mat_value = 0;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (p_eq(b->b[i][j], no_piece)) continue;
switch(b->b[i][j].type) {
case 'P': mat_value += 1; break;
case 'N': mat_value += 3; break;
case 'B': mat_value += 3; break;
case 'R': mat_value += 5; break;
case 'Q': mat_value += 9; break;
default: ;
}
}
}
// Assume the game is 70 moves long, but never use more than 1/10th of the remaining time
int half_moves_left_guess;
if (mat_value < 20) half_moves_left_guess = mat_value + 10;
else if (mat_value <= 60) half_moves_left_guess = (mat_value * 3 + 176) / 8;
else half_moves_left_guess = (mat_value * 5 - 120) / 4;
half_moves_left_guess += 6; // Adjustment for search invocation overhead
int our_moves_left_guess = max(5, (half_moves_left_guess / 2));
return time_left/our_moves_left_guess;
}
void search(board *b, int ply) {
clear_stats(); // Stats for search
sstats.depth = ply;
// Start timer for the search
struct timeval t1, t2;
gettimeofday(&t1, NULL);
int result;
if (use_mtd_f) result = mtd_f(b, ply);
else {
coord king_loc = b->black_to_move ? b->black_king : b->white_king;
bool side_to_move_in_check = in_check(b, king_loc.col, king_loc.row, b->black_to_move);
result = abq(b, NEG_INFINITY, POS_INFINITY, ply, 0, true, side_to_move_in_check);
}
gettimeofday(&t2, NULL);
// Compute and print the elapsed time in millisec
double search_millisec = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
search_millisec += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
sstats.time = search_millisec;
}
int mtd_f(board *board, int ply) {
int g; // First guess of evaluation
evaluation stored;
tt_get(board, &stored); // Use last pass in Transposition Table
if (!e_eq(stored, no_eval)) g = stored.score; // If not present, use static evaluation as guess
else {
g = evaluate(board);
if (board->black_to_move) g = -g;
}
int upper_bound = POS_INFINITY;
int lower_bound = NEG_INFINITY;
coord king_loc = board->black_to_move ? board->black_king : board->white_king;
bool side_to_move_in_check = in_check(board, king_loc.col, king_loc.row, board->black_to_move);
while (lower_bound < upper_bound) {
if (search_terminate_requested) return 0;
int beta;
if (g == lower_bound) beta = g+1;
else beta = g;
g = abq(board, beta-1, beta, ply, 0, true, side_to_move_in_check);
if (g < beta) upper_bound = g;
else lower_bound = g;
}
return g;
}
/*int abq_multithread(board *b, int alpha, int beta, int ply, int centiply_extension, bool allow_extensions, bool side_to_move_in_check) {
pthread_t workers[num_search_threads];
for (int i = 0; i < num_search_threads; i++) {
search_worker_thread_args *args = malloc(sizeof(search_worker_thread_args));
board *new_board = malloc(sizeof(board)); // Every worker gets its own board
*new_board = *b;
search_worker_thread_args param_list = {.b = new_board, .alpha = alpha, .beta = beta, .ply = ply,
.centiply_extension = centiply_extension, .allow_extensions = allow_extensions,
.side_to_move_in_check = side_to_move_in_check};
*args = param_list;
if (pthread_create(&workers[i], NULL, abq_multithread_entrypoint, args)) {
stdout_fprintf(logstr, "info string error creating worker thread\n");
free(new_board);
free(args);
}
}
// Wait for the workers to finish
void *return_val;
for (int i = 0; i < num_search_threads; i++) {
pthread_join(workers[i], &return_val);
}
return (int)return_val;
}*/
void *abq_multithread_entrypoint(void *param) {
search_worker_thread_args *args = param;
int res = abq(args->b, args->alpha, args->beta, args->ply, args->centiply_extension, args->allow_extensions, args->side_to_move_in_check);
free(args->b);
free(param);
return res;
}
// Unified alpha-beta and quiescence search
int abq(board *b, int alpha, int beta, int ply, int centiply_extension, bool allow_extensions, bool side_to_move_in_check) {
if (search_terminate_requested) return 0; // Check for search termination
int alpha_orig = alpha; // For use in later TT storage
// Retrieve the value from the transposition table, if appropriate
evaluation stored;
tt_get(b, &stored);
if (!e_eq(stored, no_eval) && stored.depth >= ply && use_ttable) {
if (stored.type == qexact || stored.type == exact) return stored.score;
if (stored.type == qlowerbound || stored.type == lowerbound) alpha = max(alpha, stored.score);
else if (stored.type == qupperbound || stored.type == upperbound) beta = min(beta, stored.score);
if (alpha >= beta) return stored.score;
}
// Futility pruning: enter quiescence early if the node is futile
if (use_futility_pruning && !side_to_move_in_check && ply == 1) {
if (relative_evaluation(b) + frontier_futility_margin < alpha) ply = 0;
} else if (use_futility_pruning && !side_to_move_in_check && ply == 2) {
if (relative_evaluation(b) + prefrontier_futility_margin < alpha) ply = 0;
}
bool quiescence = (ply <= 0);
// Generate all possible moves for the quiscence search or normal search, and compute the
// static evaluation if applicable.
move *moves = NULL;
int num_available_moves = 0;
if (quiescence) moves = board_moves(b, &num_available_moves, true); // Generate only captures
else moves = board_moves(b, &num_available_moves, false); // Generate all moves
if (quiescence && !use_qsearch) {
free(moves);
return relative_evaluation(b); // If qsearch is turned off
}
// Abort if the quiescence search is too deep (currently 45 plies)
if (ply < -quiesce_ply_cutoff) {
sstats.qnode_aborts++;
free(moves);
return relative_evaluation(b);
}
int quiescence_stand_pat;
// Allow the quiescence search to generate cutoffs
if (quiescence) {
quiescence_stand_pat = relative_evaluation(b);
alpha = max(alpha, quiescence_stand_pat);
if (alpha >= beta) {
free(moves);
return quiescence_stand_pat;
}
} else if (!e_eq(stored, no_eval) && use_tt_move_hueristic) {
assert(is_legal_move(b, stored.best)); // TODO
// For non-quiescence search, use the TT entry as a hueristic
moves[num_available_moves] = stored.best;
num_available_moves++;
}
// Update search stats
if (quiescence) sstats.qnodes_searched++;
else sstats.nodes_searched++;
// Search hueristic: sort exchanges using MVV-LVA
if (quiescence && mvvlva) nlopt_qsort_r(moves, num_available_moves, sizeof(move), b, &capture_move_comparator);
// Search extensions
bool no_more_extensions = false;
// Extend the search if we are in check
//coord king_loc = b->black_to_move ? b->black_king : b->white_king;
bool currently_in_check = side_to_move_in_check; //in_check(b, king_loc.col, king_loc.row, b->black_to_move);
if (check_extend && currently_in_check && ply <= check_extend_threshold && !quiescence && allow_extensions) { // only extend in shallow non-quiescence situations
centiply_extension += check_extension_centiply;
no_more_extensions = true;
}
// Process any extensions
if (allow_extensions && centiply_extension >= 100) {
centiply_extension -= 100;
ply += 1;
} else if (allow_extensions && centiply_extension <= -100) {
centiply_extension += 100;
ply -= 1;
}
if (no_more_extensions) allow_extensions = false; // Only allow one check extension
move best_move_yet = no_move;
int best_score_yet = NEG_INFINITY;
int num_moves_actually_examined = 0; // We might end up in checkmate
//for (int iterations = 0; iterations < 2; iterations++) { // ABDADA iterations
for (int i = num_available_moves - 1; i >= 0; i--) { // Iterate backwards to match MVV-LVA sort order
/*int claimed_node_id = -1;
if (i != num_available_moves - 1 && iterations == 1) { // Skip redundant young brothers on the first pass
if (!tt_try_to_claim_node(b, &claimed_node_id)) continue; // Skip the node if it is already being searched
} else tt_always_claim_node(b, &claimed_node_id);*/
apply(b, moves[i]);
bool we_moved_into_check;
// Choose the more efficient version if possible
// If we were already in check, we need to do the expensive search
if (side_to_move_in_check) {
coord king_loc = b->black_to_move ? b->white_king : b->black_king; // for side that just moved
we_moved_into_check = in_check(b, king_loc.col, king_loc.row, !(b->black_to_move));
} else we_moved_into_check = puts_in_check(b, moves[i], !b->black_to_move);
// Never move into check
if (we_moved_into_check) {
unapply(b, moves[i]);
//tt_unclaim_node(claimed_node_id);
continue;
}
bool opponent_in_check = puts_in_check(b, moves[i], b->black_to_move);
/*coord opp_king_loc = b->black_to_move ? b->black_king : b->white_king;
bool opponent_in_check = in_check(b, opp_king_loc.col, opp_king_loc.row, (b->black_to_move));*/
int score = -abq(b, -beta, -alpha, ply - 1, centiply_extension, allow_extensions, opponent_in_check);
num_moves_actually_examined++;
unapply(b, moves[i]);
if (score > best_score_yet) {
best_score_yet = score;
best_move_yet = moves[i];
}
alpha = max(alpha, best_score_yet);
if (alpha >= beta) {
//tt_unclaim_node(claimed_node_id);
break;
}
//tt_unclaim_node(claimed_node_id);
}
//}
free(moves); // We are done with the array
// We have no available moves (or captures) that don't leave us in check
// This means checkmate or stalemate in normal search
// It might mean no captures are available in quiescence search
if (num_moves_actually_examined == 0) {
if (quiescence) return quiescence_stand_pat; // TODO: qsearch doesn't understand stalemate or checkmate
// This seems paradoxical, but the +1 is necessary so we pick some move in case of checkmate
if (currently_in_check) return NEG_INFINITY + 1; // checkmate
else return 0; // stalemate
}
if (quiescence && best_score_yet < quiescence_stand_pat) return quiescence_stand_pat; // TODO experimental stand pat
if (search_terminate_requested) return 0; // Search termination preempts tt_put
// Record the selected move in the transposition table
evaltype type;
if (best_score_yet <= alpha_orig) type = (quiescence) ? qupperbound : upperbound;
else if (best_score_yet >= beta) type = (quiescence) ? qlowerbound : lowerbound;
else type = (quiescence) ? qexact : exact;
evaluation eval = {.best = best_move_yet, .score = best_score_yet, .type = type, .depth = ply};
tt_put(b, eval);
return best_score_yet;
}
/*
* Returns a relative evaluation of the board position from the perspective of the side about to move.
*/
int relative_evaluation(board *b) {
int evaluation = evaluate(b);
if (b->black_to_move) evaluation = -evaluation;
return evaluation;
}
// An array sorting comparator for capture moves, for use with qsort_r.
// Sorts by MVV/LVA (Most Valuable Victim/Least Valuable Attacker) in REVERSE order.
// Returns -1 if the first argument should come first, etc.
// Uses reverse order because of implementation details above.
// COMPATIBILITY WARNING: When compiling with GNU libraries (Linux), the argument order
// is silently permuted! This uses the BSD/OS X ordering.
int capture_move_comparator(const board *board, const move *a, const move *b) {
int a_victim_value;
switch(a->captured.type) {
case 'P': a_victim_value = 1; break;
case 'N': a_victim_value = 3; break;
case 'B': a_victim_value = 3; break;
case 'R': a_victim_value = 5; break;
case 'Q': a_victim_value = 9; break;
case 'K': a_victim_value = 200; break;
case '0': a_victim_value = 0; break; // In case we attack an empty square (no_piece)
default: assert(false);
}
int b_victim_value;
switch(b->captured.type) {
case 'P': b_victim_value = 1; break;
case 'N': b_victim_value = 3; break;
case 'B': b_victim_value = 3; break;
case 'R': b_victim_value = 5; break;
case 'Q': b_victim_value = 9; break;
case 'K': b_victim_value = 200; break;
case '0': b_victim_value = 0; break; // In case we attack an empty square (no_piece)
default: assert(false);
}
int a_attacker_value;
switch(at(board, a->from).type) {
case 'P': a_attacker_value = 1; break;
case 'N': a_attacker_value = 3; break;
case 'B': a_attacker_value = 3; break;
case 'R': a_attacker_value = 5; break;
case 'Q': a_attacker_value = 9; break;
case 'K': a_attacker_value = 20; break;
default: assert(false);
}
int b_attacker_value;
switch(at(board, b->from).type) {
case 'P': b_attacker_value = 1; break;
case 'N': b_attacker_value = 3; break;
case 'B': b_attacker_value = 3; break;
case 'R': b_attacker_value = 5; break;
case 'Q': b_attacker_value = 9; break;
case 'K': b_attacker_value = 20; break;
default: assert(false);
}
return ((a_victim_value << 2) - a_attacker_value) - ((b_victim_value << 2) - b_attacker_value);
}
void apply(board *b, move m) {
// Disable the old en passant eligibility for a file
if (b->en_passant_pawn_push_col_history[b->last_move_ply] != -1) {
b->hash ^= zobrist_en_passant_files[b->en_passant_pawn_push_col_history[b->last_move_ply]];
}
// Information
piece moved_piece = at(b, m.from);
piece new_piece = p_eq(m.promote_to, no_piece) ? moved_piece : m.promote_to;
// If the move we will apply is en passant, remove the captured pawn
if (m.en_passant_capture) {
uint8_t en_passant_capture_row = moved_piece.white ? 4 : 3;
coord en_pasant_capture_square = (coord){b->en_passant_pawn_push_col_history[b->last_move_ply], en_passant_capture_row};
set(b, en_pasant_capture_square, no_piece);
}
// Transform board and hash
b->hash ^= tt_pieceval(b, m.from);
b->hash ^= tt_pieceval(b, m.to);
set(b, m.to, new_piece);
set(b, m.from, no_piece);
b->hash ^= tt_pieceval(b, m.to);
b->hash ^= zobrist_black_to_move;
b->black_to_move = !b->black_to_move;
b->last_move_ply++;
// For en passant
b->en_passant_pawn_push_col_history[b->last_move_ply] = -1;
if (at(b, m.to).type == 'P' && abs(m.to.row - m.from.row) == 2) {
b->en_passant_pawn_push_col_history[b->last_move_ply] = m.to.col;
// En passant capture now enabled on this file
b->hash ^= zobrist_en_passant_files[b->en_passant_pawn_push_col_history[b->last_move_ply]];
}
// Manually move rook for castling
if (m.c != N) { // Manually move rook
uint8_t rook_from_col = ((m.c == K) ? 7 : 0);
uint8_t rook_to_col = ((m.c == K) ? 5 : 3);
b->hash ^= tt_pieceval(b, (coord){rook_from_col, m.from.row});
b->b[rook_to_col][m.to.row] = (piece){'R', at(b, m.to).white}; // !!
b->b[rook_from_col][m.from.row] = no_piece;
b->hash ^= tt_pieceval(b, (coord){rook_to_col, m.to.row});
}
// King moves always strip castling rights
if (moved_piece.white && moved_piece.type == 'K') {
if (b->castle_rights_wk) {
b->hash ^= zobrist_castle_wk;
b->castle_wk_lost_on_ply = b->last_move_ply;
b->castle_rights_wk = false;
}
if (b->castle_rights_wq) {
b->hash ^= zobrist_castle_wq;
b->castle_wq_lost_on_ply = b->last_move_ply;
b->castle_rights_wq = false;
}
} else if (!moved_piece.white && moved_piece.type == 'K') {
if (b->castle_rights_bk) {
b->hash ^= zobrist_castle_bk;
b->castle_bk_lost_on_ply = b->last_move_ply;
b->castle_rights_bk = false;
}
if (b->castle_rights_bq) {
b->hash ^= zobrist_castle_bq;
b->castle_bq_lost_on_ply = b->last_move_ply;
b->castle_rights_bq = false;
}
}
if (moved_piece.type == 'K') {
if (moved_piece.white) b->white_king = m.to;
else b->black_king = m.to;
}
// Moves involving rook squares always strip castling rights
if ((c_eq(m.from, wqr) || c_eq(m.to, wqr)) && b->castle_rights_wq) {
b->castle_rights_wq = false;
b->hash ^= zobrist_castle_wq;
b->castle_wq_lost_on_ply = b->last_move_ply;
}
if ((c_eq(m.from, wkr) || c_eq(m.to, wkr)) && b->castle_rights_wk) {
b->castle_rights_wk = false;
b->hash ^= zobrist_castle_wk;
b->castle_wk_lost_on_ply = b->last_move_ply;
}
if ((c_eq(m.from, bqr) || c_eq(m.to, bqr)) && b->castle_rights_bq) {
b->castle_rights_bq = false;
b->hash ^= zobrist_castle_bq;
b->castle_bq_lost_on_ply = b->last_move_ply;
}
if ((c_eq(m.from, bkr) || c_eq(m.to, bkr)) && b->castle_rights_bk) {
b->castle_rights_bk = false;
b->hash ^= zobrist_castle_bk;
b->castle_bk_lost_on_ply = b->last_move_ply;
}
}
void unapply(board *b, move m) {
// Information
piece old_piece = p_eq(m.promote_to, no_piece) ? at(b, m.to) : (piece){'P', at(b, m.to).white};
// If we are unapplying a double pawn push, disable en passant
if (b->en_passant_pawn_push_col_history[b->last_move_ply] != -1) {
b->hash ^= zobrist_en_passant_files[b->en_passant_pawn_push_col_history[b->last_move_ply]];
}
// Transform board and hash
b->hash ^= tt_pieceval(b, m.to);
set(b, m.from, old_piece);
set(b, m.to, m.captured);
b->hash ^= tt_pieceval(b, m.from);
b->hash ^= tt_pieceval(b, m.to);
b->hash ^= zobrist_black_to_move;
b->black_to_move = !b->black_to_move;
b->last_move_ply--;
// If the previous move was a double pawn push, enable en passant
if (b->en_passant_pawn_push_col_history[b->last_move_ply] != -1) {
b->hash ^= zobrist_en_passant_files[b->en_passant_pawn_push_col_history[b->last_move_ply]];
}
// If we just unapplied an en passant move, put the pawn back
if (m.en_passant_capture) {
uint8_t en_passant_capture_row = old_piece.white ? 4 : 3;
coord en_pasant_capture_square = (coord){b->en_passant_pawn_push_col_history[b->last_move_ply], en_passant_capture_row};
piece captured_pawn = (piece) {'P', !old_piece.white};
set(b, en_pasant_capture_square, captured_pawn);
}
if (old_piece.type == 'K') {
if (old_piece.white) b->white_king = m.from;
else b->black_king = m.from;
}
// Manually move rook for castling
if (m.c != N) { // Manually move rook
uint8_t rook_to_col = ((m.c == K) ? 7 : 0);
uint8_t rook_from_col = ((m.c == K) ? 5 : 3);
b->hash ^= tt_pieceval(b, (coord){rook_from_col, m.from.row});
b->b[rook_to_col][m.to.row] = (piece){'R', at(b, m.from).white};
b->b[rook_from_col][m.from.row] = no_piece;
b->hash ^= tt_pieceval(b, (coord){rook_to_col, m.to.row});
}
// Restore castling rights
if (b->castle_wq_lost_on_ply == b->last_move_ply + 1) {
b->castle_rights_wq = true;
b->hash ^= zobrist_castle_wq;
b->castle_wq_lost_on_ply = -1;
}
if (b->castle_wk_lost_on_ply == b->last_move_ply + 1) {
b->castle_rights_wk = true;
b->hash ^= zobrist_castle_wk;
b->castle_wk_lost_on_ply = -1;
}
if (b->castle_bq_lost_on_ply == b->last_move_ply + 1) {
b->castle_rights_bq = true;
b->hash ^= zobrist_castle_bq;
b->castle_bq_lost_on_ply = -1;
}
if (b->castle_bk_lost_on_ply == b->last_move_ply + 1) {
b->castle_rights_bk = true;
b->hash ^= zobrist_castle_bk;
b->castle_bk_lost_on_ply = -1;
}
}