Top Level Namespace

Defined Under Namespace

Classes: GeneticObject

Instance Method Summary collapse

Instance Method Details

#bestSelection(population) ⇒ Object



132
133
134
# File 'lib/gemetics.rb', line 132

def bestSelection(population)
  return population[0..1]
end

#continue?(highestFitness, threshold, currentGen, options) ⇒ Boolean

Internal Logic

Returns:

  • (Boolean)


99
100
101
102
103
# File 'lib/gemetics.rb', line 99

def continue?(highestFitness, threshold, currentGen, options)
  return false if exceedsThreshold?(options[:greaterBetter], highestFitness, threshold)
  return false if currentGen > options[:maxGen]
  return true
end

#default_GA_optionsObject



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/gemetics.rb', line 3

def default_GA_options()
  return {
  greaterBetter: true,
  totalPopReplace: true,
  genMax: 1000,
  selectionStyle: 'tournament',
  mutationPercent: 0.05,
  elitism: 0,
  debug: false,
  }
end

#exceedsThreshold?(greaterBetter, val, threshold) ⇒ Boolean

Returns:

  • (Boolean)


105
106
107
108
109
110
111
112
113
114
115
# File 'lib/gemetics.rb', line 105

def exceedsThreshold?(greaterBetter, val, threshold)
  if(val == nil)
  return false
  end
  if(greaterBetter)
    return val>=threshold
  else
    return val<=threshold
  end
  return false
end

#hasRequiredOptions(options) ⇒ Object



148
149
150
151
152
153
154
155
156
# File 'lib/gemetics.rb', line 148

def hasRequiredOptions(options)
  return false if !options.has_key?(:greaterBetter)
  return false if !options.has_key?(:totalPopReplace)
  return false if !options.has_key?(:genMax)
  return false if !options.has_key?(:mutation_percent)
  return false if !options.has_key?(:debug)
  return false if !options.has_key?(:elitism)
  return true
end

#mateOrgs(one, two) ⇒ Object



136
137
138
# File 'lib/gemetics.rb', line 136

def mateOrgs(one, two)
  return one.mate(two)
end

#runGeneticAlgorithm(initialPopulation, eval, threshold, options) ⇒ Object



15
16
17
18
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/gemetics.rb', line 15

def runGeneticAlgorithm(initialPopulation, eval, threshold, options)
  # make sure options is assigned
  if(options == nil)
    options = default_GA_options
  end
  validOptions(options,population.size()) # Raises error if options are not correct
  currentGen = 0
  bestCanidate = initialPopulation[0]
  population = initialPopulation
  while(continue?(bestCanidate.fitness, threshold, currentGen, options)) do
      if(options[:debug])
       puts 'Best Canidate Soultion:'
        puts bestCanidate.inspect
        puts 'Current Generation:'
        puts currentGen
      end
    # evaluate the population
    population = eval.call(population)
    if(options[:greaterBetter])
      sortedPopulation = population.sort{ |x , y| y.fitness <=> x.fitness }
    else
      sortedPopulation = population.sort{ |x , y| x.fitness <=> y.fitness }
    end
    bestCanidate = population[0].clone


    if(options[:totalPopReplace] == false)
      # Do not replace every organism
      mates = selection(sortedPopulation.clone(), options[:selectionStyle])

      # mate and replace
      results = mateOrgs(mates[0], mates[1])
      replaced = []
      if(options[:elitism] > 0)
        population = sortedPopulation
        for i in 0...options[:elitism]
          replaced.append(0)
        end
      end
      for i in 0...results.size()
        results[i].mutate() if Random.new.rand() < options[:mutationPercent]
        temp = Random.new.rand(population.size())
        while(!replaced.includes?(temp)) do
          temp = Random.new.rand(population.size())
        end
        replaced.append(temp)
        population[replaced[-1]] = results[i]
      end
    else
      # Repalce every single organism
      needed = population.size()
      have = 0
      newPopulation = Array.new(population.size(), GeneticObject.new)
      if(option[:elitism] > 0)
        if(options[:greaterBetter])
          sortedPopulation = population.sort{ |x , y| y.fitness <=> x.fitness }
        else
          sortedPopulation = population.sort{ |x , y| x.fitness <=> y.fitness }
        end
        for i in 0...options[:elitism]
          newPopulation[i] = sortedPopulation[i]
        end
      end
      while have < needed do
        mates = selection(sortedPopulation.clone(), options[:selectionStyle])

        # mate and put them into new pop
        results = mateOrgs(mates[0], mates[1])
        for i in 0...results.size()
          results[i].mutate() if Random.new.rand() < options[:mutationPercent]
          newPopulation[have+i] = result[i] if (have+i) < needed
        end
        have += results.size()
      end
      population = newPopulation
    end
    # Increment generations
    currentGen += 1
  end
  return bestCanidate
end

#selection(population, type) ⇒ Object



117
118
119
120
121
122
123
124
125
# File 'lib/gemetics.rb', line 117

def selection(population, type)
  # select mates
  if(type == 'tournament')
    return tournamentSelection(population)
  elsif(type == 'best')
    return bestSelection(population)
  end
  raise 'Problem with selection type'
end

#tournamentSelection(population) ⇒ Object



127
128
129
130
# File 'lib/gemetics.rb', line 127

def tournamentSelection(population)
  population = population.shuffle
  return population[0..10].sort{ |x , y| x.fitness <=> y.fitness }[0..1]
end

#validOptions(options, populationSize) ⇒ Object

Validation



142
143
144
145
146
# File 'lib/gemetics.rb', line 142

def validOptions(options, populationSize)
  raise 'Required Option Missing' if !hasRequiredOptions(options)
  raise 'Options Not Within Limits' if !withinLimits(options, populationSize)
  return true
end

#withinLimits(options, populationSize) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/gemetics.rb', line 158

def withinLimits(options, populationSize)
  possibleGreaterBetter = [true, false]
  possibleTotalPopReplace = [true, false]
  possibleDebug = [true, false]
  possibleSelectionStyle = ['tournament', 'best']
  return false if !(possibleGreaterBetter.include?(options[:greaterBetter]))
  return false if !(possibleTotalPopReplace.include?(options[:totalPopReplace]))
  return false if !(options[:genMax]>0)
  return false if !(possibleSelectionStyle.include?(options[:selectionStyle]))
  return false if !(options[:mutationPercent]>0.0)
  return false if !(possibleDebug.include?(options[:debug]))
  return false if !(options[:elitism]>=0 && options[:elitism]<populationSize)
  return true
end