jenes.tutorials.problem4.EntropyFitness

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.problem4;
20 
21 import jenes.Fitness;
22 import jenes.chromosome.DoubleChromosome;
23 import jenes.population.Individual;
24 
25 /**
26  *
27  @author Luigi Troiano
28  */
29 public class EntropyFitness extends Fitness<DoubleChromosome> {
30 
31     public static EntropyFitness MAX = new EntropyFitness(true);
32     public static EntropyFitness MIN = new EntropyFitness(false);
33 
34     private EntropyFitness(boolean maximize) {
35         super(maximize);
36     }
37 
38     @Override
39     public void evaluate(Individual<DoubleChromosome> individual) {
40         DoubleChromosome chrom = individual.getChromosome();
41 
42         int length = chrom.length();
43 
44         double sum = 0.0;
45         for (int i = 0; i < length; ++i) {
46             sum += chrom.getValue(i);
47         }
48 
49         double entropy = 0.0;
50         for (int i = 0; i < length; ++i) {
51             double pxi = chrom.getValue(i/ sum;
52             chrom.setValue(i, pxi);
53 
54             entropy -= (pxi * Math.log(pxi/ Math.log(2));
55         }
56 
57         individual.setScore(entropy);
58     }
59 }