Class: GeneGenie::Gene

Inherits:
Object
  • Object
show all
Defined in:
lib/gene_genie/gene.rb

Overview

A Gene is the basic unit of the genetic algorithm. Genes hold the information used to evaluate their fitness. They are combined into new Genes during the optimisation process.

Since:

  • 0.0.1

Instance Method Summary collapse

Constructor Details

#initialize(information:, fitness_evaluator:, gene_combiner: GeneGenie::Combiner::OnePointCombiner.new) ⇒ Gene

Returns a new instance of Gene.

Since:

  • 0.0.1



9
10
11
12
13
14
15
16
17
18
# File 'lib/gene_genie/gene.rb', line 9

def initialize(information:,
               fitness_evaluator:,
               gene_combiner: GeneGenie::Combiner::OnePointCombiner.new)
  fail ArgumentError, 'information must be Array' unless information.kind_of? Array
  fail ArgumentError, 'information must be Array of Hashes' unless information[0].kind_of? Hash

  @information = information
  @fitness_evaluator = fitness_evaluator
  @combiner = gene_combiner
end

Instance Method Details

#<=>(other) ⇒ Object

Since:

  • 0.0.1



47
48
49
# File 'lib/gene_genie/gene.rb', line 47

def <=>(other)
  fitness <=> other.fitness
end

#combine(other_gene) ⇒ Object

Since:

  • 0.0.1



43
44
45
# File 'lib/gene_genie/gene.rb', line 43

def combine(other_gene)
  @combiner.call(self, other_gene)
end

#fitnessObject

Since:

  • 0.0.1



24
25
26
# File 'lib/gene_genie/gene.rb', line 24

def fitness
  @fitness ||= @fitness_evaluator.fitness(@information)
end

#fitness_evaluatorObject

Since:

  • 0.0.1



28
29
30
# File 'lib/gene_genie/gene.rb', line 28

def fitness_evaluator
  @fitness_evaluator
end

#mutate(mutator) ⇒ Object

Since:

  • 0.0.1



36
37
38
39
40
41
# File 'lib/gene_genie/gene.rb', line 36

def mutate(mutator)
  @information = mutator.call @information
  @fitness = nil
  @normalised_fitness = nil
  self
end

#normalised_fitness(minimum) ⇒ Object

Since:

  • 0.0.1



32
33
34
# File 'lib/gene_genie/gene.rb', line 32

def normalised_fitness(minimum)
  @normalised_fitness ||= fitness - minimum
end

#to_hashesObject

Since:

  • 0.0.1



20
21
22
# File 'lib/gene_genie/gene.rb', line 20

def to_hashes
  @information
end