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
extern crate rand;
extern crate simple_matrix;
use std::fmt;
use std::ptr;
use std::mem;
use std::marker::Sync;
use std::sync::{Arc, RwLock};
use rand::seq::SliceRandom;
use rand::rngs::ThreadRng;
use rand::Rng;
use simple_matrix::Matrix;
use super::{
iterators,
node::Node,
network::NeuralNetwork,
evenv::TreeEnvionment
};
use crate::engine::genome::{Genome};
#[derive(PartialEq)]
pub struct Evtree {
root: *mut Node,
size: i32,
}
impl Evtree {
pub fn new() -> Self {
Evtree {
root: ptr::null_mut(),
size: 0,
}
}
pub fn iter_mut(&mut self) -> iterators::IterMut {
let mut stack = Vec::new();
unsafe { stack.push(&mut *self.root); }
iterators::IterMut { stack }
}
pub fn level_order_iter(&self) -> iterators::LevelOrderIterator {
let mut stack = Vec::new();
unsafe { stack.push(&*self.root); }
iterators::LevelOrderIterator { stack }
}
pub fn in_order_iter(&self) -> iterators::InOrderIterator {
let mut stack = Vec::new();
unsafe { stack.push(&*self.root); }
iterators::InOrderIterator { stack }
}
pub fn len(&self) -> &i32 {
&self.size
}
#[inline]
pub fn height(&self) -> i32 {
unsafe { (&*self.root).height() }
}
#[inline]
pub fn get(&mut self, index: usize) -> &mut Node {
let mut temp: Option<&mut Node> = None;
for (i, node) in self.iter_mut().enumerate() {
if i == index {
temp = Some(node);
break;
}
}
temp.unwrap_or_else(|| panic!("Index not found in tree."))
}
#[inline]
pub fn index_of(&self, node: &Node) -> usize {
let mut temp: Option<usize> = None;
for (index, curr) in self.in_order_iter().enumerate() {
if curr == node {
temp = Some(index);
break;
}
}
temp.unwrap_or_else(|| panic!("Node index not found."))
}
pub fn insert_random(&mut self, input_size: i32, outputs: &Vec<i32>) {
if self.root == ptr::null_mut() {
self.root = Node::new(input_size, outputs).as_mut_ptr();
} else {
unsafe {
(*self.root).insert_random(input_size, outputs);
}
}
self.size += 1;
}
pub fn display(&self) {
if self.root == ptr::null_mut() {
panic!("The root node is ptr::null_mut()");
}
unsafe { (*self.root).display(0); }
}
pub fn balance(&mut self) {
let node_bag = self.in_order_iter()
.map(|x: &Node| x.copy().as_mut_ptr())
.collect::<Vec<_>>();
self.root = self.make_tree(&node_bag[..], None)
.unwrap_or_else(|| panic!("Tree failed to balance"));
}
#[inline]
fn make_tree(&self, bag: &[*mut Node], parent: Option<&*mut Node>) -> Option<*mut Node> {
if bag.len() == 0 {
return Some(ptr::null_mut());
}
let midpoint = bag.len() / 2;
let curr_node = bag[midpoint];
unsafe {
(*curr_node).parent = if let Some(node) = parent { *node } else { ptr::null_mut() };
(*curr_node).left_child = self.make_tree(&bag[..midpoint], Some(&curr_node))?;
(*curr_node).right_child = self.make_tree(&bag[midpoint + 1..], Some(&curr_node))?;
}
Some(curr_node)
}
#[inline]
pub fn get_biased_level<'a>(&'a self) -> Vec<&'a Node> {
let mut r = rand::thread_rng();
let index = r.gen_range(0, self.len()) as usize;
let levels = self.level_order_iter()
.map(|x: &Node| self.height() - x.height())
.collect::<Vec<_>>();
self.in_order_iter()
.filter(|x| x.depth() == levels[index])
.collect::<Vec<_>>()
}
pub fn get_biased_random_node<'a>(&'a self) -> &'a Node {
let mut nodes = self.get_biased_level();
let index = rand::thread_rng().gen_range(0, nodes.len());
nodes.remove(index)
}
fn replace(&mut self, swap_index: usize, other_node: *mut Node) {
let swap_node = self.get(swap_index);
unsafe {
if !swap_node.has_parent() {
(*other_node).parent = ptr::null_mut();
self.root = other_node;
} else {
let parent = &*(swap_node).parent;
if parent.check_left_child(swap_node) {
(*other_node).parent = swap_node.parent;
(*swap_node.parent).left_child = other_node;
} else if parent.check_right_child(swap_node) {
(*other_node).parent = swap_node.parent;
(*swap_node.parent).right_child = other_node;
}
}
self.size = (*self.root).size();
}
}
pub fn gut_random_node(&mut self, r: &mut ThreadRng) {
let index = r.gen_range(0, self.len()) as usize;
let temp_node = self.get(index);
temp_node.neural_network = NeuralNetwork::new(temp_node.input_size);
}
#[inline]
pub fn shuffle_tree(&mut self, r: &mut ThreadRng) {
let mut node_list = self.in_order_iter()
.map(|x: &Node| x.copy().as_mut_ptr())
.collect::<Vec<_>>();
node_list.shuffle(r);
self.root = self.make_tree(&node_list[..], None)
.unwrap_or_else(|| panic!("Make tree failed"));
}
#[inline]
pub fn edit_random_node_networks(&mut self, weight_mutate: f32, weight_transform: f32, layer_mutate: f32) {
for node in self.iter_mut() {
node.neural_network.edit_weights(weight_mutate, weight_transform, layer_mutate);
}
}
#[inline]
pub fn asymmetry(&self) -> f32 {
let mut total: f32 = 0.0;
for node in self.in_order_iter() {
total += node.height() as f32 * node.neural_network.weight_sum();
}
total.sin()
}
pub fn propagate(&self, inputs: Matrix<f32>) -> u8 {
unsafe {
let mut curr_node = self.root;
loop {
let node_output = (*curr_node).neural_network.feed_forward(inputs.clone());
let (mut max_index, mut temp_value) = (0, None);
for i in 0..node_output.len() {
if node_output[i] > node_output[max_index] || temp_value.is_none() {
max_index = i;
temp_value = Some(node_output[i]);
}
}
if (&*curr_node).is_leaf() {
return (&*curr_node).output;
} else if max_index == 0 && (&*curr_node).has_left_child() {
curr_node = (&*curr_node).left_child;
} else if max_index == 0 && !(&*curr_node).has_left_child() {
curr_node = (&*curr_node).right_child;
} else if max_index == 1 && (&*curr_node).has_right_child() {
curr_node = (&*curr_node).right_child;
} else if max_index == 1 && !(&*curr_node).has_right_child() {
curr_node = (&*curr_node).left_child;
}
}
}
}
}
impl fmt::Debug for Evtree {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
unsafe {
let address: u64 = mem::transmute(self);
let root: u64 = if self.root != ptr::null_mut() { mem::transmute(&*self.root) } else { 0x64 };
write!(f, "Tree=[{}, {}, {}]", address, root, self.size)
}
}
}
impl Clone for Evtree {
#[inline]
fn clone(&self) -> Evtree {
Evtree {
root: unsafe { (&*self.root).deepcopy() },
size: self.size,
}
}
}
impl Drop for Evtree {
fn drop(&mut self) {
unsafe {
let mut stack = Vec::with_capacity(*self.len() as usize);
stack.push(self.root);
while stack.len() > 0 {
let curr_node = stack.pop().unwrap();
if (&*curr_node).has_left_child() {
stack.push((&*curr_node).left_child);
}
if (&*curr_node).has_right_child() {
stack.push((&*curr_node).right_child);
}
drop(Box::from_raw(curr_node));
}
}
}
}
unsafe impl Send for Evtree {}
unsafe impl Sync for Evtree {}
impl Default for Evtree {
fn default() -> Evtree {
Evtree {
root: ptr::null_mut(),
size: 0
}
}
}
impl Genome<Evtree, TreeEnvionment> for Evtree {
#[inline]
fn crossover(one: &Evtree, two: &Evtree, settings: &Arc<RwLock<TreeEnvionment>>, crossover_rate: f32) -> Option<Evtree> {
let set = &*(*settings).read().unwrap();
let mut result = one.clone();
let mut r = rand::thread_rng();
let mut node_one = one.get_biased_random_node();
let mut node_two = two.get_biased_random_node();
while node_one.depth() + node_two.height() > set.max_height? {
node_one = one.get_biased_random_node();
node_two = two.get_biased_random_node();
}
if r.gen::<f32>() < crossover_rate {
let node_index = one.index_of(&node_one);
result.replace(node_index, node_two.deepcopy());
} else {
if r.gen::<f32>() < set.get_network_mutation_rate() {
result.edit_random_node_networks(set.weight_mutate_rate?, set.weight_transform_rate?, set.layer_mutate_rate?);
}
if r.gen::<f32>() < set.node_add_rate? {
result.insert_random(set.input_size?, set.get_outputs());
}
if r.gen::<f32>() < set.shuffle_rate? {
result.shuffle_tree(&mut r);
}
if r.gen::<f32>() < set.gut_rate? {
result.gut_random_node(&mut r);
}
result.size = unsafe { (&*result.root).size() };
}
Some(result)
}
fn base(settings: &mut TreeEnvionment) -> Evtree {
let mut result = Evtree::new();
let nodes = (0..(2 * settings.get_max_height()) - 1)
.map(|_| Node::new(settings.get_input_size(), settings.get_outputs()).as_mut_ptr())
.collect::<Vec<_>>();
result.size = nodes.len() as i32;
result.root = result.make_tree(&nodes[..], None)
.unwrap_or_else(|| panic!("failed to make default tree."));
result
}
fn distance(one: &Evtree, two: &Evtree, _settings: &Arc<RwLock<TreeEnvionment>>) -> f32 {
(one.asymmetry() - two.asymmetry()).abs()
}
}