1 | package de.uka.ipd.sdq.dsexplore.opt4j.operator; |
2 | |
3 | import org.opt4j.common.random.Rand; |
4 | import org.opt4j.operator.crossover.Crossover; |
5 | import org.opt4j.optimizer.ea.Pair; |
6 | |
7 | import com.google.inject.Inject; |
8 | |
9 | import de.uka.ipd.sdq.dsexplore.opt4j.genotype.DesignDecisionGenotype; |
10 | |
11 | /** |
12 | * Uniform crossover implementation. For each gene of the first offspring, |
13 | * it is randomly decided whether the value of parent 1 or parent 2 is taken. |
14 | * The second offspring then is the opposite. |
15 | * |
16 | * @author martens |
17 | * |
18 | */ |
19 | public class UniformDesignDecisionGenotypeCrossover implements Crossover<DesignDecisionGenotype> { |
20 | |
21 | private Rand random; |
22 | |
23 | @Inject |
24 | public UniformDesignDecisionGenotypeCrossover(Rand random) { |
25 | this.random = random; |
26 | } |
27 | |
28 | @Override |
29 | public Pair<DesignDecisionGenotype> crossover(DesignDecisionGenotype parent1, DesignDecisionGenotype parent2) { |
30 | |
31 | DesignDecisionGenotype o1 = parent1.newInstance(); |
32 | DesignDecisionGenotype o2 = parent2.newInstance(); |
33 | |
34 | if (o1.size() != o2.size()){ |
35 | throw new RuntimeException("Two genomes do not have the same length: "+parent1 + " and "+parent2); |
36 | } |
37 | |
38 | for (int i = 0; i < o2.size(); i ++) { |
39 | if (this.random.nextBoolean()){ |
40 | o1.add(parent1.get(i)); |
41 | o2.add(parent2.get(i)); |
42 | } else { |
43 | o1.add(parent2.get(i)); |
44 | o2.add(parent1.get(i)); |
45 | } |
46 | } |
47 | |
48 | Pair<DesignDecisionGenotype> offspring = new Pair<DesignDecisionGenotype>(o1, o2); |
49 | return offspring; |
50 | } |
51 | |
52 | } |