Class Genotype
In: lib/charlie/genotype.rb
Parent: Object

Base class. Inherit this if you‘re starting from scratch

Methods

<=>   cache_fitness   clear_cache   dup   fight   fitness   from_genes   mutate   to_s   use  

Included Modules

Comparable

Attributes

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] 

Public Class methods

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.

[Source]

    # 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.

[Source]

    # 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

[Source]

    # 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

Public Instance methods

[Source]

    # File lib/charlie/genotype.rb, line 89
89:   def <=>(b)
90:     fitness <=> b.fitness
91:   end

[Source]

    # File lib/charlie/genotype.rb, line 55
55:   def clear_cache
56:     @fitness_cache = nil
57:   end

[Source]

    # File lib/charlie/genotype.rb, line 62
62:   def dup
63:     self.class.from_genes(genes.dup)
64:   end

raises an exception when called

[Source]

    # 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

[Source]

    # 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

[Source]

    # File lib/charlie/genotype.rb, line 66
66:   def mutate
67:     cp = dup
68:     cp.mutate!
69:     cp
70:   end

[Source]

    # File lib/charlie/genotype.rb, line 72
72:   def to_s
73:     @genes.to_s
74:   end

[Validate]