Class: Algorithm::Genetic::Population

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/algorithm/genetic/population.rb

Overview

population management class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(population_size, evaluator, opts = {}) ⇒ Population

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



36
37
38
39
40
41
42
43
44
45
46
47
48
# 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

Instance Attribute Details

#generationObject (readonly)

Returns the value of attribute generation.



20
21
22
# File 'lib/algorithm/genetic/population.rb', line 20

def generation
  @generation
end

Instance Method Details

#eachObject

iterate each member



60
61
62
63
# File 'lib/algorithm/genetic/population.rb', line 60

def each
  return @members.each unless block_given?
  @members.each{|m| yield m }
end

#generateObject

increment the generation: senection, crossover and mutation



51
52
53
54
55
56
57
# File 'lib/algorithm/genetic/population.rb', line 51

def generate
  @generation += 1
  select!
  crossover
  mutate
  sort!
end