Debian Codegraph @

src/dr/math/DifferentialEvolution.java

raw symbols SCIP
1 /*
2 * DifferentialEvolution.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.math;
27
28
29 /**
30 * <b>global</b> minimization of a real-valued function of several
31 * variables without using derivatives using a genetic algorithm
32 * Price, K., and R. Storn. 1997. Differential evolution: a simple
33 * strategy for fast optimization. Dr. Dobb's Journal 264(April), pp. 18-24.
34 * Strategy used here: DE/rand-to-best/1/bin
35 * @author Korbinian Strimmer
36 */
37 public class DifferentialEvolution extends MultivariateMinimum
38 {
39 //
40 // Public stuff
41 //
42
43 // Variables that control aspects of the inner workings of the
44 // minimization algorithm. Setting them is optional, they
45 // are all set to some reasonable default values given below.
46
47 /** weight factor (default 0.7) */
48 public double F = 0.7 /* 0.5*/;
49
50 /** Crossing over factor (default 0.9) */
51 public double CR = 0.9 /*1.0*/;
52
53 /**
54 * variable controlling print out, default value = 0
55 * (0 -> no output, 1 -> print final value,
56 * 2 -> detailed map of optimization process)
57 */
58 public int prin = 0;
59
60
61 /**
62 * construct DE optimization modul (population size is
63 * selected automatically)
64 *
65 * <p><em>DE web page:</em>
66 * <a href="http://www.icsi.berkeley.edu/~storn/code.html"
67 * >http://www.icsi.berkeley.edu/~storn/code.html</a>
68 *
69 * @param dim dimension of optimization vector
70 */
71 public DifferentialEvolution (int dim)
72 {
73 this(dim, 5*dim);
74 }
75
76 /**
77 * construct optimization modul
78 *
79 * @param dim dimension of optimization vector
80 * @param popSize population size
81 */
82 public DifferentialEvolution (int dim, int popSize)
83 {
84
85 // Dimension and Population size
86 dimension = dim;
87 populationSize = popSize;
88
89 numFun = 0;
90
91 // Allocate memory
92 currentPopulation = new double[populationSize][dimension];
93 nextPopulation = new double[populationSize][dimension];
94 costs = new double[populationSize];
95 trialVector = new double[dimension];
96
97 // helper variable
98 //numr = 5; // for strategy DE/best/2/bin
99 numr = 3; // for stragey DE/rand-to-best/1/bin
100 r = new int[numr];
101 }
102
103
104 // implementation of abstract method
105
106 public void optimize(MultivariateFunction func, double[] xvec, double tolfx, double tolx)
107 {
108 optimize(func,xvec,tolfx,tolx,null);
109 }
110 public void optimize(MultivariateFunction func, double[] xvec, double tolfx, double tolx, MinimiserMonitor monitor)
111 {
112 f = func;
113 x = xvec;
114
115 // Create first generation
116 firstGeneration ();
117
118 stopCondition(fx, x, tolfx, tolx, true);
119
120 while (true)
121 {
122 boolean xHasChanged;
123 do
124 {
125 xHasChanged = nextGeneration ();
126
127 if (maxFun > 0 && numFun > maxFun)
128 {
129 break;
130 }
131
132 if (prin > 1 && currGen % 20 == 0)
133 {
134 printStatistics();
135 }
136 if(monitor!=null) {
137 monitor.newMinimum(fx,xvec);
138 }
139 }
140 while (!xHasChanged);
141
142
143 if (stopCondition(fx, x, tolfx, tolx, false) ||
144 (maxFun > 0 && numFun > maxFun))
145 {
146 break;
147 }
148 }
149
150 if (prin > 0) printStatistics();
151 }
152
153 //
154 // Private stuff
155 //
156
157 private MultivariateFunction f;
158 private int currGen;
159 private double fx;
160 private double[] x;
161
162 // Dimension
163 private int dimension;
164
165 // Population size
166 private int populationSize;
167
168 // Population data
169 private double trialCost;
170 private double[] costs;
171 private double[] trialVector;
172 private double[][] currentPopulation;
173 private double[][] nextPopulation;
174
175 // Helper variable
176 private int numr;
177 private int[] r;
178
179 private void printStatistics()
180 {
181 // Compute mean
182 double meanCost = 0.0;
183 for (int i = 0; i < populationSize; i++)
184 {
185 meanCost += costs[i];
186 }
187 meanCost = meanCost/populationSize;
188
189 // Compute variance
190 double varCost = 0.0;
191 for (int i = 0; i < populationSize; i++)
192 {
193 double tmp = (costs[i]-meanCost);
194 varCost += tmp*tmp;
195 }
196 varCost = varCost/(populationSize-1);
197
198 System.out.println();
199 System.out.println();
200 System.out.println();
201 System.out.println("Smallest value: " + fx);
202 System.out.println();
203 for (int k = 0; k < dimension; k++)
204 {
205 System.out.println("x[" + k + "] = " + x[k]);
206 }
207 System.out.println();
208 System.out.println("Current Generation: " + currGen);
209 System.out.println("Function evaluations: " + numFun);
210 System.out.println("Populations size (populationSize): " + populationSize);
211 System.out.println("Average value: " + meanCost);
212 System.out.println("Variance: " + varCost);
213
214 System.out.println("Weight factor (F): " + F);
215 System.out.println("Crossing-over (CR): " + CR);
216 System.out.println();
217 }
218
219 // Generate starting population
220 private void firstGeneration()
221 {
222 currGen = 1;
223
224 // Construct populationSize random start vectors
225 for (int i = 0; i < populationSize; i++)
226 {
227 for (int j = 0; j < dimension; j++ )
228 {
229 double min = f.getLowerBound(j);
230 double max = f.getUpperBound(j);
231
232 double diff = max - min;
233
234 // Uniformly distributed sample points
235 currentPopulation[i][j] = min + diff* MathUtils.nextDouble();
236 }
237 costs[i] = f.evaluate(currentPopulation[i]);
238 }
239 numFun += populationSize;
240
241 findSmallestCost ();
242 }
243
244 // check whether a parameter is out of range
245 private double checkBounds(double param, int numParam)
246 {
247 if (param < f.getLowerBound(numParam))
248 {
249 return f.getLowerBound(numParam);
250 }
251 else if (param > f.getUpperBound(numParam))
252 {
253 return f.getUpperBound(numParam);
254 }
255 else
256 {
257 return param;
258 }
259 }
260
261 // Generate next generation
262 private boolean nextGeneration()
263 {
264 boolean updateFlag = false;
265 int best = 0; // to avoid compiler complaints
266 double[][] swap;
267
268 currGen++;
269
270 // Loop through all population vectors
271 for (int r0 = 0; r0 < populationSize; r0++)
272 {
273 // Choose ri so that r0 != r[1] != r[2] != r[3] != r[4] ...
274
275 r[0] = r0;
276 for (int k = 1; k < numr; k++)
277 {
278 r[k] = randomInteger (populationSize-k);
279 for (int l = 0; l < k; l++)
280 {
281 if (r[k] >= r[l])
282 {
283 r[k]++;
284 }
285 }
286 }
287
288 copy(trialVector, currentPopulation[r0]);
289 int n = randomInteger (dimension);
290 for (int i = 0; i < dimension; i++) // perform binomial trials
291 {
292 // change at least one parameter
293 if (MathUtils.nextDouble() < CR || i == dimension - 1)
294 {
295 // DE/rand-to-best/1/bin
296 // (change to 'numr=3' in constructor when using this strategy)
297 trialVector[n] = trialVector[n] +
298 F*(x[n] - trialVector[n]) +
299 F*(currentPopulation[r[1]][n] - currentPopulation[r[2]][n]);
300
301 //DE/rand-to-best/2/bin
302 //double K = rng.nextDouble();
303 //trialVector[n] = trialVector[n] +
304 // K*(x[n] - trialVector[n]) +
305 // F*(currentPopulation[r[1]][n] - currentPopulation[r[2]][n]);
306
307
308 // DE/best/2/bin
309 // (change to 'numr=5' in constructor when using this strategy)
310 //trialVector[n] = x[n] +
311 // (currentPopulation[r[1]][n]+currentPopulation[r[2]][n]
312 // -currentPopulation[r[3]][n]-currentPopulation[r[4]][n])*F;
313 }
314 n = (n+1) % dimension;
315 }
316
317 // make sure that trial vector obeys boundaries
318 for (int i = 0; i < dimension; i++)
319 {
320 trialVector[i] = checkBounds(trialVector[i], i);
321 }
322
323
324 // Test this choice
325 trialCost = f.evaluate(trialVector);
326 if (trialCost < costs[r0])
327 {
328 // Better than old vector
329 costs[r0] = trialCost;
330 copy(nextPopulation[r0], trialVector);
331
332 // Check for new best vector
333 if (trialCost < fx)
334 {
335 fx = trialCost;
336 best = r0;
337 updateFlag = true;
338 }
339 }
340 else
341 {
342 // Keep old vector
343 copy(nextPopulation[r0], currentPopulation[r0]);
344 }
345 }
346 numFun += populationSize;
347
348 // Update best vector
349 if (updateFlag)
350 {
351 copy(x, nextPopulation[best]);
352 }
353
354 // Switch pointers
355 swap = currentPopulation;
356 currentPopulation = nextPopulation;
357 nextPopulation = swap;
358
359 return updateFlag;
360 }
361
362 // Determine vector with smallest cost in current population
363 private void findSmallestCost()
364 {
365 int best = 0;
366 fx = costs[0];
367
368 for (int i = 1; i < populationSize; i++)
369 {
370 if (costs[i] < fx)
371 {
372 fx = costs[i];
373 best = i;
374 }
375 }
376 copy(x, currentPopulation[best]);
377 }
378
379 // draw random integer in the range from 0 to n-1
380 private int randomInteger(int n)
381 {
382 return MathUtils.nextInt(n);
383 }
384 }
385