01 /*
02 * JENES
03 * A time and memory efficient Java library for genetic algorithms and more
04 * Copyright (C) 2011 Intelligentia srl
05 *
06 * This program is free software: you can redistribute it and/or modify
07 * it under the terms of the GNU General Public License as published by
08 * the Free Software Foundation, either version 3 of the License, or
09 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package jenes.tutorials.problem2;
20
21 import jenes.Fitness;
22 import jenes.GeneticAlgorithm;
23 import jenes.chromosome.IntegerChromosome;
24 import jenes.population.Individual;
25 import jenes.population.Population;
26
27 /**
28 * Tutorial showing how to extend <code>GeneticAlgorithm</code> and how to use
29 * the flexible and configurable breeding structure in Jenes.
30 * The problem consists in searching a pattern of integers with a given precision.
31 * Solutions flow through two different crossovers in parallel. Some are processed by
32 * a single point crossover, the other by a double point crossover.
33 * After solutions are mutated.
34 *
35 * This class implements the algorithm by extending <code>GeneticAlgorithm</code>.
36 *
37 * @author Luigi Troiano
38 *
39 * @version 2.0
40 *
41 * @since 1.0
42 */
43 public class PatternGA extends GeneticAlgorithm<IntegerChromosome> {
44
45 private PatternFitness fitness = new PatternFitness();
46
47 public PatternGA(Population<IntegerChromosome> pop, int numGen) {
48 super(pop, numGen);
49 this.setFitness(fitness);
50 }
51
52 @Override
53 protected boolean end() {
54 jenes.population.Population.Statistics stat = this.getCurrentPopulation().getStatistics();
55 return stat.getGroup(Population.LEGALS).getMin()[0] <= this.fitness.precision;
56 }
57
58 public class PatternFitness extends Fitness<IntegerChromosome> {
59
60 private int[] target = null;
61 private int precision = 0;
62
63 private PatternFitness() {
64 super(false);
65 }
66
67 @Override
68 public void evaluate(Individual<IntegerChromosome> individual) {
69 IntegerChromosome chrom = individual.getChromosome();
70 int diff = 0;
71 int length = chrom.length();
72 for (int i = 0; i < length; i++) {
73 diff += Math.abs(chrom.getValue(i) - target[i]);
74 }
75 individual.setScore(diff);
76 }
77
78 public void setTarget(int[] target) {
79 this.target = target;
80 }
81
82 public void setPrecision(int precision) {
83 this.precision = precision;
84 }
85 }
86 }
|
|
|