Debian Codegraph @

mlspp/include/mls/tree_math.h

raw symbols SCIP
1 #pragma once
2
3 #include <cstdint>
4 #include <tls/tls_syntax.h>
5 #include <vector>
6
7 // The below functions provide the index calculus for the tree
8 // structures used in MLS. They are premised on a "flat"
9 // representation of a balanced binary tree. Leaf nodes are
10 // even-numbered nodes, with the n-th leaf at 2*n. Intermediate
11 // nodes are held in odd-numbered nodes. For example, a 11-element
12 // tree has the following structure:
13 //
14 // X
15 // X
16 // X X X
17 // X X X X X
18 // X X X X X X X X X X X
19 // 0 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14
20 //
21 // This allows us to compute relationships between tree nodes simply
22 // by manipulating indices, rather than having to maintain
23 // complicated structures in memory, even for partial trees. (The
24 // storage for a tree can just be a map[int]Node dictionary or an
25 // array.) The basic rule is that the high-order bits of parent and
26 // child nodes have the following relation:
27 //
28 // 01x = <00x, 10x>
29
30 namespace mlspp {
31
32 // Index types go in the overall namespace
33 // XXX([email protected]): Seems like this stuff can probably get
34 // simplified down a fair bit.
35 struct UInt32
36 {
37 uint32_t val;
38
39 UInt32()
40 : val(0)
41 {
42 }
43
44 explicit UInt32(uint32_t val_in)
45 : val(val_in)
46 {
47 }
48
49 TLS_SERIALIZABLE(val)
50 };
51
52 struct NodeCount;
53
54 struct LeafCount : public UInt32
55 {
56 using UInt32::UInt32;
57 explicit LeafCount(const NodeCount w);
58
59 static LeafCount full(const LeafCount n);
60 };
61
62 struct NodeCount : public UInt32
63 {
64 using UInt32::UInt32;
65 explicit NodeCount(const LeafCount n);
66 };
67
68 struct NodeIndex;
69
70 struct LeafIndex : public UInt32
71 {
72 using UInt32::UInt32;
73 explicit LeafIndex(const NodeIndex x);
74 bool operator<(const LeafIndex other) const { return val < other.val; }
75 bool operator<(const LeafCount other) const { return val < other.val; }
76
77 NodeIndex ancestor(LeafIndex other) const;
78 };
79
80 struct NodeIndex : public UInt32
81 {
82 using UInt32::UInt32;
83 explicit NodeIndex(const LeafIndex x);
84 bool operator<(const NodeIndex other) const { return val < other.val; }
85 bool operator<(const NodeCount other) const { return val < other.val; }
86
87 static NodeIndex root(LeafCount n);
88
89 bool is_leaf() const;
90 bool is_below(NodeIndex other) const;
91
92 NodeIndex left() const;
93 NodeIndex right() const;
94 NodeIndex parent() const;
95 NodeIndex sibling() const;
96
97 // Returns the sibling of this node "relative to this ancestor" -- the child
98 // of `ancestor` that is not in the direct path of this node.
99 NodeIndex sibling(NodeIndex ancestor) const;
100
101 std::vector<NodeIndex> dirpath(LeafCount n);
102 std::vector<NodeIndex> copath(LeafCount n);
103
104 uint32_t level() const;
105 };
106
107 } // namespace mlspp