Class: SimpleGa::GeneticAlgorithm::Chromosome

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_ga/genetic_algorithm.rb

Overview

A Chromosome is a representation of an individual solution for a specific problem. You will have to redifine the Chromosome representation for each particular problem, along with its fitness, mutate, reproduce, and seed methods.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Chromosome

Chromosome.new



176
177
178
# File 'lib/simple_ga/genetic_algorithm.rb', line 176

def initialize(data) # Chromosome.new
  @data = data
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



173
174
175
# File 'lib/simple_ga/genetic_algorithm.rb', line 173

def data
  @data
end

#normalized_fitnessObject

Returns the value of attribute normalized_fitness.



174
175
176
# File 'lib/simple_ga/genetic_algorithm.rb', line 174

def normalized_fitness
  @normalized_fitness
end

Class Method Details

.mutate(chromosome) ⇒ Object

Mutation method is used to maintain genetic diversity from one generation of a population of chromosomes to the next. It is analogous to biological mutation.

The purpose of mutation in GAs is to allow the algorithm to avoid local minima by preventing the population of chromosomes from becoming too similar to each other, thus slowing or even stopping evolution.

Callling the mutate function will “probably” slightly change a chromosome randomly.



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/simple_ga/genetic_algorithm.rb', line 281

def self.mutate(chromosome)
  if chromosome.normalized_fitness && rand < ((1 - chromosome.normalized_fitness) * 0.4)
      courses, grades = [], []
      data = chromosome.data

      # Split the chromosome into 2.
      0.step(data.length-1, 2) do |j|
        courses << data[j]
        grades << data[j+1]
      end

      p1 = (rand * courses.length-1).ceil
      courses[p1] = rand(2)
      p2 = (rand * grades.length-1).ceil
      grades[p2] = (1 + rand(6))

      # Recombine the chromosome.
      # [0,1,2,3,4,5,6,7,8,9,10]
      0.upto(courses.length-1) do |j|
        even_index = j * 2
        odd_index =  even_index + 1
        data[even_index] = courses[j]
        data[odd_index] = grades[j]
      end

      chromosome.data = data
      @fitness = nil
  end
end

.reproduce(a, b) ⇒ Object

Chromosome a and b might be the same.

NOTE

Why is chromosome a the same as chromosome b?



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/simple_ga/genetic_algorithm.rb', line 322

def self.reproduce(a, b)
  # We know that (a.data.length == b.data.length) must be always true.
  chromosomeLength = a.data.length
  aCourses, bCourses, aGrades, bGrades = [], [], [], []    

  # Split the chromosome into 2.
  0.step(chromosomeLength-1, 2) do |index|
    next_index = index + 1
    aCourses << a.data[index]
    aGrades << a.data[next_index]
    bCourses << b.data[index]
    bGrades << b.data[next_index]
  end

  # One-point crossover
  # We know that (aCourses.length == aGrades.length) must be always true.
  # However, we want to cut and cross at different points for the 
  # corresponding course and grade array.
  # Avoid slice(0,0) or slice (11,11). It brings no changes.
  course_Xpoint = rand(aCourses.length-1) + 1 
  grade_Xpoint = rand(aGrades.length-1) + 1
  new_Courses = aCourses.slice(0, course_Xpoint) + bCourses.slice(course_Xpoint, aCourses.length)
  new_Grades = aGrades.slice(0, grade_Xpoint) + bGrades.slice(grade_Xpoint, aGrades.length)
  
  spawn = []
  # We know that (new_Courses.length == new_Grades.length) must be always true.
  0.upto(new_Courses.length-1) do |i|
    spawn << new_Courses[i]
    spawn << new_Grades[i]
  end

  return Chromosome.new(spawn)
end

.seedObject

Initializes an individual solution (chromosome) for the initial population. Usually the chromosome is generated randomly, but you can use some problem domain knowledge, to generate a (probably) better initial solution.



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/simple_ga/genetic_algorithm.rb', line 361

def self.seed
  # Current state inputs to be retrieved from the database.
  # ncourse = 11
  seed = []

  max_credits = 20
  if @@total_credits > max_credits
    1.step(@@ncourse*2, 2) do |j|
      seed << rand(2)
      seed << (1 + rand(6))
    end
  else
    1.step(@@ncourse*2, 2) do |j|
      seed << 1
      seed << (1 + rand(6))
    end
  end

  return Chromosome.new(seed)
end

.set_params(available_courses, current_gpa, acum_ch) ⇒ Object

available_courses is an array of arrays containing a list of available courses with the course information e.g. [[<course_name>, <course_ch], [<course_name>, <course_ch]]



385
386
387
388
389
390
391
392
393
394
395
# File 'lib/simple_ga/genetic_algorithm.rb', line 385

def self.set_params(available_courses, current_gpa, acum_ch)
  @@credits = []
  @@old_gpa = current_gpa
  @@old_total_credits = acum_ch
  @@old_cgpa = @@old_gpa/@@old_total_credits
  @@ncourse = available_courses.length
  available_courses.each do |course_info|
    @@credits << course_info[1]
  end
  @@total_credits = @@credits.inject(0, :+)
end

Instance Method Details

#fitnessObject

The fitness method quantifies the optimality of a solution (that is, a chromosome) in a genetic algorithm so that that particular chromosome may be ranked against all the other chromosomes.

Optimal chromosomes, or at least chromosomes which are more optimal, are allowed to breed and mix their datasets by any of several techniques, producing a new generation that will (hopefully) be even better.



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/simple_ga/genetic_algorithm.rb', line 197

def fitness
  return @fitness if @fitness

  # Current state inputs to be retrieved from the database.
  # @@credits = [2,3,3,3,5,2,4,4,4,4,3]
  # @@old_gpa = 58 
  # @@old_total_credits = 16
  min_credits = 16
  max_credits = 20
  target_cgpa ||= 3.7

  courses, grades, points = [], [], []
  # Split the chromosome into 2.
  0.step(@data.length-1, 2) do |j|
    courses << @data[j]
    grades << @data[j+1]
  end

  total_credits = ([courses, @@credits].transpose.map {|x| x.inject(:*)}).inject{|sum,x| sum + x }
  new_total_credits = @@old_total_credits + total_credits

  grades.each do |grade|
    case grade
      when 1
        points << 4.00
      when 2
        points << 3.70
      when 3
        points << 3.30
      when 4
        points << 3.00
      when 5
        points << 2.70
      when 6
        points << 2.30
      when 7
        points << 2.00
      else 
        points << 0.00
    end
  end

  gpa = (([@@credits, courses, points].transpose.map {|x| x.inject(:*)}).inject{|sum,x| sum + x }).round(2)
  new_gpa = @@old_gpa + gpa
  cgpa = (new_gpa/new_total_credits).round(2)

  # Core constraints.
  # Elites own a high fitness value.
  # The higher the fitness value, the higher the chance of being selected. 
  if total_credits <= max_credits && total_credits >= min_credits
      @fitness = cgpa
  # This chromosome doesn't satisfy the important constraints 
  # e.g. within the range of min_credits and max_credits
  # should be discarded.

  # Perhaps, we should add cases that statisfy one of the constraints
  # 1. credit hours + cgpa
  # 2. credit hours
  else 
      # Negative cgpa value will allow the invalid chromosome to be considered.
      # However, surprisingly the solutions suggested are more consistent and 
      # diverse.
      @fitness = 0
  end
  return @fitness
end

#improved_fitnessObject

The evolution value



265
266
267
# File 'lib/simple_ga/genetic_algorithm.rb', line 265

def improved_fitness
  return @fitness - @@old_cgpa
end

#num_of_selected_genesObject



180
181
182
183
184
185
186
187
188
# File 'lib/simple_ga/genetic_algorithm.rb', line 180

def num_of_selected_genes
  count = 0
  data.each_with_index do |gene, index|
    if index % 2 == 0 && gene == 1
      count += 1
    end
  end
  return count
end