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
//! Contains a data structure for nice tree decompositions and an algorithm to generate them.

use arboretum_td::tree_decomposition::TreeDecomposition;
use fxhash::FxHashSet;

/// Represents one of the four possible node types of a nice tree decomposition.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum NiceTdNodeType {
    /// Join node
    Join,
    /// Introduce node (with introduced vertex)
    Introduce(usize),
    /// Forget node (with forgotten vertex)
    Forget(usize),
    /// Leaf
    Leaf,
}

/// Represents a nice tree decomposition.
///
/// In a nice tree decomposition, each node is either a Leaf, Join, Forget or Introduce node.
pub struct NiceTreeDecomposition {
    /// Is guaranteed to have the properties of a nice tree decomposition.
    pub td: TreeDecomposition,
    /// Maps nodes to their `NiceTdNodeType`.
    pub mapping: Vec<NiceTdNodeType>,
}

impl NiceTreeDecomposition {
    /// Create a nice tree decomposition.
    pub fn new(mut td: TreeDecomposition) -> Self {
        let root = td.root.unwrap_or(0);
        td.root = Some(root);

        Self::nicify_multi_child_nodes(root, &td.bags()[root].neighbors.clone(), &mut td);
        Self::nicify_double_child_nodes(root, &td.bags()[root].neighbors.clone(), &mut td);
        Self::nicify_single_child_nodes(root, &td.bags()[root].neighbors.clone(), &mut td);
        Self::nicify_leaf_nodes(root, &td.bags()[root].neighbors.clone(), &mut td);

        let mut mapping: Vec<Option<NiceTdNodeType>> = vec![None; td.bags().len()];

        assert!(Self::is_nice_td(
            &td,
            root,
            &td.bags()[root].neighbors.clone(),
            &mut mapping
        ));
        assert!(mapping.iter().all(|node_type| { node_type.is_some() }));

        Self {
            td: td.to_owned(),
            mapping: mapping.iter().map(|node_type| node_type.unwrap()).collect(),
        }
    }

    fn nicify_multi_child_nodes(
        id: usize,
        children: &FxHashSet<usize>,
        td: &mut TreeDecomposition,
    ) {
        if children.len() <= 2 {
            for child_id in children {
                Self::nicify_multi_child_nodes(*child_id, &get_children(td, *child_id, id), td);
            }

            return;
        }

        let vertex_set: FxHashSet<usize> = td.bags()[id].vertex_set.clone();
        let left_child_id = td.add_bag(vertex_set);
        td.add_edge(id, left_child_id);
        let mut it = children.iter();
        let right_child_id = *it.next().unwrap();

        for child_id in it {
            Self::remove_edge(td, id, *child_id);
            td.add_edge(left_child_id, *child_id);
        }

        Self::nicify_multi_child_nodes(left_child_id, &get_children(td, left_child_id, id), td);

        Self::nicify_multi_child_nodes(right_child_id, &get_children(td, right_child_id, id), td);
    }

    fn nicify_double_child_nodes(
        id: usize,
        children: &FxHashSet<usize>,
        td: &mut TreeDecomposition,
    ) {
        if children.len() != 2 {
            for child_id in children {
                Self::nicify_double_child_nodes(*child_id, &get_children(td, *child_id, id), td);
            }

            return;
        }

        let mut it = children.iter();
        let left_child_id = *it.next().unwrap();
        let right_child_id = *it.next().unwrap();
        let vertex_set: FxHashSet<usize> = td.bags()[id].vertex_set.clone();
        let new_left_child_id = td.add_bag(vertex_set.clone());
        let new_right_child_id = td.add_bag(vertex_set);

        Self::remove_edge(td, id, left_child_id);
        Self::remove_edge(td, id, right_child_id);
        td.add_edge(id, new_left_child_id);
        td.add_edge(id, new_right_child_id);
        td.add_edge(new_left_child_id, left_child_id);
        td.add_edge(new_right_child_id, right_child_id);

        Self::nicify_double_child_nodes(
            left_child_id,
            &get_children(td, left_child_id, new_left_child_id),
            td,
        );

        Self::nicify_double_child_nodes(
            right_child_id,
            &get_children(td, right_child_id, new_right_child_id),
            td,
        );
    }

    fn nicify_single_child_nodes(
        id: usize,
        children: &FxHashSet<usize>,
        td: &mut TreeDecomposition,
    ) {
        if children.len() != 1 {
            for child_id in children {
                Self::nicify_single_child_nodes(*child_id, &get_children(td, *child_id, id), td);
            }

            return;
        }

        let mut vertex_set: FxHashSet<usize> = td.bags()[id].vertex_set.clone();
        let child_id = *children.iter().next().unwrap();
        let child_vertex_set: FxHashSet<usize> = td.bags()[child_id].vertex_set.clone();

        if vertex_set.eq(&child_vertex_set.clone()) {
            Self::remove_edge(td, id, child_id);

            for grandchild_id in get_children(td, child_id, id) {
                td.add_edge(id, grandchild_id);
                Self::remove_edge(td, child_id, grandchild_id);
                Self::nicify_single_child_nodes(
                    grandchild_id,
                    &get_children(td, grandchild_id, id),
                    td,
                );
            }

            Self::remove_bag(td, child_id);

            return;
        }

        let mut parent_id = id;

        for v in vertex_set.clone().difference(&child_vertex_set) {
            vertex_set.remove(v);

            if vertex_set.eq(&child_vertex_set) {
                break;
            }

            let new_child_id = td.add_bag(vertex_set.clone());
            Self::remove_edge(td, parent_id, child_id);
            td.add_edge(parent_id, new_child_id);
            td.add_edge(new_child_id, child_id);
            parent_id = new_child_id;
        }

        for v in child_vertex_set.difference(&vertex_set.clone()) {
            vertex_set.insert(*v);

            if vertex_set.eq(&child_vertex_set) {
                break;
            }

            let new_child_id = td.add_bag(vertex_set.clone());
            Self::remove_edge(td, parent_id, child_id);
            td.add_edge(parent_id, new_child_id);
            td.add_edge(new_child_id, child_id);
            parent_id = new_child_id;
        }

        Self::nicify_single_child_nodes(child_id, &get_children(td, child_id, parent_id), td);
    }

    fn nicify_leaf_nodes(id: usize, children: &FxHashSet<usize>, td: &mut TreeDecomposition) {
        if !children.is_empty() {
            for child_id in children {
                Self::nicify_leaf_nodes(*child_id, &get_children(td, *child_id, id), td);
            }

            return;
        }

        let bag = &td.bags()[id];
        let mut vertex_set = bag.vertex_set.clone();
        let mut parent_id = id;

        while vertex_set.len() > 1 {
            let v = *vertex_set.iter().next().unwrap();
            vertex_set.remove(&v);
            let new_child_id = td.add_bag(vertex_set.clone());
            td.add_edge(parent_id, new_child_id);
            parent_id = new_child_id;
        }
    }

    fn is_nice_td(
        td: &TreeDecomposition,
        id: usize,
        children: &FxHashSet<usize>,
        mapping: &mut Vec<Option<NiceTdNodeType>>,
    ) -> bool {
        match Self::get_nice_td_node_type(td, id, children) {
            Some(node_type) => {
                mapping[id] = Some(node_type);
                children.iter().all(|child_id| {
                    Self::is_nice_td(td, *child_id, &get_children(td, *child_id, id), mapping)
                })
            }
            None => false,
        }
    }

    fn get_nice_td_node_type(
        td: &TreeDecomposition,
        id: usize,
        children: &FxHashSet<usize>,
    ) -> Option<NiceTdNodeType> {
        if Self::is_nice_td_join(td, id, children) {
            return Some(NiceTdNodeType::Join);
        } else if let Some(v) = Self::is_nice_td_intro(td, id, children) {
            return Some(NiceTdNodeType::Introduce(v));
        } else if let Some(v) = Self::is_nice_td_forget(td, id, children) {
            return Some(NiceTdNodeType::Forget(v));
        } else if Self::is_nice_td_leaf(td, id, children) {
            return Some(NiceTdNodeType::Leaf);
        }

        None
    }

    fn is_nice_td_join(td: &TreeDecomposition, id: usize, children: &FxHashSet<usize>) -> bool {
        let mut it = children.iter();
        let left = it.next();
        let right = it.next();
        let none = it.next();

        match (left, right, none) {
            (Some(left), Some(right), None) => {
                let vertex_set: &FxHashSet<usize> = &td.bags()[id].vertex_set;
                let left_vertex_set: &FxHashSet<usize> = &td.bags()[*left].vertex_set;
                let right_vertex_set: &FxHashSet<usize> = &td.bags()[*right].vertex_set;
                vertex_set == left_vertex_set && vertex_set == right_vertex_set
            }
            _ => false,
        }
    }

    fn is_nice_td_intro(
        td: &TreeDecomposition,
        id: usize,
        children: &FxHashSet<usize>,
    ) -> Option<usize> {
        let mut it = children.iter();
        let child = it.next();
        let none = it.next();

        match (child, none) {
            (Some(child), None) => {
                let vertex_set: &FxHashSet<usize> = &td.bags()[id].vertex_set;
                let child_vertex_set: &FxHashSet<usize> = &td.bags()[*child].vertex_set;

                if !vertex_set.is_superset(child_vertex_set)
                    || vertex_set.len() != child_vertex_set.len() + 1
                {
                    return None;
                }

                Some(*vertex_set.difference(child_vertex_set).next().unwrap())
            }
            _ => None,
        }
    }

    fn is_nice_td_forget(
        td: &TreeDecomposition,
        id: usize,
        children: &FxHashSet<usize>,
    ) -> Option<usize> {
        let mut it = children.iter();
        let child = it.next();

        if it.next().is_some() {
            return None;
        }

        match child {
            Some(child) => {
                let vertex_set: &FxHashSet<usize> = &td.bags()[id].vertex_set;
                let child_vertex_set: &FxHashSet<usize> = &td.bags()[*child].vertex_set;

                if !vertex_set.is_subset(child_vertex_set)
                    || vertex_set.len() + 1 != child_vertex_set.len()
                {
                    return None;
                }

                Some(*child_vertex_set.difference(vertex_set).next().unwrap())
            }
            None => None,
        }
    }

    fn is_nice_td_leaf(td: &TreeDecomposition, id: usize, children: &FxHashSet<usize>) -> bool {
        let vertex_set = &td.bags()[id].vertex_set;

        children.is_empty() && vertex_set.len() == 1
    }

    fn remove_edge(td: &mut TreeDecomposition, b1: usize, b2: usize) {
        assert!(b1 < td.bags.len());
        assert!(b2 < td.bags.len());
        assert_ne!(b1, b2);
        td.bags[b1].neighbors.remove(&b2);
        td.bags[b2].neighbors.remove(&b1);
    }

    // taken from https://github.com/jmeintrup/arboretum/blob/master/src/tree_decomposition.rs
    fn remove_bag(td: &mut TreeDecomposition, id: usize) {
        assert!(td.bags[id].neighbors.is_empty());
        if id == td.bags.len() - 1 {
            td.bags.pop();
        } else {
            let old_last = td.bags.swap_remove(id);
            assert!(old_last.neighbors.is_empty());
            td.bags[id].id = id;
            let old_last = td.bags.len();

            for neighbor in td.bags[id].neighbors.clone() {
                assert!(td.bags[neighbor].neighbors.remove(&old_last));
                assert!(td.bags[neighbor].neighbors.insert(id));
            }
        }
    }
}

/// Return the children of a bag (children = neighbors \ {parent_id}).
pub fn get_children(td: &TreeDecomposition, id: usize, parent_id: usize) -> FxHashSet<usize> {
    let mut children = td.bags()[id].neighbors.clone();
    children.remove(&parent_id);

    children
}

#[cfg(test)]
mod tests {
    use super::NiceTreeDecomposition;
    use crate::{
        algorithm::nice_tree_decomposition::get_children,
        generation::erdos_renyi::generate_hash_map_graph,
    };
    use arboretum_td::{solver::Solver, tree_decomposition::TreeDecomposition};
    use fxhash::FxHashSet;
    use rand::{rngs::StdRng, Rng, SeedableRng};

    #[test]
    fn single_bag_with_1_vertex() {
        let mut td = TreeDecomposition::default();
        let mut vertex_set = FxHashSet::default();
        vertex_set.insert(1);
        td.add_bag(vertex_set);

        let nice_td = NiceTreeDecomposition::new(td.clone());
        assert!(nice_td.td.bags().len() == td.bags().len());
        assert!(nice_td.td.bags()[0].vertex_set == td.bags()[0].vertex_set);
    }

    #[test]
    fn single_bag_with_multiple_vertices() {
        let mut td = TreeDecomposition::default();
        let mut vertex_set = FxHashSet::default();
        vertex_set.insert(1);
        vertex_set.insert(2);
        vertex_set.insert(3);
        let id = td.add_bag(vertex_set);

        let nice_td = NiceTreeDecomposition::new(td.clone());
        let bag = &nice_td.td.bags()[id];
        let child_id = *bag.neighbors.iter().next().unwrap();
        let grandchild_id = get_child_bag_id(&nice_td.td, child_id, id).unwrap();

        assert!(nice_td.td.bags().len() == 3);
        assert!(bag.vertex_set.len() == 3);
        assert!(
            NiceTreeDecomposition::is_nice_td_intro(&nice_td.td, id, &bag.neighbors.clone())
                .is_some()
        );
        assert!(NiceTreeDecomposition::is_nice_td_intro(
            &nice_td.td,
            child_id,
            &get_children(&nice_td.td, child_id, id)
        )
        .is_some());
        assert!(NiceTreeDecomposition::is_nice_td_leaf(
            &nice_td.td,
            grandchild_id,
            &get_children(&nice_td.td, grandchild_id, child_id)
        ));
    }

    #[test]
    fn two_bags_with_multiple_vertices() {
        let mut td = TreeDecomposition::default();
        let mut vertex_set_1 = FxHashSet::default();
        vertex_set_1.insert(1);
        vertex_set_1.insert(2);
        let mut vertex_set_2 = FxHashSet::default();
        vertex_set_2.insert(2);
        vertex_set_2.insert(3);

        let id_1 = td.add_bag(vertex_set_1);
        let id_2 = td.add_bag(vertex_set_2);
        td.add_edge(id_1, id_2);

        let nice_td = NiceTreeDecomposition::new(td.clone());
        let bag = &nice_td.td.bags()[id_1];
        let child_id = *bag.neighbors.iter().next().unwrap();
        let grandchild_id = get_child_bag_id(&nice_td.td, child_id, id_1).unwrap();
        let grandgrandchild_id = get_child_bag_id(&nice_td.td, grandchild_id, child_id).unwrap();

        assert!(nice_td.td.bags().len() == 4);
        assert_eq!(
            NiceTreeDecomposition::is_nice_td_intro(&nice_td.td, id_1, &bag.neighbors.clone()),
            Some(1)
        );
        assert_eq!(
            NiceTreeDecomposition::is_nice_td_forget(
                &nice_td.td,
                child_id,
                &get_children(&nice_td.td, child_id, id_1)
            ),
            Some(3)
        );
        assert!(NiceTreeDecomposition::is_nice_td_intro(
            &nice_td.td,
            grandchild_id,
            &get_children(&nice_td.td, grandchild_id, child_id)
        )
        .is_some());
        assert!(NiceTreeDecomposition::is_nice_td_leaf(
            &nice_td.td,
            grandgrandchild_id,
            &get_children(&nice_td.td, grandgrandchild_id, grandchild_id)
        ));
    }

    #[test]
    fn random() {
        let mut rng = StdRng::seed_from_u64(1);

        for i in 0..100 {
            let graph = generate_hash_map_graph(
                rng.gen_range(1..30),
                rng.gen_range(0.05..0.1),
                Some(i as u64),
            );
            let td = Solver::default().solve(&graph);
            let nice_td = NiceTreeDecomposition::new(td);
            assert!(nice_td.td.verify(&graph).is_ok());
        }
    }

    fn get_child_bag_id(td: &TreeDecomposition, id: usize, parent_id: usize) -> Option<usize> {
        get_children(td, id, parent_id).iter().copied().next()
    }
}