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
//! A module for generating Halton sequences, a deterministic low discrepancy
//! sequence that appears to be random. The uniform distribution and
//! repeatability makes the sequence ideal for choosing sample points or
//! placing objects in 2D or 3D space.
//!
//! # Examples
//!
//! ```
//! use halton::Sequence;
//!
//! let mut grid = [["."; 10]; 10];
//! let alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").skip(1).take(26);
//! let seq = Sequence::new(2).zip(Sequence::new(3)).zip(alpha);
//! for ((x, y), c) in seq {
//!     grid[(y * 10.0) as usize][(x * 10.0) as usize] = c;
//! }
//! for row in grid.iter() {
//!     println!("{}", row.join(" "));
//! }
//! ```
//!
//! Outputs:
//!
//! ``` text
//! . . R . . I . . . .
//! . L . . . . U C . .
//! X . . F . . . . . O
//! . . . J . A . . . .
//! . D . . . . M S . .
//! P . . . V . . . G .
//! . . B . . Y . . . .
//! . T . . . . E . K .
//! H . . . N . . . . W
//! . . . Z . Q . . . .
//! ```

#[cfg(test)]
#[macro_use]
extern crate approx;

const D: usize = 20;

/// An iterator implementing the fast generation of Halton sequences.
/// The method of generation is adapted from _Fast, portable, and reliable
/// algorithm for the calculation of Halton numbers_ by Miroslav Kolar and
/// Seamus O'Shea.
///
/// # Examples
///
/// With a `for` loop:
///
/// ``` no_run
/// use halton::Sequence;
///
/// let seq = Sequence::new(2);
///
/// for x in seq {
///     println!("{}", x);
/// }
/// ```
///
/// Collecting into a `Vec`:
///
/// ```
/// use halton::Sequence;
///
/// let seq = Sequence::new(2);
///
/// assert_eq!(vec![0.5, 0.25, 0.75], seq.take(3).collect::<Vec<f64>>());
/// ```
///
/// Skipping entries on initialisation:
///
/// ```
/// use halton::Sequence;
///
/// // use base 17, skip the first 20 entries
/// let mut seq = Sequence::skip(17, 20);
///
/// assert_eq!(Some(0.23875432525951557), seq.next());
/// ```
pub struct Sequence {
    b: u8,
    d: [u8; D + 1],
    r: [f64; D + 1],
}

impl Sequence {
    /// Constructs a new `Sequence` for `base`.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use halton::Sequence;
    /// let mut seq = Sequence::new(2);
    ///
    /// assert_eq!(Some(0.5), seq.next());
    /// ```
    pub fn new(base: u8) -> Self {
        Sequence {
            b: base,
            d: [0; D + 1],
            r: [0.0; D + 1],
        }
    }

    /// Constructs a new `Sequence` for `base`, skipping `n` elements.
    ///
    /// The method used to skip elements when constructing the `Sequence` is
    /// considerably faster than advancing the iterator to that point.
    ///
    /// # Examples
    ///
    /// Basic usage:
    ///
    /// ```
    /// # use halton::Sequence;
    /// let mut seq = Sequence::skip(2, 8);
    ///
    /// assert_eq!(Some(0.5625), seq.next());
    /// ```
    pub fn skip(base: u8, n: usize) -> Self {
        let b = base;
        let mut n0 = n;
        let mut d = [0; D + 1];
        let mut r = [0.0; D + 1];

        let mut last = 0;
        while n0 >= usize::from(b) {
            d[last] = n0 as u8 % b;
            last += 1;
            n0 /= usize::from(b);
        }
        d[last] = n0 as u8;
        for i in (1..(D + 1)).rev() {
            r[i - 1] = (f64::from(d[i]) + r[i]) / f64::from(b);
        }
        Sequence { b, d, r }
    }
}

impl Iterator for Sequence {
    type Item = f64;

    fn next(&mut self) -> Option<Self::Item> {
        if self.d[D] != 0 {
            return None;
        }

        let mut l = 0;

        self.d[0] += 1;
        if self.d[0] == self.b {
            loop {
                self.d[l] = 0;
                l += 1;
                self.d[l] += 1;
                if self.d[l] != self.b {
                    break;
                };
            }
            self.r[l - 1] = (f64::from(self.d[l]) + self.r[l]) / f64::from(self.b);
            for i in (1..l).rev() {
                self.r[i - 1] = self.r[i] / f64::from(self.b);
            }
            Some(self.r[0] / f64::from(self.b))
        } else {
            Some((f64::from(self.d[0]) + self.r[0]) / f64::from(self.b))
        }
    }
}

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

    #[test]
    fn base_2() {
        let mut seq = Sequence::new(2);
        assert_relative_eq!(0.5, seq.next().unwrap());
        assert_relative_eq!(0.25, seq.next().unwrap());
        assert_relative_eq!(0.75, seq.next().unwrap());
        assert_relative_eq!(0.125, seq.next().unwrap());
        assert_relative_eq!(0.625, seq.next().unwrap());
        assert_relative_eq!(0.375, seq.next().unwrap());
        assert_relative_eq!(0.875, seq.next().unwrap());
        assert_relative_eq!(0.0625, seq.next().unwrap());
        assert_relative_eq!(0.5625, seq.next().unwrap());
    }

    #[test]
    fn base_3() {
        let mut seq = Sequence::new(3);
        assert_relative_eq!(0.3333333333333333, seq.next().unwrap());
        assert_relative_eq!(0.6666666666666666, seq.next().unwrap());
        assert_relative_eq!(0.1111111111111111, seq.next().unwrap());
        assert_relative_eq!(0.4444444444444444, seq.next().unwrap());
        assert_relative_eq!(0.7777777777777777, seq.next().unwrap());
        assert_relative_eq!(0.2222222222222222, seq.next().unwrap());
        assert_relative_eq!(0.5555555555555555, seq.next().unwrap());
        assert_relative_eq!(0.8888888888888888, seq.next().unwrap());
        assert_relative_eq!(0.0370370370370370, seq.next().unwrap());
    }

    #[test]
    fn skip_base_2() {
        let mut seq = Sequence::skip(2, 8);
        assert_relative_eq!(0.5625, seq.next().unwrap());
    }

    #[test]
    fn skip_base_3() {
        let mut seq = Sequence::skip(3, 8);
        assert_relative_eq!(0.0370370370370370, seq.next().unwrap());
    }

    #[test]
    fn last() {
        let mut seq = Sequence::new(2);
        assert_relative_eq!(4.76837158203125e-07, seq.nth(1048575).unwrap());
        assert_eq!(None, seq.next());
    }

    #[test]
    fn skip_last() {
        let mut seq = Sequence::skip(2, 1048575);
        assert_relative_eq!(4.76837158203125e-07, seq.next().unwrap());
        assert_eq!(None, seq.next());
    }

    #[test]
    fn iter() {
        let seq = Sequence::new(2);
        assert_eq!(vec![0.5, 0.25, 0.75], seq.take(3).collect::<Vec<f64>>());
    }
}