ddo 2.0.0

DDO a generic and efficient framework for MDD-based optimization.
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
663
664
// Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

//! This module provides the implementation of a solver fringe that forbids the
//! co-occurrence of two sub-problems having the same root state.

use std::{hash::Hash, sync::Arc};
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::cmp::Ordering;
use std::cmp::Ordering::{Greater, Less};

use compare::Compare;
use fxhash::FxHashMap;

use crate::*;
use self::Action::{BubbleDown, BubbleUp, DoNothing};

/// This is a type-safe identifier for some node in the queue.
/// Basically, this NodeId equates to the position of the identified
/// node in the `nodes` list from the `NoDupHeap`.
#[derive(Debug, Copy, Clone)]
struct NodeId(usize);

/// An enum to know what needs to be done with a given node id
#[derive(Debug, Copy, Clone)]
enum Action {
    DoNothing,
    BubbleUp(NodeId),
    BubbleDown(NodeId),
}

/// This is an updatable binary heap backed by a vector which ensures that
/// items remain ordered in the priority queue while guaranteeing that a
/// given state will only ever be present *ONCE* in the priority queue (the
/// node with the longest path to state is the only kept copy).
pub struct NoDupFringe<O>
where
    O: SubProblemRanking,
    O::State: Eq + Hash + Clone,
{
    /// This is the comparator used to order the nodes in the binary heap
    cmp: CompareSubProblem<O>,
    /// A mapping that associates some state to a node identifier.
    states: FxHashMap<Arc<O::State>, NodeId>,
    /// The actual payload (nodes) ordered in the list
    nodes: Vec<SubProblem<O::State>>,
    /// The position of the items in the heap
    pos: Vec<usize>,
    /// This is the actual heap which orders nodes.
    heap: Vec<NodeId>,
    /// The positions in the `nodes` vector that can be recycled.
    recycle_bin: Vec<NodeId>,
}

impl<O> Fringe for NoDupFringe<O>
where
    O: SubProblemRanking,
    O::State: Eq + Hash + Clone,
{
    type State = O::State;

    /// Pushes one node onto the heap while ensuring that only one copy of the
    /// node (identified by its state) is kept in the heap.
    ///
    /// # Note:
    /// In the event where the heap already contains a copy `x` of a node having
    /// the same state as the `node` being pushed. The priority of the node
    /// left in the heap might be affected. If `node` node is "better" (greater
    /// UB and or longer longest path), the priority of the node will be
    /// increased. As always, in the event where the newly pushed node has a
    /// longer longest path than the pre-existing node, that one will be kept.
    fn push(&mut self, mut node: SubProblem<O::State>) {
        let state = Arc::clone(&node.state);

        let action = match self.states.entry(state) {
            Occupied(e) => {
                let id = *e.get();

                // info about the pre-existing node
                let old_lp = self.nodes[id.0].value;
                let old_ub = self.nodes[id.0].ub;
                // info about the new node
                let new_lp = node.value;
                let new_ub = node.ub;
                // make sure that ub is the max of the known ubs
                node.ub = new_ub.max(old_ub);

                let action = if self.cmp.compare(&node, &self.nodes[id.0]) == Greater {
                    BubbleUp(id)
                } else {
                    DoNothing
                };

                if new_lp > old_lp {
                    self.nodes[id.0] = node;
                }
                if new_ub > old_ub {
                    self.nodes[id.0].ub = new_ub;
                }

                action
            }
            Vacant(e) => {
                let id = if self.recycle_bin.is_empty() {
                    let id = NodeId(self.nodes.len());
                    self.nodes.push(node);
                    self.pos.push(0); // dummy
                    id
                } else {
                    let id = self.recycle_bin.pop().unwrap();
                    self.nodes[id.0] = node;
                    id
                };

                self.heap.push(id);
                self.pos[id.0] = self.heap.len() - 1;
                e.insert(id);
                BubbleUp(id)
            }
        };

        // restore the invariants
        self.process_action(action);
    }

    /// Pops the best node out of the heap. Here, the best is defined as the
    /// node having the best upper bound, with the longest `value`.
    fn pop(&mut self) -> Option<SubProblem<Self::State>> {
        if self.is_empty() {
            return None;
        }

        let id = self.heap.swap_remove(0);
        let action = if self.heap.is_empty() {
            DoNothing
        } else {
            self.pos[self.heap[0].0] = 0;
            BubbleDown(self.heap[0])
        };

        self.process_action(action);
        self.recycle_bin.push(id);

        let node = self.nodes[id.0].clone();
        self.states.remove(&node.state);

        Some(node)
    }

    /// Clears the content of the heap to reset it to a state equivalent to
    /// a fresh instantiation of the heap.
    fn clear(&mut self) {
        self.states.clear();
        self.nodes.clear();
        self.pos.clear();
        self.heap.clear();
        self.recycle_bin.clear();
    }

    /// Returns the 'length' of the heap. That is, the number of items that
    /// can still be popped out of the heap.
    fn len(&self) -> usize {
        self.heap.len()
    }
}

impl<O> NoDupFringe<O>
where
    O: SubProblemRanking,
    O::State: Eq + Hash + Clone,
{
    /// Creates a new instance of the no dup heap which uses cmp as
    /// comparison criterion.
    pub fn new(ranking: O) -> Self {
        Self {
            cmp: CompareSubProblem::new(ranking),
            states: Default::default(),
            nodes: vec![],
            pos: vec![],
            heap: vec![],
            recycle_bin: vec![],
        }
    }

    /// Returns true iff the heap is empty (len() == 0)
    pub fn is_empty(&self) -> bool {
        self.heap.is_empty()
    }

    /// Internal helper method to bubble a node up or down, depending of the
    /// specified action.
    fn process_action(&mut self, action: Action) {
        match action {
            BubbleUp(id) => self.bubble_up(id),
            BubbleDown(id) => self.bubble_down(id),
            DoNothing => { /* sweet life */ }
        }
    }
    /// Internal helper method to return the position of a node in the heap.
    fn position(&self, n: NodeId) -> usize {
        self.pos[n.0]
    }
    /// Internal helper method to compare the nodes identified by the ids found
    /// at the given positions in the heap.
    fn compare_at_pos(&self, x: usize, y: usize) -> Ordering {
        let node_x = &self.nodes[self.heap[x].0];
        let node_y = &self.nodes[self.heap[y].0];
        self.cmp.compare(node_x, node_y)
    }
    /// Internal method to bubble a node up and restore the heap invariant.
    fn bubble_up(&mut self, id: NodeId) {
        let mut me = self.position(id);
        let mut parent = self.parent(me);

        while !self.is_root(me) && self.compare_at_pos(me, parent) == Greater {
            let p_id = self.heap[parent];

            self.pos[p_id.0] = me;
            self.pos[id.0] = parent;
            self.heap[me] = p_id;
            self.heap[parent] = id;

            me = parent;
            parent = self.parent(me);
        }
    }
    /// Internal method to sink a node down so as to restore the heap invariant.
    fn bubble_down(&mut self, id: NodeId) {
        let mut me = self.position(id);
        let mut kid = self.max_child_of(me);

        while kid > 0 && self.compare_at_pos(me, kid) == Less {
            let k_id = self.heap[kid];

            self.pos[k_id.0] = me;
            self.pos[id.0] = kid;
            self.heap[me] = k_id;
            self.heap[kid] = id;

            me = kid;
            kid = self.max_child_of(me);
        }
    }
    /// Internal helper method that returns the position of the node which is
    /// the parent of the node at `pos` in the heap.
    fn parent(&self, pos: usize) -> usize {
        if self.is_root(pos) {
            pos
        } else if self.is_left(pos) {
            pos / 2
        } else {
            pos / 2 - 1
        }
    }
    /// Internal helper method that returns the position of the child of the
    /// node at position `pos` which is considered to be the maximum of the
    /// children of that node.
    ///
    /// # Warning
    /// When the node at `pos` is a leaf, this method returns **0** for the
    /// position of the child. This value 0 acts as a marker to tell that no
    /// child is to be found.
    fn max_child_of(&self, pos: usize) -> usize {
        let size = self.len();
        let left = self.left_child(pos);
        let right = self.right_child(pos);

        if left >= size {
            return 0;
        }
        if right >= size {
            return left;
        }

        match self.compare_at_pos(left, right) {
            Greater => left,
            _ => right,
        }
    }
    /// Internal helper method to return the position of the left child of
    /// the node at the given `pos`.
    fn left_child(&self, pos: usize) -> usize {
        pos * 2 + 1
    }
    /// Internal helper method to return the position of the right child of
    /// the node at the given `pos`.
    fn right_child(&self, pos: usize) -> usize {
        pos * 2 + 2
    }
    /// Internal helper method which returns true iff the node at `pos` is the
    /// root of the binary heap (position is zero).
    fn is_root(&self, pos: usize) -> bool {
        pos == 0
    }
    /// Internal helper method which returns true iff the node at `pos` is the
    /// left child of its parent.
    fn is_left(&self, pos: usize) -> bool {
        pos % 2 == 1
    }
    /*
    /// Internal helper method which returns true iff the node at `pos` is the
    /// right child of its parent.
    fn is_right(&self, pos: usize) -> bool {
        pos % 2 == 0
    }
    */
}


#[cfg(test)]
#[allow(clippy::many_single_char_names)]
mod test_no_dup_fringe {
    use crate::*;
    use std::{sync::Arc, cmp::Ordering};

    // by default, it is empty
    #[test]
    fn by_default_it_is_empty() {
        assert!(empty_fringe().is_empty())
    }

    // when the size is zero, then it is empty
    #[test]
    fn when_the_size_is_zero_then_it_is_empty() {
        let fringe = empty_fringe();
        assert_eq!(fringe.len(), 0);
        assert!(fringe.is_empty());
    }

    // when the size is greater than zero, it it not empty
    #[test]
    fn when_the_size_is_greater_than_zero_it_is_not_empty() {
        let fringe = non_empty_fringe();
        assert_eq!(fringe.len(), 1);
        assert!(!fringe.is_empty());
    }

    // when I push a non existing node onto the fringe then the length increases
    #[test]
    fn when_i_push_a_non_existing_node_onto_the_fringe_then_the_length_increases() {
        let mut fringe = empty_fringe();
        fringe.push(SubProblem {
            state: Arc::new(42),
            value: 0,
            path : vec![],
            ub   : 0,
            depth: 0,
        });
        assert_eq!(fringe.len(), 1);
        fringe.push(SubProblem{
            state: Arc::new(43),
            value: 0,
            path : vec![],
            ub: 0,
            depth: 0,
        });
        assert_eq!(fringe.len(), 2);
    }
    // when I push an existing node onto the fringe then the length wont increases
    #[test]
    fn when_i_push_an_existing_node_onto_the_fringe_then_the_length_does_not_increases() {
        let mut fringe = empty_fringe();
        fringe.push(SubProblem {
            state: Arc::new(42),
            value: 0,
            path : vec![],
            ub   : 0,
            depth: 0,
        });
        assert_eq!(fringe.len(), 1);
        fringe.push(SubProblem {
            state: Arc::new(42),
            value: 12,
            path : vec![],
            ub   : 5,
            depth: 0,
        });
        assert_eq!(fringe.len(), 1);
    }
    // when I pop a node off the fringe then the length decreases
    #[test]
    fn when_i_pop_a_node_off_the_fringe_then_the_length_decreases() {
        let mut fringe = non_empty_fringe();
        assert_eq!(fringe.len(), 1);
        fringe.pop();
        assert_eq!(fringe.len(), 0);
    }

    // when I try to pop a node off an empty fringe, I get none
    #[test]
    fn when_i_try_to_pop_a_node_off_an_empty_fringe_i_get_none() {
        let mut fringe = empty_fringe();
        assert_eq!(fringe.pop(), None);
    }

    // when I pop a node, it is always the one with the largest ub (then value)
    #[test]
    fn when_i_pop_a_node_it_is_always_the_one_with_the_largest_ub_then_lp() {
        let mut fringe = empty_fringe();
        let a = SubProblem {
            state: Arc::new(1),
            value: 1,
            path : vec![],
            ub   : 1,
            depth: 0,
        };
        let b = SubProblem {
            state: Arc::new(2),
            value: 2,
            path : vec![],
            ub   : 2,
            depth: 0,
        };
        let c = SubProblem {
            state: Arc::new(3),
            value: 3,
            path : vec![],
            ub   : 3,
            depth: 0,
        };
        let d = SubProblem {
            state: Arc::new(4),
            path: vec![],
            value: 4,
            ub: 4,
            depth: 0,
        };
        let e = SubProblem{
            state: Arc::new(5),
            path: vec![],
            value: 4,
            ub: 5,
            depth: 0,
        };
        let f = SubProblem{
            state: Arc::new(5),
            path: vec![],
            value: 5,
            ub: 5,
            depth: 0,
        };

        fringe.push(a.clone());
        fringe.push(f.clone());
        fringe.push(b.clone());
        fringe.push(d.clone());
        fringe.push(c.clone());
        fringe.push(e);

        assert_eq!(fringe.pop(), Some(f));
        //assert_eq!(fringe.pop(), Some(e)); // node 'e' will never show up
        assert_eq!(fringe.pop(), Some(d));
        assert_eq!(fringe.pop(), Some(c));
        assert_eq!(fringe.pop(), Some(b));
        assert_eq!(fringe.pop(), Some(a));
    }

    // when I pop a node off the fringe, for which multiple copies have been added
    // I retrieve the one with the longest path
    #[test]
    fn when_i_pop_a_node_off_the_fringe_for_which_multiple_copies_have_been_added_then_i_retrieve_the_one_with_longest_path(){
        let pe = vec![
            Decision {variable: Variable(0), value: 4},
        ];

        let pf = vec![
            Decision {variable: Variable(1), value: 5},
        ];

        let ne = SubProblem{
            state: Arc::new(5),
            path: pe,
            value: 4,
            ub: 5,
            depth: 1,
        };
        let nf = SubProblem{
            state: Arc::new(5),
            path: pf,
            value: 5,
            ub: 5,
            depth: 1,
        };

        let mut fringe = empty_fringe();
        fringe.push(ne);
        fringe.push(nf.clone());

        assert_eq!(fringe.pop(), Some(nf));
    }

    // when I clear an empty fringe, it remains empty
    #[test]
    fn when_i_clear_an_empty_fringe_it_remains_empty() {
        let mut fringe = empty_fringe();
        assert!(fringe.is_empty());
        fringe.clear();
        assert!(fringe.is_empty());
    }
    // when I clear a non empty fringe it becomes empty
    #[test]
    fn when_i_clear_a_non_empty_fringe_it_becomes_empty() {
        let mut fringe = non_empty_fringe();
        assert!(!fringe.is_empty());
        fringe.clear();
        assert!(fringe.is_empty());
    }


    /// A dummy state comparator for use in the tests
    #[derive(Debug, Clone, Copy, Default)]
    struct UsizeRanking;
    impl StateRanking for UsizeRanking {
        type State = usize;

        fn compare(&self, a: &Self::State, b: &Self::State) -> Ordering {
            a.cmp(b)
        }
    }

        
    fn empty_fringe() -> NoDupFringe<MaxUB<'static, UsizeRanking>> {
        NoDupFringe::new(MaxUB::new(&UsizeRanking))
    }
    fn non_empty_fringe() -> NoDupFringe<MaxUB<'static, UsizeRanking>> {
        let mut fringe = empty_fringe();
        fringe.push(SubProblem{
            state: Arc::new(42),
            path: vec![],
            value: 0,
            ub: 0,
            depth: 0,
        });
        fringe
    }

    // 

    #[test]
    fn popped_in_order() {
        let nodes = [
            fnode(1, 10, 100),
            fnode(2, 10, 101),
            fnode(3, 10, 102),
            fnode(4, 10, 103),
            fnode(5, 10, 104),
        ];

        let mut heap = empty_fringe();
        push_all(&mut heap, &nodes);
        assert_eq!(5,     heap.len());
        assert!(!heap.is_empty());

        let actual   = pop_all(&mut heap);
        let expected = vec![5, 4, 3, 2, 1];
        assert_eq!(expected,  actual);
        assert_eq!(0,    heap.len());
        assert!(heap.is_empty());
    }
    #[test]
    fn pushing_same_node_multiple_times_does_not_alter_pop_order() {
        let nodes = [
            fnode(1, 10, 100),
            fnode(2, 10, 101),
            fnode(3, 10, 102),
            fnode(4, 10, 103),
            fnode(5, 10, 104),
        ];

        let mut heap = empty_fringe();
        push_all(&mut heap, &nodes);
        push_all(&mut heap, &nodes);
        push_all(&mut heap, &nodes);
        push_all(&mut heap, &nodes);
        push_all(&mut heap, &nodes);
        // even after pushing all nodes five times, there are only 5 nodes in the heap
        assert_eq!(5,     heap.len());
        assert!(!heap.is_empty());

        let actual   = pop_all(&mut heap);
        let expected = vec![5, 4, 3, 2, 1];
        assert_eq!(expected,  actual);
        assert_eq!(0,    heap.len());
        assert!(heap.is_empty());
    }

    #[test]
    fn pushing_nodes_triggers_reordering_if_lplen_is_better_up() {
        let nodes_1 = [
            fnode(1, 10, 100),
            fnode(2, 10, 101),
            fnode(3, 10, 102),
            fnode(4, 10, 103),
            fnode(5, 10, 104),
        ];
        let nodes_2 = [
            fnode(1, 15, 100),
            fnode(2, 15,  99),
            fnode(3, 15,  98),
            fnode(4, 15,  97),
            fnode(5, 15,  96),
        ];
        let nodes_3 = [
            fnode(1, 20,  92),
            fnode(2, 20,  93),
            fnode(3, 20,  94),
            fnode(4, 20,  95),
            fnode(5, 20,  96),
        ];

        let mut heap = empty_fringe();
        push_all(&mut heap, &nodes_1);
        push_all(&mut heap, &nodes_2);
        push_all(&mut heap, &nodes_3);
        // even after pushing all nodes five times, there are only 5 nodes in the heap
        assert_eq!(5,     heap.len());
        assert!(!heap.is_empty());

        let actual   = pop_all(&mut heap);
        let expected = vec![5, 4, 3, 2, 1];
        assert_eq!(expected,  actual);
        assert_eq!(0,    heap.len());
        assert!(heap.is_empty());
    }

    fn push_all<T: SubProblemRanking<State = usize>>(heap: &mut NoDupFringe<T>, nodes: &[SubProblem<usize>]) {
        for n in nodes.iter() {
            heap.push(n.clone());
        }
    }
    fn pop_all<T: SubProblemRanking<State = usize>>(heap: &mut NoDupFringe<T>) -> Vec<usize> {
        let mut popped = vec![];
        while let Some(n) = heap.pop() {
            popped.push(*n.state)
        }
        popped
    }

    fn fnode(state: usize, value: isize, ub: isize) -> SubProblem<usize> {
        SubProblem {
            state: Arc::new(state),
            path : vec![],
            value,
            ub,
            depth: 0,
        }
    }
}