pounce 2.0.2

A mediocre (but trying its best) uci chess engine
Documentation
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
use std::sync::atomic::AtomicBool;
use std::time::Instant;

use arrayvec::ArrayVec;

use crate::chess::{Accumulator, Color, GameResult, Move, Position, Role, Square};
use crate::engine::eval::{self, nnue};
use crate::engine::limits::Limits;
use crate::engine::movepicker::{MAX_MOVES, MovePicker};
use crate::engine::time_management::SearchCop;
use crate::engine::tt::{Entry, EntryType, Table};

const MAX_DEPTH: u8 = 64;
pub const MAX_PLY: u8 = 128;

static mut REDUCTIONS: [[u8; MAX_MOVES]; MAX_DEPTH as usize] = [[0; MAX_MOVES]; MAX_DEPTH as usize];

pub fn init_reductions() {
    unsafe {
        #[allow(clippy::needless_range_loop)]
        for m in 1..MAX_MOVES {
            for depth in 1..MAX_DEPTH as usize {
                let reduction = 1. + ((depth as f32).ln() * (m as f32).ln()) / 2.;
                REDUCTIONS[depth][m] = reduction as u8;
            }
        }
    }
}
#[derive(Debug, Clone, Copy)]
pub struct SearchResult {
    pub bestmove: Move,
    pub score: i16,
    pub depth: i32,
    pub done_early: bool,
}

pub struct Stats {
    pub nodes: u64,
    pub effort: [[u64; Square::NUM]; Square::NUM],
    pub pv: [[Move; MAX_PLY as usize]; MAX_PLY as usize],
    pub pv_length: [u8; MAX_PLY as usize],
    pub start_time: Instant,
}

impl Default for Stats {
    fn default() -> Self {
        Self {
            nodes: 0,
            effort: [[0; Square::NUM]; Square::NUM],
            pv: [[Move::NONE; MAX_PLY as usize]; MAX_PLY as usize],
            pv_length: [0; MAX_PLY as usize],
            start_time: Instant::now(),
        }
    }
}

impl Stats {
    fn reset(&mut self) {
        self.nodes = 0;
        self.effort = [[0; Square::NUM]; Square::NUM];
        self.pv = [[Move::NONE; MAX_PLY as usize]; MAX_PLY as usize];
        self.pv_length = [0; MAX_PLY as usize];
        self.start_time = Instant::now();
    }

    fn uci_info(&self, depth: i32, score: i16, hashfull: f64) {
        let elapsed = self.start_time.elapsed().as_millis() + 1;
        let nps = (self.nodes as u128 * 1000) / elapsed;
        let pv = (0..self.pv_length[0])
            .map(|i| self.pv[0][i as usize].to_string())
            .collect::<Vec<String>>()
            .join(" ");
        if score.abs() > eval::MATE_IN_PLY {
            let ply = score.signum() * (1 + eval::MATE - score.abs()) / 2;

            println!(
                "info depth {} score mate {} time {} nodes {} nps {} hashfull {} pv {}",
                depth, ply, elapsed, self.nodes, nps, hashfull, pv
            );
        } else {
            println!(
                "info depth {} score cp {} time {} nodes {} nps {}, hashfull {} pv {}",
                depth, score, elapsed, self.nodes, nps, hashfull, pv
            );
        }
    }

    pub fn uci_info_done_early(&self, mv: Move, depth: i32, score: i16, hashfull: f64) {
        let elapsed = self.start_time.elapsed().as_millis() + 1;
        let nps = (self.nodes as u128 * 1000) / elapsed;
        if score.abs() > eval::MATE_IN_PLY {
            let ply = score.signum() * (1 + eval::MATE - score.abs()) / 2;

            println!(
                "info depth {} score mate {} time {} nodes {} nps {} hashfull {} pv {}",
                depth, ply, elapsed, self.nodes, nps, hashfull, mv
            );
        } else {
            println!(
                "info depth {} score cp {} time {} nodes {} nps {}, hashfull {} pv {}",
                depth, score, elapsed, self.nodes, nps, hashfull, mv
            );
        }
    }
}

pub struct Search<'a> {
    pub stats: Stats,

    position: Position,
    accum: eval::nnue::NNUEAccumulator<'a, 64>,

    current_move: [Move; MAX_PLY as usize],
    history: [[[i16; Square::NUM]; Square::NUM]; Color::NUM],
    killers: [[Move; 2]; MAX_PLY as usize],
    tt: &'a Table,

    tm: SearchCop,

    stop: &'a AtomicBool,

    silent: bool,
    thread_idx: usize,
}

impl<'a> Search<'a> {
    pub fn new(
        position: Position,
        limits: Limits,
        tt: &'a Table,
        stop: &'a AtomicBool,
        thread_idx: usize,
        silent: bool,
        net: &'a nnue::PerspectiveNet<64>,
    ) -> Self {
        let side = position.side;
        let mut accum = eval::nnue::NNUEAccumulator::new(net);
        accum.reset(&position);
        Search {
            accum,
            current_move: [Move::NONE; MAX_PLY as usize],
            history: [[[0; Square::NUM]; Square::NUM]; Color::NUM],
            killers: [[Move::NONE; 2]; MAX_PLY as usize],
            tm: SearchCop::new(limits, side),
            position,
            silent,
            stats: Stats::default(),
            stop,
            thread_idx,
            tt,
        }
    }

    pub fn think(&mut self) -> SearchResult {
        self.stats.reset();
        self.iterative_deepening()
    }

    fn iterative_deepening(&mut self) -> SearchResult {
        let max_depth = self.tm.depth.unwrap_or(MAX_DEPTH) as i32;
        let mut bestmove = Move::NONE;
        let mut score = 0;
        let mut depth_reached = 0;
        let mut done_early = false;

        for depth in 1..=max_depth {
            if self.done_thinking() {
                break;
            }

            let depth_score = self.aspiration(depth, score);

            if self.done_thinking() {
                done_early = true;
                break;
            }

            score = depth_score;
            bestmove = self.stats.pv[0][0];
            depth_reached = depth;

            if !self.silent && self.thread_idx == 0 {
                self.stats.uci_info(depth, score, self.tt.hashfull());
            }

            self.tm.adjust(&self.stats);
            if self.tm.time_up_deepening(&self.stats) {
                break;
            }
        }

        if bestmove == Move::NONE {
            bestmove = self.stats.pv[0][0];
        }

        SearchResult {
            bestmove,
            score,
            depth: depth_reached,
            done_early,
        }
    }

    fn aspiration(&mut self, depth: i32, prev: i16) -> i16 {
        let mut delta = 50;
        let (mut alpha, mut beta) = if depth > 6 {
            (prev - delta, prev + delta)
        } else {
            (-eval::INFINITY, eval::INFINITY)
        };

        loop {
            if self.done_thinking() {
                return 0;
            }

            let score = self.search(depth, alpha, beta, 0, true, true);

            if score <= alpha {
                beta = alpha + (beta - alpha) / 2;
                alpha = (-eval::INFINITY).max(alpha.saturating_sub(delta));
            } else if score >= beta {
                beta = (eval::INFINITY).min(beta.saturating_add(delta));
            } else {
                return score;
            }

            delta = delta.saturating_add(delta / 2);
            if delta > 1000 {
                alpha = -eval::INFINITY;
                beta = eval::INFINITY;
            }
        }
    }

    fn search(
        &mut self,
        mut depth: i32,
        mut alpha: i16,
        mut beta: i16,
        ply: u8,
        is_pv: bool,
        is_root: bool,
    ) -> i16 {
        if self.done_thinking() {
            return 0;
        }
        if depth >= MAX_DEPTH as i32 || ply >= MAX_PLY {
            return eval::score_nnue(&self.position, &self.accum);
        }
        self.stats.nodes += 1;

        self.stats.pv_length[ply as usize] = ply;

        debug_assert!(alpha < beta);
        debug_assert_eq!(self.position.key, self.position.zobrist_hash());

        if !is_root {
            match self.position.is_draw() {
                Some(GameResult::Draw) => return eval::DRAW,
                // test if this is between alpha and beta?
                Some(GameResult::Loss) => return -eval::MATE + ply as i16,
                _ => {}
            }

            let repetition_count = if is_pv { 2 } else { 1 };
            if self.position.is_repetition(repetition_count) {
                return eval::DRAW;
            }
        }

        if self.position.in_check() {
            depth += 1;
            if depth >= MAX_DEPTH as i32 {
                return eval::score_nnue(&self.position, &self.accum);
            }
        }

        // Go to quiescence search if depth is 0
        if depth <= 0 {
            return self.quiescence_search(alpha, beta, is_pv);
        }

        // Probe the transposition table
        let mut tt_eval = None;
        let mut tt_move = Move::NONE;
        if let Some(entry) = self.tt.probe(self.position.key) {
            tt_move = entry.best_move;
            let score = denormalize_score(entry.score, ply);
            tt_eval = Some(score);
            if entry.depth as i32 >= depth
                && !is_pv
                && self.current_move[ply as usize - 1] != Move::NULL
                && self.position.halfmove_clock < 80
            {
                match entry.score_type {
                    // Exact score
                    EntryType::Exact => return score,
                    // Lower bound
                    EntryType::LowerBound => alpha = alpha.max(score),
                    // Upper bound
                    EntryType::UpperBound => beta = beta.min(score),
                    EntryType::None => {}
                }
                if alpha >= beta {
                    return score;
                }
            }
        }

        let static_eval = tt_eval.unwrap_or(eval::score_nnue(&self.position, &self.accum));

        // internal iterative reduction
        if !is_root && depth >= 6 && !self.position.in_check() && tt_move == Move::NONE {
            depth -= 1;
        }

        // Null move pruning
        if !is_pv
            && depth >= 3
            && self.position.non_pawn_material(self.position.side)
            && !self.position.in_check()
            && static_eval >= beta
            && (ply < 1 || self.current_move[(ply - 1) as usize] != Move::NULL)
        {
            self.position.make_null_move_with(&mut self.accum);
            self.current_move[ply as usize] = Move::NULL;

            let reduced_depth = depth - (3 + (depth / 5));
            let null_score = -self.search(reduced_depth, -beta, -beta + 1, ply + 1, false, false);

            self.position.unmake_null_move_with(&mut self.accum);
            self.current_move[ply as usize] = Move::NONE;

            if null_score >= beta {
                if null_score >= (eval::MATE_IN_PLY) {
                    return beta;
                }
                return null_score;
            }
        }

        // Reverse futility pruning
        if !is_pv
            && (-eval::MATE_IN_PLY..eval::MATE_IN_PLY).contains(&beta)
            && (-eval::MATE_IN_PLY..eval::MATE_IN_PLY).contains(&static_eval)
            && !self.position.in_check()
            && depth < 7
            && static_eval.saturating_sub(300 * depth as i16) >= beta
        {
            return static_eval - 300 * depth as i16;
        }

        let mut best_move = Move::NONE;
        let mut best = -eval::INFINITY;
        let mut move_count = 0;
        let mut quiets: ArrayVec<Move, 64> = ArrayVec::new();

        let mut move_picker =
            MovePicker::new_ab_search(&self.position, tt_move, self.killers[ply as usize]);
        while let Some(mv) = move_picker.next(&self.position, &self.history) {
            move_count += 1;
            let capture = mv.is_capture(&self.position);

            // Late Move Pruning: skip late quiet moves at shallow depths
            if !is_pv
                && !capture
                && !self.position.in_check()
                && depth <= 3
                && move_count > (3 + depth * depth) as u8
                && mv != self.killers[ply as usize][0]
                && mv != self.killers[ply as usize][1]
            {
                continue;
            }

            // store node count for effort calculation
            let before_nodes = self.stats.nodes;

            self.position.make_move_with(mv, &mut self.accum);
            self.current_move[ply as usize] = mv;

            let mut score = -eval::INFINITY;

            // LMR
            let needs_full_search = if depth >= 3 && !self.position.in_check() && move_count > 4 {
                let reduction = self.reduction(depth, move_count);
                let mut rdepth = (depth - 1 - reduction).clamp(1, depth - 2);

                // Reduce less in PV nodes
                if is_pv {
                    rdepth += 1;
                }

                // reduce more in non-capture moves
                if move_count > 15 && !capture {
                    rdepth -= 1;
                }

                score = -self.search(rdepth, -alpha - 1, -alpha, ply + 1, false, false);

                score > alpha && rdepth < depth - 1
            } else {
                move_count > 1 || !is_pv
            };

            if needs_full_search {
                score = -self.search(depth - 1, -alpha - 1, -alpha, ply + 1, false, false);
            }

            if is_pv && (move_count == 1 || score > alpha && score < beta) {
                score = -self.search(depth - 1, -beta, -alpha, ply + 1, true, false);
            }

            self.position.unmake_move_with(mv, &mut self.accum);
            self.current_move[ply as usize] = Move::NONE;

            // store effort at root
            if is_root {
                self.stats.effort[mv.from()][mv.to()] = self.stats.nodes - before_nodes;
            }

            if score > best {
                best = score;
                best_move = mv;

                self.stats.pv[ply as usize][ply as usize] = mv;
                for j in (ply + 1)..self.stats.pv_length[ply as usize + 1] {
                    self.stats.pv[ply as usize][j as usize] =
                        self.stats.pv[ply as usize + 1][j as usize];
                }

                self.stats.pv_length[ply as usize] = self.stats.pv_length[ply as usize + 1];

                if score > alpha {
                    alpha = score;
                    if score >= beta {
                        if !capture {
                            self.update_killers(mv, ply);
                            let bonus = 2000.min(350 * depth as i16 - 350);
                            self.update_history(mv, bonus);

                            for quiet in quiets.iter() {
                                self.update_history(*quiet, -bonus / 2);
                            }
                        }

                        break;
                    }
                }
            }

            if !capture && quiets.len() < quiets.capacity() {
                quiets.push(mv);
            }
        }

        if move_count == 0 {
            if self.position.in_check() {
                return -eval::MATE + ply as i16;
            } else {
                return 0;
            }
        }

        let entry_type = if best >= beta {
            EntryType::LowerBound
        } else if is_pv && best_move != Move::NULL {
            EntryType::Exact
        } else {
            EntryType::UpperBound
        };

        if !self.stop.load(std::sync::atomic::Ordering::Relaxed) {
            self.tt.set(Entry::new(
                self.position.key,
                depth as u8,
                normalize_score(best, ply),
                entry_type,
                best_move,
            ));
        }
        best
    }

    fn quiescence_search(&mut self, mut alpha: i16, beta: i16, is_pv: bool) -> i16 {
        self.stats.nodes += 1;

        if self.done_thinking() {
            return 0;
        }

        match self.position.is_draw() {
            Some(GameResult::Draw) => return eval::DRAW,
            // don't have ply here so this is a guess
            Some(GameResult::Loss) => return -eval::MATE + MAX_PLY as i16,
            _ => {}
        }

        let repetition_count = if is_pv { 2 } else { 1 };
        if self.position.is_repetition(repetition_count) {
            return eval::DRAW;
        }

        // Probe tt
        let mut tt_move = Move::NONE;
        if let Some(entry) = self.tt.probe(self.position.key) {
            tt_move = entry.best_move;
            if !is_pv {
                let score = denormalize_score(entry.score, MAX_PLY);
                match entry.score_type {
                    EntryType::Exact => return score,
                    EntryType::LowerBound => {
                        if score >= beta {
                            return score;
                        }
                    }
                    EntryType::UpperBound => {
                        if score <= alpha {
                            return score;
                        }
                    }
                    _ => {}
                }
            }
        }

        let stand_pat = eval::score_nnue(&self.position, &self.accum);
        if stand_pat >= beta {
            return stand_pat;
        }

        if stand_pat > alpha {
            alpha = stand_pat;
        }

        let mut best = stand_pat;
        let mut best_move = Move::NONE;

        let best_case_score = {
            let mut value = eval::PIECE_VALUES[Role::Pawn as usize];

            for role in ((Role::Pawn as usize)..=(Role::Queen as usize)).rev() {
                if self
                    .position
                    .by_color_role(self.position.side.opponent(), Role::new(role as u8))
                    .any()
                {
                    value = eval::PIECE_VALUES[role];
                    break;
                }
            }

            // check for promotions
            if (self.position.by_color_role(self.position.side, Role::Pawn)
                & self.position.side.opponent().home_rank())
            .any()
            {
                value += eval::PIECE_VALUES[Role::Queen as usize]
                    - eval::PIECE_VALUES[Role::Pawn as usize];
            }

            value
        };

        let delta_margin = alpha.saturating_sub(stand_pat).saturating_sub(425) as i32;
        if best_case_score < delta_margin {
            return stand_pat;
        }

        let see_margin = alpha.saturating_sub(stand_pat).saturating_sub(500).max(1) as i32;
        let mut move_picker = MovePicker::new_quiescence(&self.position, tt_move, see_margin);
        while let Some(mv) = move_picker.next(&self.position, &self.history) {
            self.position.make_move_with(mv, &mut self.accum);
            let score = -self.quiescence_search(-beta, -alpha, is_pv);
            self.position.unmake_move_with(mv, &mut self.accum);

            if score > best {
                best = score;
                best_move = mv;
                if score > alpha {
                    alpha = score;
                    if score >= beta {
                        break;
                    }
                }
            }
        }

        let entry_type = if best >= beta {
            EntryType::LowerBound
        } else {
            EntryType::UpperBound
        };

        if !self.stop.load(std::sync::atomic::Ordering::Relaxed) {
            self.tt.set(Entry::new(
                self.position.key,
                0,
                normalize_score(best, MAX_PLY),
                entry_type,
                best_move,
            ));
        }

        best
    }

    pub fn update_killers(&mut self, mv: Move, ply: u8) {
        self.killers[ply as usize][1] = self.killers[ply as usize][0];
        self.killers[ply as usize][0] = mv;
    }

    fn update_history(&mut self, mv: Move, bonus: i16) {
        self.history[self.position.side][mv.from()][mv.to()] += bonus
            - ((self.history[self.position.side][mv.from()][mv.to()] as i32 * bonus.abs() as i32)
                / 16384) as i16;
    }

    fn reduction(&self, depth: i32, move_count: u8) -> i32 {
        unsafe { REDUCTIONS[depth as usize][move_count as usize] as i32 }
    }

    pub fn done_thinking(&self) -> bool {
        if self.stop.load(std::sync::atomic::Ordering::Relaxed)
            || self.tm.nodes.is_some_and(|n| self.stats.nodes >= n)
        {
            return true;
        }

        if self.stats.nodes % 2048 == 0 && self.tm.time_up(&self.stats) {
            self.stop.store(true, std::sync::atomic::Ordering::Relaxed);
            return true;
        }

        false
    }

    pub fn set_silent(&mut self, silent: bool) {
        self.silent = silent;
    }
}

fn normalize_score(score: i16, ply: u8) -> i16 {
    if score > eval::MATE_IN_PLY {
        score + ply as i16
    } else if score < -eval::MATE_IN_PLY {
        score - ply as i16
    } else {
        score
    }
}

fn denormalize_score(score: i16, ply: u8) -> i16 {
    if score >= eval::MATE_IN_PLY {
        score - ply as i16
    } else if score <= -eval::MATE_IN_PLY {
        score + ply as i16
    } else {
        score
    }
}