class Algorithm::Genetic::Population

population management class

Attributes

generation[R]

Public Class Methods

new(population_size, evaluator, opts = {}) { || ... } click to toggle source

constructor of population

code_length

size of code

population_size

size of population

evaluator

an Evaluator instance or Proc instance returns Evaluator instance

opts

hash of options

options:

:selection :: an array of module name including select method and params
:crossover :: an array of module name including crossover method and params
:mutation  :: an array of module name including mutate method and params
:mutation_chance :: mutation chance (float of 0 to 1)

need block for generate an initial (random) code of a gene

# File lib/algorithm/genetic/population.rb, line 36
def initialize(population_size, evaluator, opts = {})
        @evaluator = evaluator
        @members = Array.new(population_size){
                Algorithm::Genetic::Gene.new(yield, evaluator, opts)
        }
        @generation = 0

        if opts[:selection]
                @selection_params = opts[:selection].dup
                selection_module = @selection_params.shift.to_s.capitalize
                self.extend(Algorithm::Genetic::Selection.const_get(selection_module))
        end
end

Public Instance Methods

each() { |m| ... } click to toggle source

iterate each member

# File lib/algorithm/genetic/population.rb, line 60
def each
        return @members.each unless block_given?
        @members.each{|m| yield m }
end
generate() click to toggle source

increment the generation: senection, crossover and mutation

# File lib/algorithm/genetic/population.rb, line 51
def generate
        @generation += 1
        select!
        crossover
        mutate
        sort!
end

Private Instance Methods

crossover() click to toggle source
# File lib/algorithm/genetic/population.rb, line 78
def crossover
        @members += @members[0].crossover_with(@members[1])
end
mutate() click to toggle source
# File lib/algorithm/genetic/population.rb, line 82
def mutate
        @members.each do |m|
                m.mutate!
                if m.terminated?
                        sort!
                        raise Terminated.new(m)
                end
        end
end
select!() click to toggle source
# File lib/algorithm/genetic/population.rb, line 72
def select!
        @members = select(@members, *@selection_params) do |a, b|
                b.fitness <=> a.fitness
        end
end
sort!() click to toggle source
# File lib/algorithm/genetic/population.rb, line 66
def sort!
        @members.sort! do |a, b|
                b.fitness <=> a.fitness
        end
end