| Class | Genotype |
| In: |
lib/charlie/genotype.rb
|
| Parent: | Object |
Base class. Inherit this if you‘re starting from scratch
| fitness_cache | [RW] | Used by Genotype.cache_fitness. This accessor can be used to clear the cache. Also could be used by niche selection, etc. as a place to change the effective fitness w/o changing the actual selection algorithms. |
| genes | [RW] |
Adds caching to the fitness function. Only call AFTER defining your fitness function. Never clears the cache. This should work most of the time because crossovers/from_genes create new instances.
# File lib/charlie/genotype.rb, line 46
46: def cache_fitness
47: alias_method :real_fitness, :fitness
48: define_method(:fitness) {
49: @fitness_cache ||= send(:real_fitness)
50: }
51: self
52: end
Creates a new instance of your genotype class given its genes.
# File lib/charlie/genotype.rb, line 38
38: def from_genes(g)
39: r = allocate
40: r.genes = g
41: r
42: end
For each module passed: Includes the module if it has a mutate! method, and includes it in the metaclass otherwise. Used to include selection/crossover/mutation modules in one line, or just to avoid all the class<<self;include …;end
class Example < Genotype use RandomSelection, NullCrossover, NullMutator end
# File lib/charlie/genotype.rb, line 25
25: def use(*mods)
26: mods.each{|mod|
27: if mod.instance_methods(true).find { |m| m.to_s == 'mutate!'} # ruby1.8 returns strings, 1.9 symbols so include? doesn't work
28: include mod
29: else
30: metaclass.class_eval{
31: include mod
32: }
33: end
34: }
35: end
raises an exception when called
# File lib/charlie/genotype.rb, line 13
13: def fight(other)
14: raise NoMethodError, "You need to define a fight(other) function in your genotype class to use this selection strategy!"
15: end
raises an exception when called
# File lib/charlie/genotype.rb, line 9
9: def fitness
10: raise NoMethodError, "You need to define a fitness function in your genotype class!"
11: end