View Javadoc
1   package net.bmahe.genetics4j.core.combination.singlepointarithmetic;
2   
3   import java.util.List;
4   import java.util.Objects;
5   import java.util.random.RandomGenerator;
6   
7   import org.apache.commons.lang3.Validate;
8   
9   import net.bmahe.genetics4j.core.chromosomes.Chromosome;
10  import net.bmahe.genetics4j.core.chromosomes.IntChromosome;
11  import net.bmahe.genetics4j.core.combination.ChromosomeCombinator;
12  import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration;
13  
14  public class IntChromosomeSinglePointArithmetic<T extends Comparable<T>> implements ChromosomeCombinator<T> {
15  
16  	private final RandomGenerator randomGenerator;
17  	private final double alpha;
18  
19  	public IntChromosomeSinglePointArithmetic(final RandomGenerator _randomGenerator, final double _alpha) {
20  		Objects.requireNonNull(_randomGenerator);
21  		Validate.inclusiveBetween(0.0d, 1.0d, _alpha);
22  
23  		this.randomGenerator = _randomGenerator;
24  		this.alpha = _alpha;
25  	}
26  
27  	@Override
28  	public List<Chromosome> combine(final AbstractEAConfiguration<T> eaConfiguration, final Chromosome chromosome1,
29  			final T firstParentFitness, final Chromosome chromosome2, final T secondParentFitness) {
30  		Objects.requireNonNull(chromosome1);
31  		Objects.requireNonNull(chromosome2);
32  		Validate.isInstanceOf(IntChromosome.class, chromosome1);
33  		Validate.isInstanceOf(IntChromosome.class, chromosome2);
34  		Validate.isTrue(chromosome1.getNumAlleles() == chromosome2.getNumAlleles());
35  
36  		final int alleleSplit = randomGenerator.nextInt(chromosome1.getNumAlleles());
37  
38  		final IntChromosome intChromosome1 = (IntChromosome) chromosome1;
39  		final IntChromosome intChromosome2 = (IntChromosome) chromosome2;
40  
41  		final int numAlleles = chromosome1.getNumAlleles();
42  		final int[] firstChildValues = new int[numAlleles];
43  		final int[] secondChildValues = new int[numAlleles];
44  
45  		for (int i = 0; i < numAlleles; i++) {
46  
47  			final int firstAllele = intChromosome1.getAllele(i);
48  			final int secondAllele = intChromosome2.getAllele(i);
49  
50  			if (i < alleleSplit) {
51  				firstChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele);
52  				secondChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele);
53  			} else {
54  				firstChildValues[i] = (int) ((1 - alpha) * firstAllele + alpha * secondAllele);
55  				secondChildValues[i] = (int) (alpha * firstAllele + (1 - alpha) * secondAllele);
56  			}
57  		}
58  
59  		return List.of(
60  				new IntChromosome(numAlleles, intChromosome1.getMinValue(), intChromosome1.getMaxValue(), firstChildValues),
61  					new IntChromosome(numAlleles,
62  							intChromosome1.getMinValue(),
63  							intChromosome1.getMaxValue(),
64  							secondChildValues));
65  	}
66  }