Module: GPTreeHelper
Overview
some general helper functions, which are independant of the operator arrays
Instance Method Summary collapse
- #all_subtrees(t = @genes) ⇒ Object
- #all_terminals(t = @genes) ⇒ Object
- #dup_tree(t) ⇒ Object
- #eval_tree(tree, values_hash) ⇒ Object
- #random_subtree(t = @genes) ⇒ Object
- #random_terminal(t = @genes) ⇒ Object
- #tree_depth(t) ⇒ Object
- #tree_size(t) ⇒ Object
Instance Method Details
#all_subtrees(t = @genes) ⇒ Object
29 30 31 32 33 34 35 |
# File 'lib/charlie/tree/tree.rb', line 29 def all_subtrees(t=@genes) if t.first==:term [t] else t[1..-1].map{|st| all_subtrees(st) }.inject{|a,b|a+b} << t end end |
#all_terminals(t = @genes) ⇒ Object
41 42 43 44 45 46 47 |
# File 'lib/charlie/tree/tree.rb', line 41 def all_terminals(t=@genes) if t.first==:term [t] else t[1..-1].map{|st| all_terminals(st) }.inject{|a,b|a+b} end end |
#dup_tree(t) ⇒ Object
5 6 7 8 9 10 11 |
# File 'lib/charlie/tree/tree.rb', line 5 def dup_tree(t) if t.first==:term t.clone # avoid inf recursion here else t.map{|st| st.is_a?(Symbol) ? st : dup_tree(st) } end end |
#eval_tree(tree, values_hash) ⇒ Object
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/charlie/tree/tree.rb', line 53 def eval_tree(tree,values_hash) if tree.first == :term termval = tree[1] if termval.is_a?(Symbol) # look up symbols in the hash termval = values_hash[termval] termval = termval.call if termval.is_a?(Proc) # and if hash value is a proc, evaluate it end termval else # tree.first is an operator eval_tree(tree[1],values_hash).send(tree.first, *tree[2..-1].map{|t| eval_tree(t,values_hash) } ) end end |
#random_subtree(t = @genes) ⇒ Object
37 38 39 |
# File 'lib/charlie/tree/tree.rb', line 37 def random_subtree(t=@genes) all_subtrees(t).at_rand end |
#random_terminal(t = @genes) ⇒ Object
49 50 51 |
# File 'lib/charlie/tree/tree.rb', line 49 def random_terminal(t=@genes) all_terminals(t).at_rand end |
#tree_depth(t) ⇒ Object
21 22 23 24 25 26 27 |
# File 'lib/charlie/tree/tree.rb', line 21 def tree_depth(t) if t.first==:term 0 else 1 + t[1..-1].map{|st| tree_depth(st) }.max end end |
#tree_size(t) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/charlie/tree/tree.rb', line 13 def tree_size(t) if t.first==:term 1 else t[1..-1].inject(1){|sum,st| sum + tree_size(st) } end end |