1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math.genetics;
18
19 import static org.junit.Assert.*;
20
21 import java.util.LinkedList;
22 import java.util.List;
23 import org.junit.Test;
24
25
26
27
28 public class GeneticAlgorithmTestBinary {
29
30
31 private static final int DIMENSION = 50;
32 private static final int POPULATION_SIZE = 50;
33 private static final int NUM_GENERATIONS = 50;
34 private static final double ELITISM_RATE = 0.2;
35 private static final double CROSSOVER_RATE = 1;
36 private static final double MUTATION_RATE = 0.1;
37 private static final int TOURNAMENT_ARITY = 2;
38
39 @Test
40 public void test() {
41
42
43
44 GeneticAlgorithm ga = new GeneticAlgorithm(
45 new OnePointCrossover<Integer>(),
46 CROSSOVER_RATE,
47 new BinaryMutation(),
48 MUTATION_RATE,
49 new TournamentSelection(TOURNAMENT_ARITY)
50 );
51
52
53 Population initial = randomPopulation();
54
55 StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);
56
57
58 Chromosome bestInitial = initial.getFittestChromosome();
59
60
61 Population finalPopulation = ga.evolve(initial, stopCond);
62
63
64 Chromosome bestFinal = finalPopulation.getFittestChromosome();
65
66
67
68
69 assertTrue(bestFinal.compareTo(bestInitial) > 0);
70
71
72
73 }
74
75
76
77
78
79
80
81 private static ElitisticListPopulation randomPopulation() {
82 List<Chromosome> popList = new LinkedList<Chromosome>();
83
84 for (int i=0; i<POPULATION_SIZE; i++) {
85 BinaryChromosome randChrom = new FindOnes(BinaryChromosome.randomBinaryRepresentation(DIMENSION));
86 popList.add(randChrom);
87 }
88 return new ElitisticListPopulation(popList, popList.size(), ELITISM_RATE);
89 }
90
91
92
93
94
95
96 private static class FindOnes extends BinaryChromosome {
97
98 public FindOnes(List<Integer> representation) {
99 super(representation);
100 }
101
102
103
104
105 public double fitness() {
106 int num = 0;
107 for (int val : this.getRepresentation()) {
108 if (val != 0)
109 num++;
110 }
111
112 return num;
113 }
114
115 @Override
116 public AbstractListChromosome<Integer> newFixedLengthChromosome(List<Integer> representation) {
117 return new FindOnes(representation);
118 }
119
120 }
121 }