jenes.tutorial.old.problem2.PatternGA.java

01 /*
02  * JENES
03  * A time asnd 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.old.problem2;
20 
21 import jenes.GeneticAlgorithm;
22 import jenes.chromosome.IntegerChromosome;
23 import jenes.population.Individual;
24 import jenes.population.Population;
25 
26 /**
27  * Tutorial showing how to extend <code>GeneticAlgorithm</code> and how to use
28  * the flexible and configurable breeding structure in Jenes.
29  * The problem consists in searching a pattern of integers with a given precision.
30  * Solutions flow through two different crossovers in parallel. Some are processed by
31  * a single point crossover, the other by a double point crossover.
32  * After solutions are mutated.
33  *
34  * This class implements the algorithm by extending <code>GeneticAlgorithm</code>.
35  *
36  @author Luigi Troiano
37  @author Pierpaolo Lombardi
38  *
39  @version 1.0
40  
41  @since 1.0
42  */
43 public class PatternGA extends GeneticAlgorithm<IntegerChromosome>{
44     
45     private int[] target;
46     private int precision;
47     
48     public PatternGA(Population<IntegerChromosome> pop, int numGen) {
49         super(pop,numGen);
50         this.setBiggerIsBetter(false);
51     }
52     
53     public void setTarget(int[] target) {
54         this.target = target;
55     }
56     
57     public void setPrecision(int precision) {
58         this.precision = precision;
59     }
60     
61     @Override
62     public void evaluateIndividual(Individual<IntegerChromosome> individual) {
63         IntegerChromosome chrom = individual.getChromosome();
64         int diff = 0;
65         int length=chrom.length();
66         for(int i=0;i<length;i++){
67             diff += Math.abs(chrom.getValue(i)-this.target[i]);
68         }
69         individual.setScore(diff);
70     }
71     
72     @Override
73     protected boolean end(){
74         jenes.population.Population.Statistics stat = this.getCurrentPopulation().getStatistics();
75         return stat.getLegalLowestScore() <= this.precision;
76     }
77 }