Skip to main content

width_search/
novelty.rs

1use std::collections::HashSet;
2
3/// Records every feature tuple of size `<= k` seen so far.
4///
5/// The novelty of a state is the size of the smallest tuple of its features
6/// that has not been seen before. Size-1 and size-2 tuples use dense bitsets
7/// (`n` and `n(n-1)/2` bits); larger sizes fall back to hashing.
8#[derive(Clone, Debug)]
9pub struct NoveltyTable {
10    /// Width bound: the largest tuple size recorded. At least 1.
11    k: usize,
12    /// Number of features; every feature id is below it.
13    n: usize,
14    /// Seen single features, indexed by feature id.
15    seen1: Vec<bool>,
16    /// Seen pairs as a bitset over [`NoveltyTable::pair_index`]; empty when `k < 2`.
17    seen2: Vec<u64>,
18    /// Seen tuples of size 3 to `k`, each sorted ascending.
19    seen_hi: HashSet<Vec<u32>>,
20    /// Reused buffer for the sorted, deduplicated features of the current state.
21    scratch: Vec<u32>,
22}
23
24impl NoveltyTable {
25    /// Creates an empty table for features `0..num_features` and tuples up to size `k`.
26    ///
27    /// Memory is `num_features` bools plus, for `k >= 2`, a bitset of
28    /// `num_features * (num_features - 1) / 2` pairs. For `k >= 3`, every distinct
29    /// tuple of size 3 to `k` seen so far is also kept in a hash set, which grows
30    /// with the explored states rather than with `num_features`.
31    ///
32    /// # Panics
33    ///
34    /// Panics if `k` is 0.
35    #[must_use]
36    pub fn new(num_features: usize, k: usize) -> Self {
37        assert!(k >= 1, "width bound must be at least 1");
38        let pair_bits = if k >= 2 {
39            num_features * num_features.saturating_sub(1) / 2
40        } else {
41            0
42        };
43        Self {
44            k,
45            n: num_features,
46            seen1: vec![false; num_features],
47            seen2: vec![0; pair_bits.div_ceil(64)],
48            seen_hi: HashSet::new(),
49            scratch: Vec::new(),
50        }
51    }
52
53    /// The width bound `k` this table was created with.
54    #[must_use]
55    pub fn width_bound(&self) -> usize {
56        self.k
57    }
58
59    /// Returns the novelty of a state with the given features (`None` if it
60    /// exceeds `k`), and records all of its tuples of size `<= k`.
61    ///
62    /// Duplicate features are ignored.
63    ///
64    /// # Panics
65    ///
66    /// Panics if a feature is not below the `num_features` given to
67    /// [`NoveltyTable::new`].
68    pub fn evaluate_and_insert(&mut self, features: &[u32]) -> Option<usize> {
69        let mut feats = std::mem::take(&mut self.scratch);
70        feats.clear();
71        feats.extend_from_slice(features);
72        feats.sort_unstable();
73        feats.dedup();
74
75        let mut novelty = None;
76        for &f in &feats {
77            let seen = &mut self.seen1[f as usize];
78            if !*seen {
79                *seen = true;
80                novelty.get_or_insert(1);
81            }
82        }
83
84        if self.k >= 2 {
85            for (i, &a) in feats.iter().enumerate() {
86                for &b in &feats[i + 1..] {
87                    let idx = self.pair_index(a as usize, b as usize);
88                    let (word, bit) = (idx / 64, 1u64 << (idx % 64));
89                    if self.seen2[word] & bit == 0 {
90                        self.seen2[word] |= bit;
91                        novelty.get_or_insert(2);
92                    }
93                }
94            }
95        }
96
97        for size in 3..=self.k.min(feats.len()) {
98            let mut tuple = Vec::with_capacity(size);
99            if insert_combinations(&feats, size, 0, &mut tuple, &mut self.seen_hi) {
100                novelty.get_or_insert(size);
101            }
102        }
103
104        self.scratch = feats;
105        novelty
106    }
107
108    /// Index of pair `(a, b)`, `a < b`, in the upper triangle.
109    fn pair_index(&self, a: usize, b: usize) -> usize {
110        a * (2 * self.n - a - 1) / 2 + (b - a - 1)
111    }
112}
113
114/// Inserts every `size`-combination of `feats[start..]` (extending `tuple`);
115/// returns whether any was new.
116fn insert_combinations(
117    feats: &[u32],
118    size: usize,
119    start: usize,
120    tuple: &mut Vec<u32>,
121    seen: &mut HashSet<Vec<u32>>,
122) -> bool {
123    if tuple.len() == size {
124        return seen.insert(tuple.clone());
125    }
126
127    let mut any_new = false;
128    let needed = size - tuple.len();
129    for i in start..=feats.len() - needed {
130        tuple.push(feats[i]);
131        any_new |= insert_combinations(feats, size, i + 1, tuple, seen);
132        tuple.pop();
133    }
134
135    any_new
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn novelty_levels() {
144        let mut t = NoveltyTable::new(4, 3);
145        assert_eq!(t.evaluate_and_insert(&[0, 1]), Some(1));
146        assert_eq!(t.evaluate_and_insert(&[2]), Some(1));
147        assert_eq!(t.evaluate_and_insert(&[0, 2]), Some(2)); // new pair
148        assert_eq!(t.evaluate_and_insert(&[1, 2]), Some(2));
149        assert_eq!(t.evaluate_and_insert(&[0, 1, 2]), Some(3)); // only the triple is new
150        assert_eq!(t.evaluate_and_insert(&[0, 1, 2]), None);
151    }
152
153    #[test]
154    fn pair_index_is_a_bijection() {
155        let t = NoveltyTable::new(7, 2);
156        let mut idx: Vec<_> = (0..7)
157            .flat_map(|a| (a + 1..7).map(move |b| (a, b)))
158            .map(|(a, b)| t.pair_index(a, b))
159            .collect();
160        idx.sort_unstable();
161        assert_eq!(idx, (0..21).collect::<Vec<_>>());
162    }
163}