Class: Genetica::Chromosome

Inherits:
Array
  • Object
show all
Defined in:
lib/genetica/chromosome.rb

Instance Method Summary collapse

Instance Method Details

#crossover(crossover_method, crossover_probability, chromosome) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/genetica/chromosome.rb', line 3

def crossover(crossover_method, crossover_probability, chromosome)
  if crossover_probability > 0 && rand.between?(0, crossover_probability)
    self.send(crossover_method, crossover_probability, chromosome)
  else
    # There is no crossover, return chromosomes without changes
    return self, chromosome
  end
end

#mutate!(mutation_probability, alleles) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/genetica/chromosome.rb', line 37

def mutate!(mutation_probability, alleles)
  if mutation_probability > 0
    map! do |gene|
      if rand.between? 0, mutation_probability
        # Mutated Gene, we select a different gene from the alleles
        (alleles - [gene]).sample
      else
        # Gene without mutation
        gene
      end
    end
  end
end

#single_point_crossover(crossover_probability, chromosome) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/genetica/chromosome.rb', line 12

def single_point_crossover(crossover_probability, chromosome)
  locus = rand(chromosome.size) + 1

  offspring_a = take(locus) + chromosome.last(size - locus)
  offspring_b = chromosome.take(locus) + last(size - locus)

  return Chromosome.new(offspring_a), Chromosome.new(offspring_b)
end

#to_sObject



51
52
53
# File 'lib/genetica/chromosome.rb', line 51

def to_s
  join
end

#uniform_crossover(crossover_probability, chromosome) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/genetica/chromosome.rb', line 21

def uniform_crossover(crossover_probability, chromosome)
  offspring_a, offspring_b = Array.new, Array.new

  chromosome.size.times do |i|
    if rand(2) == 0
      offspring_a << self[i]
      offspring_b << chromosome[i]
    else
      offspring_a << chromosome[i]
      offspring_b << self[i]
    end
  end

  return Chromosome.new(offspring_a), Chromosome.new(offspring_b)
end