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
|
use std::collections::HashMap;
use crate::moves::Move;
use super::Grossmeister;
/// https://www.chessprogramming.org/Node_Types
#[derive(Debug, PartialEq, Clone, Copy)]
pub enum NodeType {
/// Principal variation node - exact score
PV,
/// Fail-high
Cut,
/// Fail-low
All,
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct TranspositionTableItem {
/// Zobrist hash of this position
pub hash: u64,
pub mov: Option<Move>,
pub depth: u8,
pub score: f32,
pub node_type: NodeType,
}
pub const TTABLE_SIZE: u64 = 2u64.pow(23);
#[derive(Debug, Clone)]
pub struct TranspositionTable {
pub always_replace: HashMap<u64, TranspositionTableItem>,
pub depth_preferred: HashMap<u64, TranspositionTableItem>,
}
impl Default for TranspositionTable {
fn default() -> Self {
TranspositionTable {
always_replace: HashMap::with_capacity(TTABLE_SIZE as usize),
depth_preferred: HashMap::with_capacity(TTABLE_SIZE as usize),
}
}
}
impl Grossmeister {
/// Find current position in Transposition Table
/// This operation is safe from collisions since it compares the *full* hash
pub fn transposition(&self) -> Option<&TranspositionTableItem> {
let hash = self.board.hash % TTABLE_SIZE;
self.transposition_table.depth_preferred.get(&hash).and_then(|item| {
if item.hash == self.board.hash {
Some(item)
} else {
None
}
}).or(self.transposition_table.always_replace.get(&hash).and_then(|item| {
if item.hash == self.board.hash {
Some(item)
} else {
None
}
}))
}
pub fn store_transposition(&mut self, transposition: TranspositionTableItem) {
let hash = transposition.hash % TTABLE_SIZE;
self.transposition_table.always_replace.insert(hash, transposition);
if match self.transposition_table.depth_preferred.get(&hash) {
Some(existing_transposition) => transposition.depth >= existing_transposition.depth,
None => true,
} {
self.transposition_table.depth_preferred.insert(hash, transposition);
}
}
pub fn table_full(&self) -> u64 {
let total_entries = self.transposition_table.always_replace.len() + self.transposition_table.depth_preferred.len();
let total_size = TTABLE_SIZE * 2;
(1000.0 * (total_entries as f64 / total_size as f64)) as u64
}
}
|