Module GPTreeHelper
In: lib/charlie/tree/tree.rb

some general helper functions, which are independant of the operator arrays

Methods

Public Instance methods

[Source]

    # File lib/charlie/tree/tree.rb, line 29
29:   def all_subtrees(t=@genes)
30:     if t.first==:term
31:       [t]
32:     else
33:       t[1..-1].map{|st| all_subtrees(st) }.inject{|a,b|a+b} << t
34:     end
35:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 41
41:   def all_terminals(t=@genes)
42:     if t.first==:term
43:       [t]
44:     else
45:       t[1..-1].map{|st| all_terminals(st) }.inject{|a,b|a+b}
46:     end
47:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 5
 5:   def dup_tree(t)
 6:     if t.first==:term
 7:       t.clone # avoid inf recursion here
 8:     else
 9:       t.map{|st| st.is_a?(Symbol) ? st : dup_tree(st) }
10:     end
11:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 53
53:   def eval_tree(tree,values_hash)
54:     if tree.first == :term
55:       termval = tree[1]
56:       if termval.is_a?(Symbol) # look up symbols in the hash
57:         termval = values_hash[termval]
58:         termval = termval.call if termval.is_a?(Proc) # and if hash value is a proc, evaluate it
59:       end
60:       termval
61:     else # tree.first is an operator
62:       eval_tree(tree[1],values_hash).send(tree.first, *tree[2..-1].map{|t| eval_tree(t,values_hash) } )
63:     end
64:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 37
37:   def random_subtree(t=@genes)
38:     all_subtrees(t).at_rand
39:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 49
49:   def random_terminal(t=@genes)
50:     all_terminals(t).at_rand
51:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 21
21:   def tree_depth(t)
22:     if t.first==:term
23:       0
24:     else
25:       1 + t[1..-1].map{|st| tree_depth(st) }.max
26:     end
27:   end

[Source]

    # File lib/charlie/tree/tree.rb, line 13
13:   def tree_size(t)
14:     if t.first==:term
15:       1
16:     else
17:       t[1..-1].inject(1){|sum,st| sum + tree_size(st) }
18:     end
19:   end

[Validate]