Class: Jinni::Genepool

Inherits:
Array
  • Object
show all
Defined in:
lib/jinni/genepool.rb

Instance Method Summary collapse

Instance Method Details

#average(quality = :fitness) ⇒ Object

this method returns the mean of one quality through a collection of objects. It’s very useful for watching your generations increase in fitness.



50
51
52
# File 'lib/jinni/genepool.rb', line 50

def average(quality = :fitness)
  self.map {|f| f.send(quality)}.inject{ |sum, n| sum + n }.to_f / self.length
end

#generate(n, mutationRate = 0.01, quality = :fitness) ⇒ Object

use this method to create a new generation of ‘n` creatures based on a genepool. it uses weighted roulette wheel selection to simulate the effects of genetic fitness, then crosses the selected objects together.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/jinni/genepool.rb', line 32

def generate(n, mutationRate = 0.01, quality = :fitness)
  scratch = self.clone

  pool = scratch.roulette(n * 2, quality)

  generation = Jinni::Genepool.new

  pool.each_slice(2) do |pair|
    child = pair[0] << pair[1]
    (child = child.mutate) if mutationRate > 0
    generation << child
  end

  return generation
end

#roulette(n, quality = :fitness) ⇒ Object

this utility method uses weighted roulette wheel selection to choose ‘n` objects from your gene pool influenced by fitness. It does not cross them.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/jinni/genepool.rb', line 6

def roulette(n, quality = :fitness)
  scratch = self.clone

  probabilities = scratch.map { |creature| creature.send(quality) }
  selected = []

  n.times do
    r, inc = rand * probabilities.max, 0 # pick a random number and select the  individual
                     # corresponding to that roulette-wheel area
    scratch.each_index do |i|
      if r < (inc += probabilities[i])
        selected << scratch[i]
        # make selection not pick sample twice
        # scratch.delete_at i
        # probabilities.delete_at i
        break
      end
    end
  end
  return selected
end