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 public class FitnessCachingTest {
27
28
29 private static final int DIMENSION = 50;
30 private static final double CROSSOVER_RATE = 1;
31 private static final double MUTATION_RATE = 0.1;
32 private static final int TOURNAMENT_ARITY = 5;
33
34 private static final int POPULATION_SIZE = 10;
35 private static final int NUM_GENERATIONS = 50;
36 private static final double ELITISM_RATE = 0.2;
37
38
39 public static int fitnessCalls = 0;
40
41
42 @Test
43 public void testFitnessCaching() {
44
45 GeneticAlgorithm ga = new GeneticAlgorithm(
46 new OnePointCrossover<Integer>(),
47 CROSSOVER_RATE,
48 new BinaryMutation(),
49 MUTATION_RATE,
50 new TournamentSelection(TOURNAMENT_ARITY)
51 );
52
53
54 Population initial = randomPopulation();
55
56 StoppingCondition stopCond = new FixedGenerationCount(NUM_GENERATIONS);
57
58
59 ga.evolve(initial, stopCond);
60
61 int neededCalls =
62 POPULATION_SIZE
63 (NUM_GENERATIONS - 1)
64 ;
65 assertTrue(fitnessCalls <= neededCalls);
66 }
67
68
69
70
71
72 private static ElitisticListPopulation randomPopulation() {
73 List<Chromosome> popList = new LinkedList<Chromosome>();
74
75 for (int i=0; i<POPULATION_SIZE; i++) {
76 BinaryChromosome randChrom = new DummyCountingBinaryChromosome(BinaryChromosome.randomBinaryRepresentation(DIMENSION));
77 popList.add(randChrom);
78 }
79 return new ElitisticListPopulation(popList, popList.size(), ELITISM_RATE);
80 }
81
82 private static class DummyCountingBinaryChromosome extends DummyBinaryChromosome {
83
84 public DummyCountingBinaryChromosome(List<Integer> representation) {
85 super(representation);
86 }
87
88 @Override
89 public double fitness() {
90 fitnessCalls++;
91 return 0;
92 }
93 }
94 }