View Javadoc

1   /*
2   
3       dsh-evolve-examples  Examples for the evolve library.
4       Copyright (c) 2007-2012 held jointly by the individual authors.
5   
6       This library is free software; you can redistribute it and/or modify it
7       under the terms of the GNU Lesser General Public License as published
8       by the Free Software Foundation; either version 3 of the License, or (at
9       your option) any later version.
10  
11      This library is distributed in the hope that it will be useful, but WITHOUT
12      ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or
13      FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
14      License for more details.
15  
16      You should have received a copy of the GNU Lesser General Public License
17      along with this library;  if not, write to the Free Software Foundation,
18      Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA.
19  
20      > http://www.fsf.org/licensing/licenses/lgpl.html
21      > http://www.opensource.org/licenses/lgpl-license.php
22  
23  */
24  package org.dishevelled.evolve.examples;
25  
26  import java.util.ArrayList;
27  import java.util.Collection;
28  import java.util.Collections;
29  import java.util.List;
30  import java.util.Random;
31  
32  import org.dishevelled.evolve.EvolutionaryAlgorithm;
33  import org.dishevelled.evolve.EvolutionaryAlgorithmAdapter;
34  import org.dishevelled.evolve.EvolutionaryAlgorithmEvent;
35  import org.dishevelled.evolve.EvolutionaryAlgorithmListener;
36  import org.dishevelled.evolve.ExitStrategy;
37  import org.dishevelled.evolve.Fitness;
38  import org.dishevelled.evolve.Recombination;
39  import org.dishevelled.evolve.Selection;
40  
41  import org.dishevelled.evolve.exit.FitnessThresholdExitStrategy;
42  
43  import org.dishevelled.evolve.impl.EvolutionaryAlgorithmImpl;
44  
45  import org.dishevelled.evolve.mutate.IndividualWiseMutation;
46  import org.dishevelled.evolve.mutate.NullIndividualWiseMutation;
47  import org.dishevelled.evolve.mutate.ProportionalMutation;
48  
49  import org.dishevelled.evolve.recombine.NullRecombination;
50  
51  import org.dishevelled.evolve.select.FitnessProportionalSelection;
52  
53  /**
54   * Guess the number evolve example.
55   *
56   * @author  Michael Heuer
57   * @version $Revision$ $Date$
58   */
59  public final class GuessTheNumber
60      implements Runnable
61  {
62      /** Number to guess. */
63      private final int number;
64  
65      /** Number of individuals. */
66      private final int individuals;
67  
68      /** Maximum number to guess. */
69      private final int maxNumber;
70  
71      /** Source of randomness. */
72      private final Random random;
73  
74      /** Exit strategy. */
75      private final ExitStrategy<Integer> exitStrategy;
76  
77      /** Null recombination. */
78      private final Recombination<Integer> recombination;
79  
80      /** Mutation. */
81      private final ProportionalMutation<Integer> mutation;
82  
83      /** Fitness. */
84      private final Fitness<Integer> fitness;
85  
86      /** Selection. */
87      private final Selection<Integer> selection;
88  
89      /** True if output should be verbose. */
90      private final boolean verbose = true;
91  
92  
93      /**
94       * Create a new guess the number example.
95       */
96      public GuessTheNumber()
97      {
98          random = new Random();
99          maxNumber = 1000;
100         number = random.nextInt(maxNumber);
101         individuals = 10;
102 
103         exitStrategy = new FitnessThresholdExitStrategy<Integer>(0.99d);
104 
105         recombination = new NullRecombination<Integer>();
106 
107         mutation = new ProportionalMutation<Integer>();
108         mutation.add(new NullIndividualWiseMutation<Integer>(), 0.8d);
109         mutation.add(new IndividualWiseMutation<Integer>()
110                      {
111                          /** {@inheritDoc} */
112                          public Integer mutate(final Integer i)
113                          {
114                              int j = i.intValue();
115                              j += random.nextInt((int) (maxNumber / 4.0d));
116                              j -= random.nextInt((int) (maxNumber / 4.0d));
117                              j = Math.max(0, j);
118                              j = Math.min(maxNumber, j);
119                              return Integer.valueOf(j);
120                          }
121                      }, 0.2d);
122 
123         fitness = new Fitness<Integer>()
124             {
125                 /** {@inheritDoc} */
126                 public Double score(final Integer i)
127                 {
128                     return (1.0d / (Math.abs(number - i) + 1.0d));
129                 }
130             };
131 
132         selection = new FitnessProportionalSelection<Integer>();
133     }
134 
135     /** {@inheritDoc} */
136     public void run()
137     {
138         EvolutionaryAlgorithm<Integer> ea = new EvolutionaryAlgorithmImpl<Integer>();
139         EvolutionaryAlgorithmListener<Integer> logger = new LoggingEvolutionaryAlgorithmListener();
140         if (verbose)
141         {
142             ea.addEvolutionaryAlgorithmListener(logger);
143         }
144         try
145         {
146             Collection<Integer> population = new ArrayList<Integer>(individuals);
147             for (int i = 0; i < individuals; i++)
148             {
149                 population.add(random.nextInt(maxNumber));
150             }
151             Collection<Integer> evolved = ea.evolve(population, exitStrategy, recombination, mutation, fitness, selection);
152             System.out.println("number to guess=" + number);
153             System.out.println("done.\nevolved=" + evolved);
154         }
155         catch (RuntimeException e)
156         {
157             throw e;
158         }
159         finally
160         {
161             if (verbose)
162             {
163                 ea.removeEvolutionaryAlgorithmListener(logger);
164             }
165         }
166     }
167 
168     /**
169      * Evolutionary algorithm listener that logs exit failed events to stdout.
170      */
171     private class LoggingEvolutionaryAlgorithmListener
172         extends EvolutionaryAlgorithmAdapter<Integer>
173     {
174 
175         /** {@inheritDoc} */
176         public void exitFailed(final EvolutionaryAlgorithmEvent<Integer> event)
177         {
178             int time = event.getTime();
179             List<Integer> population = new ArrayList<Integer>(event.getPopulation());
180             Collections.sort(population);
181             System.out.println("time=" + time + " population=" + population);
182         }
183     }
184 
185     /**
186      * Main.
187      *
188      * @param args command line arguments
189      */
190     public static void main(final String[] args)
191     {
192         new GuessTheNumber().run();
193     }
194 }