Class: MHL::RealVectorGenotypeSpace

Inherits:
Object
  • Object
show all
Defined in:
lib/mhl/real_vector_genotype_space.rb

Overview

This class implements a genotype with real space representation

Instance Method Summary collapse

Constructor Details

#initialize(opts, logger) ⇒ RealVectorGenotypeSpace

Returns a new instance of RealVectorGenotypeSpace.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/mhl/real_vector_genotype_space.rb', line 5

def initialize(opts, logger)
  @random_func = opts[:random_func]

  @dimensions = opts[:dimensions].to_i
  unless @dimensions and @dimensions > 0
    raise ArgumentError, 'The number of dimensions must be a positive integer!'
  end

  # TODO: enable to choose which recombination function to use
  case opts[:recombination_type].to_s
  when /intermediate/i
    @recombination_func = :extended_intermediate_recombination
  when /line/i
    @recombination_func = :extended_line_recombination
  else
    raise ArgumentError, 'Recombination function must be either line or intermediate!'
  end

  @constraints = opts[:constraints]
  if !@constraints or @constraints.size != @dimensions
    raise ArgumentError, 'Real-valued GA variants require constraints!'
  end

  @logger = logger
end

Instance Method Details

#get_randomObject



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mhl/real_vector_genotype_space.rb', line 31

def get_random
  if @random_func
    @random_func.call
  else
    if @constraints
      @constraints.map{|x| x[:from] + SecureRandom.random_number(x[:to] - x[:from]) }
    else
      raise 'Automated random genotype generation when no constraints are provided is not implemented yet!'
    end
  end
end

#reproduce_from(p1, p2, mutation_rv, recombination_rv) ⇒ Object

reproduction with power mutation and line or intermediate recombination



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/mhl/real_vector_genotype_space.rb', line 44

def reproduce_from(p1, p2, mutation_rv, recombination_rv)
  # make copies of p1 and p2
  # (we're only interested in the :genotype key)
  c1 = { genotype: p1[:genotype].dup }
  c2 = { genotype: p2[:genotype].dup }

  # mutation comes first
  power_mutation(c1[:genotype], mutation_rv)
  power_mutation(c2[:genotype], mutation_rv)

  # and then recombination
  send(@recombination_func, c1[:genotype], c2[:genotype], recombination_rv)

  if @constraints
    repair_chromosome(c1[:genotype])
    repair_chromosome(c2[:genotype])
  end

  return c1, c2
end