forrustts 0.2.0

Tools for forward simulation with tree sequence recording
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
//! Compact representation of multiple forward linked lists.
//!
//! This module defines [``NestedForwardList``].  Client
//! code will typically use this type via [``crate::EdgeBuffer``].
//! See the documentation of that type for details.
//!
//! Most of API for this type is used internally, but
//! it is public in case anyone finds other uses for
//! this data structure.

use thiserror::Error;

/// Errror type for [``NestedForwardList``] operations.
#[derive(Error, Debug, PartialEq)]
pub enum NestedForwardListError {
    /// Tail of a list is unexpectedly null.
    #[error("Tail is null")]
    NullTail,
    /// Used for invalid index values.
    #[error("Invalid index")]
    InvalidIndex,
}

/// Result type for [``NestedForwardList``] operations.
pub type Result<T> = std::result::Result<T, NestedForwardListError>;

// NOTE: I am unclear how to add a Key
// to this generic.  Unlike C++, there's
// no notion of a static_assert.  Gotta Google
// this in the future!

/// Representation of multiple forward linked
/// lists flattend into vectors.
///
/// # Overview
///
/// A typical representation of a forward list
/// involves `head`, `next`, and `tail` pointers
/// to allow iteration in one direction over
/// a `Value`.
///
/// The memory layout of such a list could be
/// "node" pointers allocated on the heap.
/// For example, the node pointer could be intrusive,
/// responsible for managing ownership of the `Value`
/// elements.
///
/// Alternately, we could use flat arrays.
///
/// This type is capable of holding multiple
/// linked lists in a single set of flattened arrays.
///
/// Internally, the `head` array is accessed by list indexes.
/// In other words, to access the i-th list, make a request
/// for the i-th `head`.  Likewise for `tail`.
///
/// # Usage
///
/// This section documents typical use.
/// Other parts of the API exist, but are mostly used internally.
/// They are `pub` in case anyone finds them useful.
///
/// ```
/// // Our value type will be i32.
/// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
/// let mut l = ListType::new();
///
/// // Create 4 empty lists
/// l.reset(4);
/// assert_eq!(l.len(), 4);
///
/// // add some data to list starting
/// // at index 2
/// l.extend(2, -1);
///
/// // There are two methods to traverse the list.
/// // 1. Explicitly use head/next values:
///
/// let mut output = vec![];
/// // Get the head of this list
/// let mut n = l.head(2).unwrap();
/// while n != ListType::null() {
///    // fetch returns an immutable reference.
///    output.push(*l.fetch(n).unwrap());
///    // proceed to the next element
///    n = l.next(n).unwrap();
/// }
/// assert_eq!(output, vec![-1]);
///
/// // 2. Use a closure.  The closure
/// // returns `true` to keep iterating,
/// // or `false` to stop, allowing searches.
/// output.clear();
/// l.for_each(2, |x| {output.push(*x); true});
/// assert_eq!(output, vec![-1]);
///
/// // We can add data out of order:
/// l.extend(0, 13).unwrap();
///
/// // Adding at a new index > that what we
/// // asked for with "reset" will automatically
/// // reallocate.  Create a list starting at index
/// // 13
/// l.extend(13, 13512).unwrap();
/// assert_eq!(l.len(), 14);
///
/// // Our existing data are still fine after
/// // this reallocation:
/// output.clear();
/// l.for_each(2, |x| {output.push(*x); true});
/// assert_eq!(output, vec![-1]);
/// ```
///
/// The following functions may be useful:
///
/// * [``NestedForwardList::clear``]
/// * [``NestedForwardList::fetch_mut``]
pub struct NestedForwardList<Value> {
    head_: Vec<i32>,
    tail_: Vec<i32>,
    next_: Vec<i32>,
    data_: Vec<Value>,
}

impl<Value> NestedForwardList<Value> {
    fn insert_new_record(&mut self, k: i32, v: Value) {
        self.data_.push(v);
        let x = (self.data_.len() - 1) as i32;
        self.head_[k as usize] = x;
        self.tail_[k as usize] = self.head_[k as usize];
        self.next_.push(NestedForwardList::<Value>::null());
    }

    fn check_key(&self, k: i32) -> Result<()> {
        if k < 0 {
            Err(NestedForwardListError::InvalidIndex)
        } else {
            Ok(())
        }
    }

    fn check_key_range(&self, k: usize, n: usize) -> Result<()> {
        if k >= n {
            Err(NestedForwardListError::InvalidIndex)
        } else {
            Ok(())
        }
    }

    // Public functions:

    /// Create a new instance
    pub const fn new() -> NestedForwardList<Value> {
        NestedForwardList {
            head_: Vec::<i32>::new(),
            tail_: Vec::<i32>::new(),
            next_: Vec::<i32>::new(),
            data_: Vec::<Value>::new(),
        }
    }

    /// Add an element to a list starting at index `k`.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap();
    /// ```
    pub fn extend(&mut self, k: i32, v: Value) -> Result<()> {
        self.check_key(k)?;

        let idx = k as usize;
        if idx >= self.head_.len() {
            self.head_
                .resize(idx + 1, NestedForwardList::<Value>::null());
            self.tail_
                .resize(idx + 1, NestedForwardList::<Value>::null());
        }

        if self.head_[idx] == NestedForwardList::<Value>::null() {
            self.insert_new_record(idx as i32, v);
            return Ok(());
        }
        let t = self.tail_[idx];
        if t == NestedForwardList::<Value>::null() {
            return Err(NestedForwardListError::NullTail {});
        }
        self.data_.push(v);
        self.tail_[idx] = (self.data_.len() - 1) as i32;
        // NOTE: this differs from fwdpp, to avoid cast,
        // and thus could be failure point?
        self.next_[t as usize] = self.tail_[idx];
        self.next_.push(NestedForwardList::<Value>::null());
        Ok(())
    }

    /// Return the null value,
    /// which is -1.
    #[inline]
    pub fn null() -> i32 {
        -1
    }

    /// Get a mutable reference to a `Value`.
    ///
    /// See [``NestedForwardList::fetch``]
    /// to get an immutable reference.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap(); // 0
    /// l.extend(1, 7).unwrap(); // 3
    /// l.extend(0, 11).unwrap(); // 2
    ///
    /// // Go through elements of list starting at 0
    /// let mut i = l.head(0).unwrap();
    /// assert_eq!(*l.fetch(i).unwrap(), 1);
    ///
    /// // We can change the data contents:
    /// *l.fetch_mut(i).unwrap() = -33;
    /// assert_eq!(*l.fetch(i).unwrap(), -33);
    /// ```    
    #[inline]
    pub fn fetch_mut(&mut self, at: i32) -> Result<&mut Value> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.data_.len())?;
        Ok(&mut self.data_[at as usize])
    }

    /// Get a reference to a `Value`.
    ///
    /// See [``NestedForwardList::fetch_mut``]
    /// to get an immutable reference.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap(); // 0
    /// l.extend(1, 7).unwrap(); // 3
    /// l.extend(0, 11).unwrap(); // 2
    ///
    /// // Go through elements of list starting at
    /// // 0
    /// let mut i = l.head(0).unwrap();
    /// assert_eq!(*l.fetch(i).unwrap(), 1);
    /// i = l.next(i).unwrap();
    /// assert_eq!(*l.fetch(i).unwrap(), 11);
    /// ```    
    #[inline]
    pub fn fetch(&self, at: i32) -> Result<&Value> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.data_.len())?;
        Ok(&self.data_[at as usize])
    }

    /// Get the index of the head entry of a list
    /// beginning at index `at`.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap(); // 0
    /// l.extend(1, 3).unwrap(); // 1
    /// l.extend(0, 5).unwrap(); // 2
    /// l.extend(1, 5).unwrap(); // 3
    /// assert_eq!(l.head(0).unwrap(), 0);
    /// assert_eq!(l.head(1).unwrap(), 1);
    /// ```    
    #[inline]
    pub fn head(&self, at: i32) -> Result<i32> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.head_.len())?;
        Ok(self.head_[at as usize])
    }

    /// Get the index of the tail entry of a list
    /// beginning at index `at`.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap(); // 0
    /// l.extend(1, 3).unwrap(); // 1
    /// l.extend(0, 5).unwrap(); // 2
    /// l.extend(1, 5).unwrap(); // 3
    /// assert_eq!(l.tail(0).unwrap(), 2);
    /// assert_eq!(l.tail(1).unwrap(), 3);
    /// ```    
    #[inline]
    pub fn tail(&self, at: i32) -> Result<i32> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.tail_.len())?;
        Ok(self.tail_[at as usize])
    }

    /// Get the index of the next data element in a list
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap();
    /// l.extend(1, 3).unwrap();
    /// l.extend(0, 5).unwrap();
    /// l.extend(1, 5).unwrap();
    /// let mut i = l.head(1).unwrap();
    /// assert_eq!(i, 1);
    /// let i = l.next(i).unwrap();
    /// assert_eq!(i, 3);
    /// ```
    #[inline]
    pub fn next(&self, at: i32) -> Result<i32> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.next_.len())?;
        Ok(self.next_[at as usize])
    }

    /// Clears all data.
    /// Memory is not released.
    pub fn clear(&mut self) {
        self.data_.clear();
        self.head_.clear();
        self.tail_.clear();
        self.next_.clear();
    }

    /// Traverse all data elements for the list
    /// beginning at index `at`.
    ///
    /// The callback returns a [``bool``].
    /// If the callback returns [``false``], then traversal
    /// ends, allowing linear searches through the data.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut list = ListType::new();
    /// for i in 0..3 {
    ///     list.extend(0, 2 * i).unwrap();
    /// }
    /// for i in 0..5 {
    ///     list.extend(1, 3 * i).unwrap();
    /// }
    /// let mut output = vec![];
    /// list.for_each(0, |x: &i32| {
    ///     output.push(*x);
    ///     true
    /// })
    /// .unwrap();
    /// assert_eq!(output, vec![0, 2, 4]);
    /// ```
    pub fn for_each(&self, at: i32, mut f: impl FnMut(&Value) -> bool) -> Result<()> {
        let mut itr = self.head(at)?;
        while itr != NestedForwardList::<Value>::null() {
            let val = self.fetch(itr)?;
            let check = f(val);
            if !check {
                break;
            }
            itr = self.next(itr)?;
        }
        Ok(())
    }

    /// Set the head/tail elements of the list
    /// beginning at index ``at`` to [``NestedForwardList::null``].
    ///
    /// # Notes
    ///
    /// This effectively "kills off" the list, preventing traversal.
    /// However, the internal data are unaffected and there is
    /// no attempt to reclaim memory.
    ///
    /// A future release may implement a stack of nullified locations,
    /// allowing their re-use.
    ///
    pub fn nullify_list(&mut self, at: i32) -> Result<()> {
        self.check_key(at)?;
        self.check_key_range(at as usize, self.head_.len())?;
        self.check_key_range(at as usize, self.tail_.len())?;
        self.head_[at as usize] = NestedForwardList::<Value>::null();
        self.tail_[at as usize] = NestedForwardList::<Value>::null();
        Ok(())
    }

    /// Executes the following:
    ///
    /// 1. Clears all data via [``NestedForwardList::clear``].
    /// 2. Sets the size of the number of lists to `newize`.
    /// 3. The lists are all empty, and this have head/tail
    ///    values of [``NestedForwardList::null``].
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap();
    /// l.extend(0, 3).unwrap();
    /// l.extend(0, 5).unwrap();
    /// l.extend(1, 4).unwrap();
    /// assert_eq!(l.len(), 2);
    /// assert_eq!(l.head(0).unwrap(), 0);
    /// assert_eq!(l.tail(0).unwrap(), 2);
    /// l.reset(1);
    /// assert_eq!(l.len(), 1);
    /// // The head of this list is now null
    /// assert_eq!(l.head(0).unwrap(), ListType::null());
    /// ```
    pub fn reset(&mut self, newsize: usize) {
        self.clear();
        self.head_
            .resize(newsize, NestedForwardList::<Value>::null());
        self.tail_
            .resize(newsize, NestedForwardList::<Value>::null());
        // .fill() is experimental right now...
        //self.head_.fill(NestedForwardList::<Value>::null());
        //self.tail_.fill(NestedForwardList::<Value>::null());
        // ... so we do this lambda mapping instead
        self.head_.iter_mut().for_each(|x| *x = Self::null());
        self.tail_.iter_mut().for_each(|x| *x = Self::null());
    }

    /// Obtain an iterator over the vector of list
    /// heads.
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// l.extend(0, 1).unwrap();
    /// l.extend(0, 3).unwrap();
    /// l.extend(0, 5).unwrap();
    /// l.extend(1, -11).unwrap();
    /// // List 0 starts at index 0
    /// // and lines 1 starts at index 3
    /// let heads = vec![0, 3];
    /// for (i, j) in l.head_itr().enumerate() {
    ///     assert_eq!(*j, heads[i]);
    /// }
    ///
    /// let mut output = vec![];
    /// for (i, j) in l.head_itr().enumerate() {
    ///     l.for_each(i as i32, |x| {output.push(*x); true});
    /// }
    /// assert_eq!(output, vec![1,3,5,-11]);
    /// ```
    pub fn head_itr(&self) -> std::slice::Iter<'_, i32> {
        self.head_.iter()
    }

    /// Return length of the vector
    /// of list heads.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// assert_eq!(l.len(), 0);
    /// l.extend(10, 1);
    /// assert_eq!(l.len(), 11);
    /// ```
    pub fn len(&self) -> usize {
        self.head_.len()
    }

    /// Return [``true``] if the
    /// vector of list heads is empty.
    ///
    /// ```
    /// type ListType = forrustts::nested_forward_list::NestedForwardList<i32>;
    /// let mut l = ListType::new();
    /// assert_eq!(l.is_empty(), true);
    /// l.extend(10, 1);
    /// assert_eq!(l.is_empty(), false);
    /// ```
    pub fn is_empty(&self) -> bool {
        self.head_.is_empty()
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    type ListType = NestedForwardList<i32>;

    struct Datum {
        datum: i32,
    }

    type DatumList = NestedForwardList<Datum>;

    fn make_data_for_testing() -> ListType {
        let mut list = ListType::new();
        list.reset(2);
        for i in 0..3 {
            list.extend(0, 2 * i).unwrap();
        }
        for i in 0..5 {
            list.extend(1, 3 * i).unwrap();
        }
        assert_eq!(list.head_.len(), 2);
        assert_eq!(list.data_.len(), 8);
        assert_eq!(list.tail_.len(), 2);
        list
    }

    #[test]
    fn test_head_tail() {
        let list = make_data_for_testing();
        assert_eq!(*list.fetch(list.head(0).unwrap()).unwrap(), 0);
        assert_eq!(*list.fetch(list.tail(0).unwrap()).unwrap(), 4);
        assert_eq!(*list.fetch(list.head(1).unwrap()).unwrap(), 0);
        assert_eq!(*list.fetch(list.tail(1).unwrap()).unwrap(), 12);
    }

    #[test]
    fn test_fetch_mut() {
        let mut list = make_data_for_testing();
        let x = list.tail(1).unwrap();
        let y = list.fetch_mut(x).unwrap();
        *y += 1;
        assert_eq!(*list.fetch(list.tail(1).unwrap()).unwrap(), 13);
    }

    #[test]
    fn test_fetch_mut_struct() {
        let mut list = DatumList::new();
        list.reset(1);
        list.extend(0, Datum { datum: 0 }).unwrap();
        let x = list.tail(0).unwrap();
        let y = list.fetch_mut(x).unwrap();
        y.datum = 111;
        assert_eq!(list.fetch(list.tail(0).unwrap()).unwrap().datum, 111);
    }

    #[test]
    fn test_explicit_data_round_trip() {
        let list = make_data_for_testing();

        let mut output = Vec::<i32>::new();
        let mut itr = list.head(0).unwrap();
        while itr != ListType::null() {
            let val = list.fetch(itr).unwrap();
            output.push(*val);
            itr = list.next(itr).unwrap();
        }
        assert_eq!(3, output.len());

        for (idx, val) in output.iter().enumerate().take(3) {
            assert_eq!(2 * idx, *val as usize);
        }

        output.clear();

        itr = list.head(1).unwrap();
        while itr != ListType::null() {
            let val = list.fetch(itr).unwrap();
            output.push(*val);
            itr = list.next(itr).unwrap();
        }
        assert_eq!(5, output.len());

        for (idx, val) in output.iter().enumerate().take(5) {
            assert_eq!(3 * idx, *val as usize);
        }
    }

    #[test]
    fn test_nullify() {
        let mut list = make_data_for_testing();
        list.nullify_list(0).unwrap();
        let mut output = Vec::<i32>::new();
        list.for_each(0, |x: &i32| {
            output.push(*x);
            true
        })
        .unwrap();
        assert_eq!(output.len(), 0);
    }

    #[test]
    fn test_for_each_data_round_trip() {
        let list = make_data_for_testing();
        let mut output = Vec::<i32>::new();

        list.for_each(0, |x: &i32| {
            output.push(*x);
            true
        })
        .unwrap();

        for (idx, val) in output.iter().enumerate().take(3) {
            assert_eq!(2 * idx, *val as usize);
        }

        output.clear();

        list.for_each(1, |x: &i32| {
            output.push(*x);
            true
        })
        .unwrap();

        for (idx, val) in output.iter().enumerate().take(5) {
            assert_eq!(3 * idx, *val as usize);
        }

        output.clear();
        list.for_each(1, |_: &i32| false).unwrap();

        assert_eq!(output.len(), 0);
    }

    #[test]
    fn test_check_key() {
        let mut list = make_data_for_testing();
        list.reset(1);
        let result = list.extend(-1, 2);
        match result {
            Ok(_) => panic!(),
            Err(NestedForwardListError::InvalidIndex) => (),
            Err(NestedForwardListError::NullTail) => panic!(),
        }
    }

    #[test]
    fn test_head_forward_iteration() {
        let list = make_data_for_testing();
        let mut output = Vec::<i32>::new();
        for (i, _) in list.head_itr().enumerate() {
            list.for_each(i as i32, |x: &i32| {
                output.push(*x);
                true
            })
            .unwrap();
        }
        assert_eq!(output.len(), 8);
        for (idx, val) in output.iter().enumerate().take(3) {
            assert_eq!(2 * idx, *val as usize);
        }
        for (idx, val) in output.iter().enumerate().skip(3) {
            assert_eq!(3 * (idx - 3), *val as usize);
        }
    }

    #[test]
    fn test_head_reverse_iteration() {
        let list = make_data_for_testing();
        let mut output = Vec::<i32>::new();
        for (i, _) in list.head_itr().rev().enumerate() {
            list.for_each((list.len() - i - 1) as i32, |x: &i32| {
                output.push(*x);
                true
            })
            .unwrap();
        }
        assert_eq!(output.len(), 8);
        for (idx, val) in output.iter().enumerate().take(5) {
            assert_eq!(3 * idx, *val as usize);
        }
        for (idx, val) in output.iter().enumerate().skip(5) {
            assert_eq!(2 * (idx - 5), *val as usize);
        }
    }
}