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
use crate::collections::{Tree, TreeNode};
use crate::node::Node;
use crate::{Arity, Factory, NodeStore, NodeType};
const NUM_CHILDREN_ANY: usize = 2;
impl<T: Clone + Default> Tree<T> {
/// Create a tree with the given depth, where each node is a random node from the node store.
/// This obeys the rules of the [NodeStore]'s [NodeType]'s arity, and will create a tree
/// that is as balanced as possible.
///
/// Note that the root node will try to be a [NodeType::Root] if it is available in the
/// [NodeStore], otherwise it will be a [NodeType::Vertex]. This allows caller's to specify what
/// the root node is if desired, otherwise it will be a random vertex node from the [NodeStore].
///
/// # The [NodeStore] must contain at least one [NodeType::Root] or one [NodeType::Vertex]
///
/// # Arguments
/// * `depth` - The depth of the tree.
/// * `nodes` - The node store to use for the tree.
///
/// # Returns
/// A tree with the given depth, where each node is a random node from the node store.
pub fn with_depth(depth: usize, nodes: impl Into<NodeStore<T>>) -> Self {
let store = nodes.into();
let mut root = if store.contains_type(NodeType::Root) {
store.new_instance(NodeType::Root)
} else {
store.new_instance(NodeType::Vertex)
};
if root.arity() == Arity::Any {
for _ in 0..NUM_CHILDREN_ANY {
root.add_child(Self::grow(depth - 1, &store));
}
} else {
for _ in 0..*root.arity() {
root.add_child(Self::grow(depth - 1, &store));
}
}
Tree::new(root)
}
/// Recursively grow a tree from the given depth, where each node is a random node from the
/// node store. If the depth is 0, then a leaf node is returned. Otherwise, a vertex node is
/// returned with children that are grown from the given depth.
/// This obeys the rules of the [NodeStore]'s [NodeType]'s arity, and will create a tree
/// that is as balanced as possible.
///
/// # Arguments
/// * `current_depth` - The current depth of the tree.
/// * `store` - The node store to use for the tree.
///
/// # Returns
/// A tree node with the given depth, where each node is a random node from the node store.
fn grow(current_depth: usize, store: &NodeStore<T>) -> TreeNode<T> {
if current_depth == 0 {
return store.new_instance(NodeType::Leaf);
}
let mut parent = store.new_instance(NodeType::Vertex);
let num_children = match parent.arity() {
Arity::Zero => 0,
Arity::Exact(n) => n,
Arity::Any => NUM_CHILDREN_ANY,
};
for _ in 0..num_children {
parent.add_child(Self::grow(current_depth - 1, store));
}
parent
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Op, TreeIterator};
#[test]
fn test_tree_builder_depth_two() {
let store = vec![
(NodeType::Vertex, vec![Op::add(), Op::sub(), Op::mul()]),
(NodeType::Leaf, vec![Op::constant(1.0), Op::constant(2.0)]),
];
let tree = Tree::with_depth(2, store);
assert!(tree.root().is_some());
assert_eq!(tree.root().unwrap().children().unwrap().len(), 2);
assert_eq!(tree.height(), 2);
assert_eq!(tree.size(), 7);
for node in tree.iter_breadth_first() {
if node.arity() == Arity::Any {
assert_eq!(node.children().map(|c| c.len()), Some(2));
} else if let Arity::Exact(n) = node.arity() {
assert_eq!(node.children().map(|c| c.len()), Some(n));
} else {
assert_eq!(node.children(), None);
}
}
}
#[test]
fn test_tree_builder_depth_three() {
// just a quality of life test to make sure the builder is working.
// The above test should be good enough, but just for peace of mind.
let store = vec![
(NodeType::Vertex, vec![Op::add(), Op::sub(), Op::mul()]),
(NodeType::Leaf, vec![Op::constant(1.0), Op::constant(2.0)]),
];
let tree = Tree::with_depth(3, store);
assert!(tree.root().is_some());
assert_eq!(tree.root().unwrap().children().unwrap().len(), 2);
assert_eq!(tree.height(), 3);
assert_eq!(tree.size(), 15);
for node in tree.iter_breadth_first() {
if node.arity() == Arity::Any {
assert_eq!(node.children().map(|c| c.len()), Some(2));
} else if let Arity::Exact(n) = node.arity() {
assert_eq!(node.children().map(|c| c.len()), Some(n));
} else {
assert_eq!(node.children(), None);
}
}
}
#[test]
fn test_vertex_with_any_arity_builds_correct_depth() {
let tree = Tree::with_depth(
2,
vec![
(
NodeType::Vertex,
vec![Op::sigmoid(), Op::relu(), Op::tanh()],
),
(NodeType::Leaf, vec![Op::constant(1.0), Op::constant(2.0)]),
],
);
assert!(tree.root().is_some());
assert_eq!(tree.root().unwrap().children().unwrap().len(), 2);
assert_eq!(tree.height(), 2);
assert_eq!(tree.size(), 7);
for node in tree.iter_breadth_first() {
if node.arity() == Arity::Any {
assert_eq!(node.children().map(|c| c.len()), Some(2));
} else if let Arity::Exact(n) = node.arity() {
assert_eq!(node.children().map(|c| c.len()), Some(n));
} else {
assert_eq!(node.children(), None);
}
}
}
}