Class: Wallace::Operators::PositionCrossoverOperator

Inherits:
Wallace::Operator show all
Defined in:
lib/operators/position_crossover_operation.rb

Overview

The position crossover operator takes two parents as input and creates two offspring.

A random number of loci are selected from the first parent and all genes at those loci are copied to the corresponding proto-children of each parent.

The remaining genes are determined by finding the order of the remaining alleles (those not contained at the randomly selected loci) in the opposite parent and inserting them into the chromosome slots in that given order.

Instance Method Summary collapse

Methods inherited from Wallace::Operator

#initialize, #produce

Constructor Details

This class inherits a constructor from Wallace::Operator

Instance Method Details

#operate(rng, inputs) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/operators/position_crossover_operation.rb', line 13

def operate(rng, inputs)

  # Select a random number of loci to fix the alleles at.
  len = inputs[0].length
  loci = (0...len).to_a.sample(rng.rand(1...len), random: rng)

  # Generate the proto-children by copying the alleles at
  # the selected loci.
  #
  # Rather than having the alleles array we could just check the
  # child arrays. This would be less code, but there may be a lot
  # of null placeholder values so the look-up will take longer.
  children = Array.new(2) { Array.new(len) { nil } }
  alleles = [[],[]]
  loci.each do |i|
    alleles[0] << inputs[0][i]
    alleles[1] << inputs[1][i]
    children[0][i] = inputs[0][i]
    children[1][i] = inputs[1][i]
  end

  # Determine the order of the remaining alleles from the
  # opposite parent for each protochild.
  alleles.each_index do |i|
    alleles[i] = inputs[(i+1)%2].select { |a| alleles[i].exclude? a }
  end

  # Fill the remaining loci of each chromosome using the
  # determined order.
  children.each_index do |c|
    children[c].map! { |g| g.nil? ? alleles[c].shift : g}
  end

  return children

end