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
mod die;
use cfg_if::cfg_if;
use std::collections::HashMap;
use std::convert::TryFrom;

pub trait Element: Eq + PartialEq + Copy + Clone + std::hash::Hash {}
impl<T> Element for T where T: Eq + PartialEq + Copy + Clone + std::hash::Hash {}

/// Variable-order Markov chain.
pub struct MarkovChain<T: Element> {
    // the 'memory' for the MarkovChain chain.
    // 1 is the typical MarkovChain chain that only looks
    // back 1 element.
    // 0 is functionally equivalent to a weighteddie.
    order: usize,
    // the number of elements in the key should
    // exactly equal the order of the MarkovChain chain.
    // missing elements should be represented as None.
    probability_map: HashMap<Vec<Option<T>>, die::WeightedDie<T>>,
    optional_elements: Vec<usize>,
}

impl<T: Element> MarkovChain<T> {
    /// Creates a new MarkovChain.
    ///
    /// 'order' is the order of the Markov Chain.
    ///
    /// A value of 1 is your typical Markov Chain,
    /// that only looks back one place.
    ///
    /// A value of 0 is just a weighted die, since
    /// there is no memory.
    ///
    /// You could think of order as the shape of the
    /// input tensor, where the input tensor is the
    /// sliding view / window.
    ///
    /// 'optional_keys' allows you to specify None for
    /// the elements in the given indices during
    /// generation. This drastically increases the memory
    /// usage by 2^optional_elements.len().
    pub fn new(order: usize, optional_elements: &[usize]) -> Self {
        // filter out optional elements that are too big.
        let opts: Vec<usize> = optional_elements
            .clone()
            .into_iter()
            .map(|i| *i)
            .filter(|i| *i < order)
            .collect();
        MarkovChain {
            order,
            probability_map: HashMap::<Vec<Option<T>>, die::WeightedDie<T>>::new(),
            optional_elements: opts,
        }
    }

    /// Truncates elements as needed
    fn to_partial_key(order: usize, view: &[Option<T>]) -> Vec<Option<T>> {
        view.into_iter()
            .skip(view.len() - order)
            .take(order)
            .cloned()
            .collect()
    }

    /// Truncates elements as needed
    fn to_full_key(order: usize, view: &[T]) -> Vec<Option<T>> {
        view.into_iter()
            .skip(view.len() - order)
            .take(order)
            .cloned()
            .map(|e| Some(e))
            .collect()
    }

    fn permute(
        key: Vec<Option<T>>,
        optionals: Vec<usize>,
        mut perms: Vec<Vec<Option<T>>>,
    ) -> Vec<Vec<Option<T>>> {
        if optionals.len() == 0 {
            perms.push(key);
            perms
        } else {
            let mut off = key.clone();
            off[optionals[0]] = None;
            let on = key.clone();

            perms = Self::permute(off, optionals[1..].to_vec(), perms);
            perms = Self::permute(on, optionals[1..].to_vec(), perms);
            perms
        }
    }

    // this generates 2^(number of optional keys) keys.
    // this is used during training.
    fn permute_key(&mut self, key: Vec<T>) -> Vec<Vec<Option<T>>> {
        let optioned_key: Vec<Option<T>> = key.into_iter().map(|e| Some(e)).collect();
        Self::permute(optioned_key, self.optional_elements.clone(), vec![])
    }

    /// Feeds training data into the model.
    ///
    /// 'view' is the sliding window of elements to load
    /// into the MarkovChain chain. the number of elements in
    /// view should be self.order + 1 (excess will be ignored).
    /// the last element
    /// in view is the element to increase the weight of.
    ///
    /// 'weight_delta' should be the number of times we're
    /// loading this view into the model (typically 1 at
    /// a time).
    pub fn train(&mut self, view: &[T], result: T, weight_delta: i32) {
        for partial_key in self.permute_key(view.clone().to_vec()) {
            // Train not just on the full key, but all partial ones as well.
            self.probability_map
                .entry(partial_key)
                .and_modify(|d| {
                    d.modify(result, weight_delta);
                })
                .or_insert((|| {
                    let mut d = die::WeightedDie::new();
                    d.modify(result, weight_delta);
                    d
                })());
        }
    }

    /// Generates the next value, given the previous item(s).
    ///
    /// view is the sliding window of the latest elements.
    /// only the last self.order elements are looked at.
    ///
    /// rand_val allows for a deterministic result, if supplied.
    pub fn generate_deterministic_from_partial(
        &self,
        view: &[Option<T>],
        rand_val: u64,
    ) -> Option<T> {
        let key = MarkovChain::to_partial_key(self.order, view);

        match self.probability_map.get(&key) {
            Some(v) => v.roll(Some(rand_val)),
            None => None,
        }
    }

    /// Generates the next value, given the previous item(s).
    ///
    /// view is the sliding window of the latest elements.
    /// only the last self.order elements are looked at.
    ///
    /// rand_val allows for a deterministic result, if supplied.
    pub fn generate_deterministic(&self, view: &[T], rand_val: u64) -> Option<T> {
        let key = MarkovChain::to_full_key(self.order, view);

        match self.probability_map.get(&key) {
            Some(v) => v.roll(Some(rand_val)),
            None => None,
        }
    }

    cfg_if! {
        if #[cfg(feature = "rand")] {
            /// Generates the next value, given the previous item(s).
            ///
            /// view is the sliding window of the latest elements.
            /// only the last self.order elements are looked at.
            pub fn generate(&self, view: &[T]) -> Option<T> {
                let key = MarkovChain::to_full_key(self.order, view);

                match self.probability_map.get(&key) {
                    Some(v) => v.roll(None),
                    None => None,
                }
            }

            /// Generates the next value, given the previous item(s).
            ///
            /// view is the sliding window of the latest elements.
            /// only the last self.order elements are looked at.
            pub fn generate_from_partial(&self, view: &[Option<T>]) -> Option<T> {
                let key = MarkovChain::to_partial_key(self.order, view);

                match self.probability_map.get(&key) {
                    Some(v) => v.roll(None),
                    None => None,
                }
            }
        }
    }

    /// Returns the probability of getting 'result', given
    /// 'view'.
    pub fn probability(&self, view: &[Option<T>], result: T) -> f32 {
        let key = MarkovChain::to_partial_key(self.order, view);

        let map = self.probability_map.get_key_value(&key);
        match map {
            Some(v) => v.1.get_probability(result),
            None => 0.0,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty() {
        let m0 = MarkovChain::new(0, &[]);
        assert_eq!(m0.generate(&[]), None);
        assert_eq!(m0.generate(&[1]), None);
        assert_eq!(m0.generate_deterministic(&[], 33), None);

        let m1 = MarkovChain::new(1, &[]);
        assert_eq!(m1.generate(&[1]), None);
        assert_eq!(m1.generate(&[1, 1]), None);
        assert_eq!(m1.generate_deterministic(&[1], 33), None);

        let m2 = MarkovChain::new(2, &[]);
        assert_eq!(m2.generate(&[1, 1]), None);
        assert_eq!(m2.generate(&[1, 1, 1]), None);
        assert_eq!(m2.generate_deterministic(&[1, 1], 33), None);
    }

    #[test]
    fn alphabet_first_order() {
        let mut m = MarkovChain::new(1, &[]);

        // this could have just been a number range,
        // but it serves as an example of how to encode
        // an alphabet
        let alpha: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
        let encoded: Vec<u64> = alpha
            .clone()
            .into_iter()
            .enumerate()
            .map(|(i, _x)| i as u64)
            .collect();

        for i in m.order..encoded.len() {
            m.train(&[encoded[i - 1]], encoded[i], 1);
        }

        for i in 0..(encoded.len() - 1) {
            let next = m.generate(&[encoded[i]].clone());
            match next {
                Some(v) => assert_eq!(v, encoded[i + 1]),
                None => panic!(
                    "can't predict next letter after {} (encoded as {})",
                    alpha[i], encoded[i]
                ),
            };
        }
    }

    #[test]
    fn alphabet_second_order() {
        let mut m = MarkovChain::new(2, &[]);

        // this could have just been a number range,
        // but it serves as an example of how to encode
        // an alphabet
        let alpha: Vec<char> = "abcdefghijklmnopqrstuvwxyz".chars().collect();
        let encoded: Vec<u64> = (0..alpha.len()).map(|x| x as u64).collect();

        for i in m.order..encoded.len() {
            m.train(&[encoded[i - 2], encoded[i - 1]], encoded[i], 1);
        }

        for i in 1..(encoded.len() - 1) {
            let next = m.generate(&[encoded[i - 1], encoded[i].clone()]);
            match next {
                Some(v) => assert_eq!(v, encoded[i + 1]),
                None => panic!(
                    "can't predict next letter after {} (encoded as {})",
                    alpha[i], encoded[i]
                ),
            };
        }
    }
}