Class: GeneticAlgorithms::Population

Inherits:
Object
  • Object
show all
Defined in:
lib/genetic_algorithms/population.rb

Overview

TODO: add input validation

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(chromosomes) ⇒ Population

Returns a new instance of Population.



8
9
10
11
# File 'lib/genetic_algorithms/population.rb', line 8

def initialize(chromosomes)
  @chromosomes  = chromosomes
  @logger       = Logging.logger[self.class]
end

Instance Attribute Details

#best_solutionObject (readonly)

Returns the value of attribute best_solution.



6
7
8
# File 'lib/genetic_algorithms/population.rb', line 6

def best_solution
  @best_solution
end

#chromosomesObject (readonly)

Returns the value of attribute chromosomes.



6
7
8
# File 'lib/genetic_algorithms/population.rb', line 6

def chromosomes
  @chromosomes
end

#highest_scoreObject (readonly)

Returns the value of attribute highest_score.



6
7
8
# File 'lib/genetic_algorithms/population.rb', line 6

def highest_score
  @highest_score
end

Class Method Details

.random_chromosomes(total_chromosomes, chromosome_length) ⇒ Object



13
14
15
16
17
# File 'lib/genetic_algorithms/population.rb', line 13

def self.random_chromosomes(total_chromosomes, chromosome_length)
  Array.new(total_chromosomes).map do 
    Chromosome.random(chromosome_length)
  end
end

Instance Method Details

#evolve(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/genetic_algorithms/population.rb', line 19

def evolve(&block)
  weighted_chromosomes = @chromosomes.inject(Hash.new) do |memo, chromosome|
    memo[chromosome] = block.call(chromosome)
    memo
  end

  highest_weighted = Hash[[ weighted_chromosomes.invert.sort.last ]].invert
  @best_solution = highest_weighted.keys.first
  @highest_score = highest_weighted.values.first

  roulette_wheel = RouletteWheel.new weighted_chromosomes

  offspring = (0...(@chromosomes.size)).inject(Array.new) do |offspring|
    mates = Array.new(2).map do
      roulette_wheel.spin
    end

    child_chromosome    = mates.first.crossover(mates.last)
    offspring          << child_chromosome
  end

  @logger.info "Highest Score in population: #@highest_score"
  @logger.info "Best Solution in population: #@best_solution"

  Population.new offspring
end