Debian Codegraph @

src/dr/math/ConjugateGradientSearch.java

raw symbols SCIP
1 /*
2 * ConjugateGradientSearch.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 * minimization of a real-valued function of
31 * several variables using a the nonlinear
32 * conjugate gradient method where several variants of the direction
33 * update are available (Fletcher-Reeves, Polak-Ribiere,
34 * Beale-Sorenson, Hestenes-Stiefel) and bounds are respected.
35 * Gradients are computed numerically if they are not supplied by the
36 * user. The line search is entirely based on derivative
37 * evaluation, similar to the strategy used in macopt (Mackay).
38 *
39 * @version $Id: ConjugateGradientSearch.java,v 1.3 2005/05/24 20:26:00 rambaut Exp $
40 *
41 * @author Korbinian Strimmer
42 */
43 public class ConjugateGradientSearch extends MultivariateMinimum
44 {
45 //
46 // Public stuff
47 //
48
49 public final static int FLETCHER_REEVES_UPDATE = 0;
50 public final static int POLAK_RIBIERE_UPDATE = 1;
51 public final static int BEALE_SORENSON_HESTENES_STIEFEL_UPDATE = 2;
52
53 // Variables that control aspects of the inner workings of the
54 // minimization algorithm. Setting them is optional, they
55 // are all set to some reasonable default values given below.
56
57 /**
58 * controls the printed output from the routine
59 * (0 -> no output, 1 -> print only starting and final values,
60 * 2 -> detailed map of the minimisation process),
61 * the default value is 0
62 */
63 public int prin = 0;
64
65 /**
66 * defaultStep is a steplength parameter and should be set equal
67 * to the expected distance from the solution (in a line search)
68 * exceptionally small or large values of defaultStep lead to
69 * slower convergence on the first few iterations (the step length
70 * itself is adapted during search), the default value is 1.0
71 */
72 public double defaultStep = 1.0;
73
74
75 /**
76 * conjugateGradientStyle determines the method for the
77 * conjugate gradient direction update
78 * update (0 -> Fletcher-Reeves, 1 -> Polak-Ribiere,
79 * 2 -> Beale-Sorenson, Hestenes-Stiefel), the default is 2.
80 */
81 public int conjugateGradientStyle = BEALE_SORENSON_HESTENES_STIEFEL_UPDATE;
82
83
84 public ConjugateGradientSearch() {
85 }
86
87 public ConjugateGradientSearch(int conGradStyle) {
88 this.conjugateGradientStyle = conGradStyle;
89 }
90
91
92 // implementation of abstract method
93
94 public void optimize(MultivariateFunction f, double[] x, double tolfx, double tolx)
95 {
96 optimize(f,x,tolfx,tolx,null);
97 }
98 public void optimize(MultivariateFunction f, double[] x, double tolfx, double tolx, MinimiserMonitor monitor)
99 {
100 xvec = x;
101 numArgs = f.getNumArguments();
102
103 boolean numericalGradient;
104 if (f instanceof MFWithGradient)
105 {
106 numericalGradient = false;
107 fgrad = (MFWithGradient) f;
108 }
109 else
110 {
111 numericalGradient = true;
112 fgrad = null;
113 }
114
115
116 // line function
117 LineFunction lf = new LineFunction(f);
118
119 // xvec contains current guess for minimum
120 lf.checkPoint(xvec);
121 double[] xold = new double[numArgs];
122 copy(xold, xvec);
123
124 // function value and gradient at current guess
125 numFun = 0;
126 double fx;
127 numGrad = 0;
128 gvec = new double[numArgs];
129 if (numericalGradient)
130 {
131 fx = f.evaluate(xvec);
132 numFun++;
133 NumericalDerivative.gradient(f, xvec, gvec);
134 numFun += 2*numArgs;
135 }
136 else
137 {
138 fx = fgrad.evaluate(xvec, gvec);
139 numFun++;
140 numGrad++;
141 }
142 double[] gold = new double[numArgs];
143 copy(gold, gvec);
144
145 // init stop condition
146 stopCondition(fx, xvec, tolfx, tolx, true);
147
148 // currently active variables
149 boolean[] active = new boolean[numArgs];
150 double numActive = lf.checkVariables(xvec, gvec, active);
151
152 // if no variables are active return
153 if (numActive == 0)
154 {
155 return;
156 }
157
158 // initial search direction (steepest descent)
159 sdir = new double[numArgs];
160 steepestDescentDirection(sdir, gvec, active);
161 lf.update(xvec, sdir);
162
163 // slope at start point in initial direction
164 double slope = gradientProjection(sdir, gvec);
165
166
167 if (prin > 0)
168 {
169 System.out.println("--- starting minimization ---");
170 System.out.println("... current parameter settings ...");
171 System.out.println("... tolx ... " + tolx);
172 System.out.println("... tolfx ... " + tolfx);
173 System.out.println("... maxFun ... " + maxFun);
174 System.out.println();
175 printVec("... start vector ...", xvec);
176 System.out.println();
177 printVec("... start direction ...", sdir);
178 }
179
180 int numLin = 0;
181 lastStep = defaultStep;
182 while(true)
183 {
184 // determine an appropriate step length
185 double step = findStep(lf, fx, slope, numericalGradient);
186 lastStep = step;
187 numLin++;
188
189 // update xvec
190 lf.getPoint(step, xvec);
191 lf.checkPoint(xvec);
192
193
194 // function value at current guess
195 if (numericalGradient)
196 {
197 fx = f.evaluate(xvec);
198 numFun++;
199 }
200 else
201 {
202 // compute gradient as well
203 fx = fgrad.evaluate(xvec, gvec);
204 numFun++;
205 numGrad++;
206 }
207
208 // test for for convergence
209 if (stopCondition(fx, xvec, tolfx, tolx, false)
210 || (maxFun > 0 && numFun > maxFun))
211 {
212 break;
213 }
214
215 // Compute numerical gradient
216 if (numericalGradient)
217 {
218 NumericalDerivative.gradient(f, xvec, gvec);
219 numFun += 2*numArgs;
220 }
221
222
223 numActive = lf.checkVariables(xvec, gvec, active);
224
225 // if all variables are inactive return
226 if (numActive == 0)
227 {
228 break;
229 }
230
231 // determine new search direction
232 conjugateGradientDirection(sdir, gvec, gold, active);
233 lf.checkDirection(xvec, sdir);
234
235 // compute slope in new direction
236 slope = gradientProjection(sdir, gvec);
237
238 if (slope >= 0)
239 {
240 //reset to steepest descent direction
241 steepestDescentDirection(sdir, gvec, active);
242
243 // compute slope in new direction
244 slope = gradientProjection(sdir, gvec);
245
246 // reset to default step length
247 lastStep = defaultStep;
248 }
249
250
251 // other updates
252 lf.update(xvec, sdir);
253 copy(xold, xvec);
254 copy(gold, gvec);
255
256 if (prin > 1)
257 {
258 System.out.println();
259 System.out.println("Function value: " +
260 f.evaluate(xvec));
261 System.out.println();
262 printVec("... new vector ...", xvec);
263 System.out.println();
264 printVec("... new direction ...", sdir);
265 System.out.println("... numFun ... " + numFun);
266 if (!numericalGradient)
267 {
268 System.out.println("... numGrad ... " + numGrad);
269 }
270 System.out.println("... numLin ... " + numLin);
271 System.out.println();
272 }
273 if(monitor!=null) {
274 monitor.newMinimum(f.evaluate(xvec),xvec);
275 }
276
277 }
278
279 if (prin > 0)
280 {
281 System.out.println();
282 printVec("... final vector ...", xvec);
283 System.out.println("... numFun ... " + numFun);
284 System.out.println("... numLin ... " + numLin);
285 System.out.println();
286 System.out.println("--- end of minimization ---");
287 }
288 }
289
290
291 //
292 // Private stuff
293 //
294
295 private int numArgs, numGrad;
296 private double lastStep;
297 private double[] xvec, gvec, sdir;
298 private MFWithGradient fgrad;
299
300 private double findStep(LineFunction lf, double f0, double s0, boolean numericalGradient)
301 {
302 // f0 function value at step = 0
303 // s0 slope at step = 0
304
305 double step;
306 double maxStep = lf.getUpperBound();
307 if (maxStep <= 0 || s0 == 0)
308 {
309 return 0.0;
310 }
311
312 //step = Math.abs(lf.findMinimum());
313
314
315 // growing/shrinking factors for bracketing
316
317 double g1 = 2.0;
318 double g2 = 1.25;
319 double g3 = 0.5;
320
321 // x1 and x2 try to bracket the minimum
322
323 double x1 = 0;
324 double s1 = s0;
325 double x2 = lastStep*g2;
326 if(x2 > maxStep)
327 {
328 x2 = maxStep*g3;
329 }
330 double s2 = computeDerivative(lf, x2, numericalGradient);
331
332 // we need to go further to bracket minimum
333 boolean boundReached = false;
334 while (s2 <= 0 && !boundReached)
335 {
336 x1 = x2;
337 s1 = s2;
338 x2 = x2*g1;
339 if (x2 > maxStep)
340 {
341 x2 = maxStep;
342 boundReached = true;
343 }
344 s2 = computeDerivative(lf, x2, numericalGradient);
345 }
346
347 // determine step length by quadratic interpolation
348 // for minimum in interval [x1,x2]
349
350 if (s2 <= 0)
351 {
352 // true local minimum could NOT be bracketed
353 // instead we have a local minimum on a boundary
354
355 step = x2;
356 }
357 else
358 {
359 // minimum is bracketed
360
361 step = (x1*s2-x2*s1)/(s2-s1);
362 // note that nominator is always positive
363 }
364
365 // just to be safe - should not be necessary
366 if (step >= maxStep)
367 {
368 step = maxStep;
369 }
370 if (step < 0)
371 {
372 step = 0;
373 }
374
375 return step;
376 }
377
378 private double computeDerivative(LineFunction lf, double lambda, boolean numericalGradient)
379 {
380 if (numericalGradient)
381 {
382 numFun += 2;
383 return NumericalDerivative.firstDerivative(lf, lambda);
384 }
385 else
386 {
387 /* lf.getPoint(lambda, xvec);
388 lf.checkPoint(xvec);
389 fgrad.computeGradient(xvec, gvec);
390 numGrad++;
391 return gradientProjection(sdir, gvec);
392 */
393
394 // the following code prevents overstepping
395 // and is due to Jesse Stone <[email protected]>
396
397 double[] xtmp = new double[numArgs];
398 copy(xtmp, xvec);
399 lf.getPoint(lambda, xtmp);
400 lf.checkPoint(xtmp);
401 fgrad.computeGradient(xtmp, gvec);
402 numGrad++;
403 return gradientProjection(sdir, gvec);
404
405 }
406 }
407
408 /*
409 private void testStep(double f0, double s0, double f1, double s1, double step)
410 {
411 // f0 function value at x=0
412 // s0 slope at x=0
413
414 // f1 function value at x=step
415 // f2 function value at x=step
416
417 double mue = 0.0001;
418 double eta = 0.9;
419
420 // sufficent decrease in function value
421 if (f1 <= mue*s0*step + f0)
422 {
423 System.out.println("<<< Sufficient decrease in function value");
424 }
425 else
426 {
427 System.out.println("<<< NO sufficient decrease in function value");
428 }
429
430 // sufficient decrease in slope
431 if (Math.abs(s1) <= eta*Math.abs(s0))
432 {
433 System.out.println("<<< Sufficient decrease in slope");
434 }
435 else
436 {
437 System.out.println("<<< NO sufficient decrease in slope");
438 }
439 }
440 */
441
442 private void conjugateGradientDirection(double[] sdir, double[] gvec, double[] gold,
443 boolean[] active)
444 {
445 double gg = 0;
446 double dgg = 0;
447 for (int i = 0; i < numArgs; i++)
448 {
449 if (active[i])
450 {
451 switch (conjugateGradientStyle)
452 {
453 case 0:
454 // Fletcher-Reeves
455 dgg += gvec[i]*gvec[i];
456 gg += gold[i]*gold[i];
457 break;
458
459 case 1:
460 // Polak-Ribiere
461 dgg += gvec[i]*(gvec[i]-gold[i]);
462 gg += gold[i]*gold[i];
463 break;
464
465 case 2:
466 // Beale-Sorenson
467 // Hestenes-Stiefel
468 dgg += gvec[i] * (gvec[i] - gold[i]);
469 gg += sdir[i] * (gvec[i] - gold[i]);
470 break;
471 }
472 }
473 }
474 double beta = dgg/gg;
475 if (beta < 0 || gg == 0)
476 {
477 // better convergence (Gilbert and Nocedal)
478 beta = 0;
479 }
480 for (int i = 0; i < numArgs; i++)
481 {
482 if (active[i])
483 {
484 sdir[i] = -gvec[i] + beta*sdir[i];
485 }
486 else
487 {
488 sdir[i] = 0;
489 }
490 }
491 }
492
493 private void steepestDescentDirection(double[] sdir, double[] gvec, boolean[] active)
494 {
495 for (int i = 0; i < numArgs; i++)
496 {
497 if (active[i])
498 {
499 sdir[i] = -gvec[i];
500 }
501 else
502 {
503 sdir[i] = 0;
504 }
505 }
506 }
507
508 private double gradientProjection(double[] sdir, double[] gvec)
509 {
510 double s = 0;
511 double n = gvec.length;
512 for (int i = 0; i < n; i++)
513 {
514 s += gvec[i]*sdir[i];
515 }
516
517 return s;
518 }
519
520 private void printVec(String s, double[] x)
521 {
522 System.out.println(s);
523 for (int i=0; i < x.length; i++)
524 {
525 System.out.print(x[i] + " ");
526 }
527 System.out.println();
528 }
529 }