Class: GeneticAlgorithms::Chromosome

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ Chromosome

Returns a new instance of Chromosome.



6
7
8
9
10
11
12
13
# File 'lib/genetic_algorithms/chromosome.rb', line 6

def initialize(string)
  unless string.each_char.all? { |s| s == OFF or s == ON }
    raise InvalidChromosome, "A chromosome can only have 0's and 1's" 
  end

  @logger = Logging.logger[self.class]
  super(string)
end

Class Method Details

.random(length) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/genetic_algorithms/chromosome.rb', line 15

def self.random(length)
  chromosome = (0...length).inject(String.new) do |chromosome, i|
    chromosome += (rand(2) == 0 ? OFF : ON)
  end

  Chromosome.new chromosome
end

Instance Method Details

#check_prob(prob) ⇒ Object Also known as: crossover?, mutate?



57
58
59
# File 'lib/genetic_algorithms/chromosome.rb', line 57

def check_prob(prob)
  rand <= prob
end

#crossover(chromosome, probability = 0.7) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/genetic_algorithms/chromosome.rb', line 39

def crossover(chromosome, probability=0.7)
  unless self.size == chromosome.size
    raise IncompatibleChromosomes, "Both chromosomes need to be the same size"
  end

  offspring = self

  if crossover?(probability)
    index       = rand(0...length)
    offspring   = Chromosome.new self[0...index] + chromosome[index...length]
    @logger.debug "CROSSOVER: Using the first #{index} bits from #{self} and " +
                  "the last #{length - index} bits from #{chromosome}"
    @logger.debug "CROSSOVER: Result\t#{offspring}"
  end

  offspring.mutate  
end

#flip(char) ⇒ Object



34
35
36
37
# File 'lib/genetic_algorithms/chromosome.rb', line 34

def flip(char)
  @logger.debug "MUTATION: Triggered on #{self}" if char == ON
  char == ON ? OFF : ON
end

#mutate(prob = 0.05) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/genetic_algorithms/chromosome.rb', line 23

def mutate(prob=0.05)
  @logger.debug "MUTATION: Starting on\t#{self}"

  chromosome = self.each_char.map do |char|
    mutate?(prob) ? flip(char) : char
  end.join

  @logger.debug "MUTATION: Result\t\t#{chromosome}"
  Chromosome.new chromosome
end