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
//! Implementation of dynamic variable ordering techniques

#![allow(rustdoc::private_intra_doc_links)]

use std::io::stdout;

use crossterm::{cursor, execute};
use indicatif::ProgressBar;

use crate::{
    bdd_manager::{order::order_to_layernames, DDManager, ZERO},
    bdd_node::{NodeID, VarID},
    if_some,
};

impl DDManager {
    /// Find the variable at specified level
    fn var_at_level(&self, level: u32) -> Option<VarID> {
        self.order
            .iter()
            .enumerate()
            .find(|(_, &l)| l == level)
            .map(|(v, _)| VarID(v as u32))
    }

    /// Swap layer containing specified variable first to the bottom of the BDD, then to the top,
    /// and then to the position which resulted in smallest BDD size.
    /// Optional parameter `max_increase` stops swapping in either direction once the difference
    /// between BDD size and current optimum exceeds threshold.
    #[allow(unused)]
    fn sift_single_var(&mut self, var: VarID, max_increase: Option<u32>, mut f: NodeID) -> NodeID {
        let starting_pos = self.order[var.0 as usize];

        let mut best_position = starting_pos;
        let mut best_graphsize = self.count_active(f);

        log::info!(
            "Sifting variable {:?}, starting from level {} (graph size {}).",
            var,
            starting_pos,
            best_graphsize
        );

        // Move variable to the bottom
        let terminal_node_level = self.order[ZERO.var.0 as usize];

        let mut current_level = starting_pos;

        log::info!("Moving down...");

        for level in starting_pos + 1..terminal_node_level {
            log::info!("Trying level {}", level);
            // Swap var at level-1 (our variable) with var at level
            f = self.swap(
                self.var_at_level(level - 1).unwrap(),
                self.var_at_level(level).unwrap(),
                f,
            );
            current_level += 1;

            let new_size = self.count_active(f);
            log::info!(" Size is {}", new_size);

            if new_size < best_graphsize {
                log::info!(
                    " New optimum found with order {:?}",
                    order_to_layernames(&self.order)
                );
                self.purge_retain(f);
                best_graphsize = new_size;
                best_position = level;
            } else if let Some(max) = max_increase {
                if new_size > best_graphsize + max {
                    // Do not continue moving downwards, because the graph has grown too much
                    break;
                }
            }
        }

        // Level is now bottom (terminal-1).
        log::info!("Moving up...");

        // Swap back to initial position, without calculating size
        for level in (starting_pos..current_level).rev() {
            f = self.swap(
                self.var_at_level(level).unwrap(),
                self.var_at_level(level + 1).unwrap(),
                f,
            );
            current_level -= 1;
        }

        assert_eq!(current_level, starting_pos);

        // Move variable to the top
        for level in (1..starting_pos).rev() {
            log::info!("Trying level {}", level);
            // Swap var at level+1 (our variable) with var at level
            f = self.swap(
                self.var_at_level(level).unwrap(),
                self.var_at_level(level + 1).unwrap(),
                f,
            );
            current_level -= 1;

            let new_size = self.count_active(f);
            log::info!(" Size is {}", new_size);

            if new_size < best_graphsize {
                log::info!(
                    " New optimum found with order {:?}",
                    order_to_layernames(&self.order)
                );
                self.purge_retain(f);
                best_graphsize = new_size;
                best_position = level;
            } else if let Some(max) = max_increase {
                if new_size > best_graphsize + max {
                    // Do not continue moving upwards, because the graph has grown too much
                    break;
                }
            }
        }

        // Level is now top (1). Move variable down to best location

        log::info!(
            "The best result was graph size of {} at level {}. Moving there...",
            best_graphsize,
            best_position
        );

        for level in current_level + 1..best_position + 1 {
            // Swap var at level-1 (our variable) with var at level
            f = self.swap(
                self.var_at_level(level - 1).unwrap(),
                self.var_at_level(level).unwrap(),
                f,
            );
            current_level += 1;
        }

        assert_eq!(current_level, best_position);

        log::info!("Size is now  {}", self.count_active(f));

        f
    }

    /// Perform sifting for every layer containing at least one variable.
    /// If `progressbar` is `true`, display a progress bar in the terminal
    /// which shows the number of layers already processed.
    /// See [Self::sift_single_var()] for `max_increase` parameter.
    #[must_use]
    #[allow(unused)]
    pub fn sift_all_vars(
        &mut self,
        mut f: NodeID,
        progressbar: bool,
        max_increase: Option<u32>,
    ) -> NodeID {
        let bar = if progressbar {
            Some(ProgressBar::new(self.var2nodes.len() as u64 - 1))
        } else {
            None
        };

        for v in (1..self.var2nodes.len()) {
            if_some!(bar, inc(1));

            if self.var2nodes[v].is_empty() {
                continue;
            }

            let var = VarID(v as u32);
            f = self.sift_single_var(var, max_increase, f);
            self.purge_retain(f);
        }
        if_some!(bar, finish_and_clear());

        if bar.is_some() {
            // Move cursor up to continue updating the top-level progress bar
            execute!(stdout(), cursor::MoveToPreviousLine(1));
        }
        f
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use num_bigint::BigUint;

    use crate::{
        bdd_manager::{order::order_to_layernames, DDManager},
        bdd_node::VarID,
        dimacs,
    };

    #[test]
    fn sift_sandwich_single() {
        let _ = env_logger::builder().is_test(true).try_init();

        let expected = BigUint::parse_bytes(b"2808", 10).unwrap();

        // Build BDD
        let mut instance = dimacs::parse_dimacs("examples/sandwich.dimacs");
        let (mut man, bdd) =
            DDManager::from_instance(&mut instance, None, Default::default()).unwrap();
        assert_eq!(man.sat_count(bdd), expected);

        let size_before = man.count_active(bdd);
        println!("Size before sifting: {}", size_before);
        let bdd = man.sift_single_var(VarID(2), None, bdd);
        let size_after = man.count_active(bdd);
        println!("Size after sifting: {}", size_after);
        println!("Order after sifting: {:?}", order_to_layernames(&man.order));

        assert_eq!(man.sat_count(bdd), expected);
        assert!(size_after <= size_before);
    }

    #[test]
    fn sift_sandwich_all() {
        let _ = env_logger::builder().is_test(true).try_init();

        let expected = BigUint::parse_bytes(b"2808", 10).unwrap();

        // Build BDD
        let mut instance = dimacs::parse_dimacs("examples/sandwich.dimacs");
        let (mut man, bdd) =
            DDManager::from_instance(&mut instance, None, Default::default()).unwrap();
        assert_eq!(man.sat_count(bdd), expected);

        let size_before = man.count_active(bdd);
        println!("Size before sifting: {}", size_before);
        let bdd = man.sift_all_vars(bdd, false, None);
        let size_after = man.count_active(bdd);
        println!("Size after sifting: {}", size_after);
        println!("Order after sifting: {:?}", order_to_layernames(&man.order));
        fs::write("after.dot", man.graphviz(bdd)).unwrap();

        assert_eq!(man.sat_count(bdd), expected);
        assert!(size_after <= size_before);
        // TODO: Check if function is actually the same
    }
}