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.FloatChromosome;
11  import net.bmahe.genetics4j.core.combination.ChromosomeCombinator;
12  import net.bmahe.genetics4j.core.spec.AbstractEAConfiguration;
13  
14  public class FloatChromosomeSinglePointArithmetic<T extends Comparable<T>> implements ChromosomeCombinator<T> {
15  
16  	private final RandomGenerator randomGenerator;
17  	private final float alpha;
18  
19  	public FloatChromosomeSinglePointArithmetic(final RandomGenerator _randomGenerator, final float _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(FloatChromosome.class, chromosome1);
33  		Validate.isInstanceOf(FloatChromosome.class, chromosome2);
34  		Validate.isTrue(chromosome1.getNumAlleles() == chromosome2.getNumAlleles());
35  
36  		final int alleleSplit = randomGenerator.nextInt(chromosome1.getNumAlleles());
37  
38  		final FloatChromosome intChromosome1 = (FloatChromosome) chromosome1;
39  		final FloatChromosome intChromosome2 = (FloatChromosome) chromosome2;
40  
41  		final int numAlleles = chromosome1.getNumAlleles();
42  		final float[] firstChildValues = new float[numAlleles];
43  		final float[] secondChildValues = new float[numAlleles];
44  
45  		for (int i = 0; i < numAlleles; i++) {
46  
47  			final float firstAllele = intChromosome1.getAllele(i);
48  			final float secondAllele = intChromosome2.getAllele(i);
49  
50  			if (i < alleleSplit) {
51  				firstChildValues[i] = alpha * firstAllele + (1 - alpha) * secondAllele;
52  				secondChildValues[i] = (1 - alpha) * firstAllele + alpha * secondAllele;
53  			} else {
54  				firstChildValues[i] = (1 - alpha) * firstAllele + alpha * secondAllele;
55  				secondChildValues[i] = alpha * firstAllele + (1 - alpha) * secondAllele;
56  			}
57  		}
58  
59  		return List.of(
60  				new FloatChromosome(numAlleles,
61  						intChromosome1.getMinValue(),
62  						intChromosome1.getMaxValue(),
63  						firstChildValues),
64  				new FloatChromosome(numAlleles,
65  						intChromosome1.getMinValue(),
66  						intChromosome1.getMaxValue(),
67  						secondChildValues));
68  	}
69  }