Class: Algorithm::Genetic::Gene
- Inherits:
-
Object
- Object
- Algorithm::Genetic::Gene
- Defined in:
- lib/algorithm/genetic/gene.rb
Overview
A gene class
Instance Attribute Summary collapse
-
#code ⇒ Object
readonly
Returns the value of attribute code.
-
#fitness ⇒ Object
readonly
Returns the value of attribute fitness.
Instance Method Summary collapse
-
#crossover_with(partner) ⇒ Object
crossover with a partner, returning a couple of children.
-
#initialize(code, evaluator, opts = {}) ⇒ Gene
constructor
constructor of Gene.
-
#mutate! ⇒ Object
mutate the code.
-
#terminated? ⇒ Boolean
judgement termination.
Constructor Details
#initialize(code, evaluator, opts = {}) ⇒ Gene
constructor of Gene
- code
-
initial code as Array
- evaluator
-
a Evaluator instance or a Proc instance returns Evaluator instance
- opts
-
hash of options
options:
:crossover :: an array of module name including crossover method and params
:mutation :: an array of module name including mutate method and params
:mutation_chance :: mutation chance (float of 0 to 1)
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/algorithm/genetic/gene.rb', line 19 def initialize(code, evaluator, opts = {}) @code, @evaluator_org, @opts = code, evaluator, opts if @evaluator_org.respond_to?(:fitness) # Evaluator instance @evaluator = @evaluator_org else # Proc instance @evaluator = @evaluator_org.call end @fitness = @evaluator.fitness(self) if opts[:crossover] @crossover_params = opts[:crossover].dup crossover_module = @crossover_params.shift.to_s.capitalize self.extend(Algorithm::Genetic::Crossover.const_get(crossover_module)) end if opts[:mutation] @mutation_params = opts[:mutation].dup mutation_module = @mutation_params.shift.to_s.capitalize self.extend(Algorithm::Genetic::Mutation.const_get(mutation_module)) end @mutation_chance = opts[:mutation_chance] || 0.5 end |
Instance Attribute Details
#code ⇒ Object (readonly)
Returns the value of attribute code.
7 8 9 |
# File 'lib/algorithm/genetic/gene.rb', line 7 def code @code end |
#fitness ⇒ Object (readonly)
Returns the value of attribute fitness.
7 8 9 |
# File 'lib/algorithm/genetic/gene.rb', line 7 def fitness @fitness end |
Instance Method Details
#crossover_with(partner) ⇒ Object
crossover with a partner, returning a couple of children
- partner
-
a partner’s gene
44 45 46 47 |
# File 'lib/algorithm/genetic/gene.rb', line 44 def crossover_with(partner) code1, code2 = crossover(self, partner, *@crossover_params) return Gene.new(code1, @evaluator_org, @opts), Gene.new(code2, @evaluator_org, @opts) end |
#mutate! ⇒ Object
mutate the code
50 51 52 53 54 |
# File 'lib/algorithm/genetic/gene.rb', line 50 def mutate! return if rand > @mutation_chance @code = mutate(@code, *@mutation_params) @fitness = @evaluator.fitness(self) end |
#terminated? ⇒ Boolean
judgement termination
57 58 59 |
# File 'lib/algorithm/genetic/gene.rb', line 57 def terminated? @evaluator.terminated?(self) end |