Debian Codegraph @

easel/esl_minimizer.c

raw symbols SCIP
1 /* Multidimensional optimization using conjugate gradient descent.
2 *
3 * Can be used even without derivative information; falls back to
4 * a numeric gradient if analytic gradient is unavailable.
5 *
6 * Contents:
7 * 1. esl_min_ConjugateGradientDescent(), our optimizer
8 * 2. ESL_MIN_CFG, for optional configuration/customization
9 * 3. ESL_MIN_DAT, for optional data collection
10 * 4. Internal functions: numeric deriv, bracketing, 1D line min
11 * 5. Unit tests
12 * 6. Test driver
13 * 7. Example
14 */
15 #include <esl_config.h>
16
17 #include <math.h>
18 #include <float.h>
19
20 #include "easel.h"
21 #include "esl_vectorops.h"
22
23 #include "esl_minimizer.h"
24
25
26
27 static void numeric_derivative(ESL_MIN_CFG *cfg, double *x, int n,
28 double (*func)(double *, int, void*),
29 void *prm, double *dx, ESL_MIN_DAT *dat);
30 static int bracket(ESL_MIN_CFG *cfg, double *ori, double *d, int n, double firststep,
31 double (*func)(double *, int, void *), void *prm, double *wrk,
32 double *ret_ax, double *ret_bx, double *ret_cx,
33 double *ret_fa, double *ret_fb, double *ret_fc, ESL_MIN_DAT *dat);
34 static void brent(ESL_MIN_CFG *cfg, double *ori, double *dir, int n,
35 double (*func)(double *, int, void *), void *prm, double a, double b,
36 double *xvec, double *opt_x, double *opt_fx, ESL_MIN_DAT *dat);
37
38
39
40 /*****************************************************************
41 * 1. esl_min_ConjugateGradientDescent(), our optimizer
42 *****************************************************************/
43
44 /* Function: esl_min_ConjugateGradientDescent()
45 * Incept: SRE, Wed Jun 22 08:49:42 2005 [St. Louis]
46 *
47 * Purpose: n-dimensional minimization by conjugate gradient descent.
48 *
49 * An initial point is provided by <x>, a vector of <n>
50 * components. The caller also provides a function <*func()> that
51 * compute the objective function f(x) when called as
52 * <(*func)(x, n, prm)>, and a function <*dfunc()> that can
53 * compute the gradient <dx> at <x> when called as
54 * <(*dfunc)(x, n, prm, dx)>, given an allocated vector <dx>
55 * to put the derivative in. Any additional data or fixed
56 * parameters that these functions require are passed by
57 * the void pointer <prm>.
58 *
59 * The first step of each iteration is to try to bracket
60 * the minimum along the current direction. The initial step
61 * size is controlled by <u[]>; the first step will not exceed
62 * <u[i]> for any dimension <i>. (You can think of <u> as
63 * being the natural "units" to use along a graph axis, if
64 * you were plotting the objective function.)
65 *
66 * The caller also provides an allocated workspace sufficient to
67 * hold four allocated n-vectors. (4 * sizeof(double) * n).
68 *
69 * Iterations continue until the objective function has changed
70 * by less than a fraction <tol>. This should not be set to less than
71 * sqrt(<DBL_EPSILON>).
72 *
73 * Upon return, <x> is the minimum, and <opt_fx> (if
74 * provided) is f(x), the function value at <x>.
75 *
76 * Args: cfg - optional custom config for tunable params; or NULL
77 * x - an initial guess n-vector; RETURN: x at the minimum
78 * n - dimensionality of all vectors
79 * *func() - function for computing objective function f(x)
80 * *dfunc() - function for computing a gradient at x
81 * prm - void ptr to any data/params func,dfunc need
82 * opt_fx - optRETURN: f(x) at the minimum; or NULL if unwanted
83 * opt_dat - optRETURN: table of stats on the run; or NULL if unwanted
84 *
85 * Returns: <eslOK> on success. <x> is updated to be the minimum. <*opt_fx>,
86 * if provided, contains f(x) at that minimum. <*opt_dat>, if
87 * an allocated <ESL_MIN_DAT> was provided, contains a table of
88 * statistics on the run.
89 *
90 * <eslENOHALT> if it fails to converge in max iterations,
91 * but the final <x>, <*opt_fx>, and <*opt_dat> are still provided;
92 * maybe they're good enough, caller can decide.
93 *
94 * Throws: <eslERANGE> if the minimum is not finite, which may
95 * indicate a problem in the implementation or choice of <*func()>.
96 *
97 * <eslEMEM> on allocation failure.
98 * On thrown exceptions, <*opt_fx> is eslINFINITY, and <x> is undefined.
99 *
100 * Xref: STL9/101.
101 */
102 int
103 esl_min_ConjugateGradientDescent(ESL_MIN_CFG *cfg, double *x, int n,
104 double (*func)(double *, int, void *),
105 void (*dfunc)(double *, int, void *, double *),
106 void *prm, double *opt_fx, ESL_MIN_DAT *dat)
107 {
108 int max_iterations = cfg ? cfg->max_iterations : eslMIN_MAXITER;
109 double cg_rtol = cfg ? cfg->cg_rtol : eslMIN_CG_RTOL;
110 double cg_atol = cfg ? cfg->cg_atol : eslMIN_CG_ATOL;
111 double *u = cfg ? cfg->u : NULL; // u[i] = 1.0 if not custom
112 double *wrk = NULL;
113 double oldfx;
114 double coeff;
115 int i, i1;
116 double *dx, *cg, *w1, *w2;
117 double fa,fb,fc;
118 double ax,bx,cx;
119 double fx;
120 int status;
121
122 ESL_ALLOC(wrk, sizeof(double) * 4 * n); // tmp workspace for 4 n-vectors
123 dx = wrk;
124 cg = wrk + n;
125 w1 = wrk + 2*n;
126 w2 = wrk + 3*n;
127
128 oldfx = (*func)(x, n, prm); /* init the objective function */
129 if (dat) { dat->fx[0] = oldfx; dat->nfunc[0] = 1; dat->niter = 0; }
130
131 /* Bail out if the function is +/-inf or nan: this can happen if the caller
132 * has screwed something up, or has chosen a bad start point.
133 */
134 if (! isfinite(oldfx)) ESL_XEXCEPTION(eslERANGE, "minimum not finite");
135
136 if (dfunc)
137 {
138 (*dfunc)(x, n, prm, dx); /* caller knows how to calc the current negative gradient, - df(x)/dxi */
139 esl_vec_DScale(dx, n, -1.0);
140 }
141 else numeric_derivative(cfg, x, n, func, prm, dx, dat); /* else resort to brute force */
142 esl_vec_DCopy(dx, n, cg); /* and make that the first conjugate direction, cg */
143
144
145 /* (failsafe) convergence test: a completely zero direction can happen,
146 * and it either means we're stuck or we're finished (most likely stuck)
147 */
148 for (i1 = 0; i1 < n; i1++)
149 if (cg[i1] != 0.) break;
150 if (i1 == n) {
151 if (opt_fx) *opt_fx = oldfx;
152 free(wrk);
153 return eslOK;
154 }
155
156 for (i = 1; i <= max_iterations; i++)
157 {
158 if (dat) {
159 dat->niter = i; // this is how bracket(), brent(), and numeric_derivative() know what CG iteration they're on
160 dat->nfunc[i] = 0;
161 }
162
163 #if (eslDEBUGLEVEL >= 2) // When debugging, it's useful to compare caller's deriv to numeric_deriv
164 int j;
165 printf("\nCG iteration %d\n", i+1);
166 printf(" current point: ");
167 for (j = 0; j < n; j++) printf("%10.4g ", x[j]);
168 printf("\n gradient: ");
169 for (j = 0; j < n; j++) printf("%10.4g ", dx[j]);
170 numeric_derivative(cfg, x, n, func, prm, w1, dat);
171 printf("\n numeric gradient: ");
172 for (j = 0; j < n; j++) printf("%10.4g ", w1[j]);
173 printf("\n conjugate direction: ");
174 for (j = 0; j < n; j++) printf("%10.4g ", cg[j]);
175 printf("\n");
176 #endif
177
178 /* Figure out the initial step size, <bx>, passed to bracketer. */
179 if (u) bx = fabs(u[0] / cg[0]);
180 else bx = fabs(1. / cg[0]);
181 for (i1 = 1; i1 < n; i1++)
182 {
183 if (u) cx = fabs(u[i1] / cg[i1]);
184 else cx = fabs(1. / cg[i1]);
185 if (cx < bx) bx = cx;
186 }
187
188 /* Bracket the minimum.*/
189 bracket(cfg, x, cg, n, bx, func, prm, w1, &ax, &bx, &cx, &fa, &fb, &fc, dat);
190
191 /* Minimize along the line given by the conjugate gradient <cg> */
192 brent(cfg, x, cg, n, func, prm, ax, cx, w2, NULL, &fx, dat);
193 esl_vec_DCopy(w2, n, x);
194
195 /* Bail out if the function is now +/-inf: this can happen if the caller
196 * has screwed something up.
197 */
198 if (! isfinite(fx)) ESL_XEXCEPTION(eslERANGE, "minimum not finite");
199
200 /* Find the negative gradient at that point (temporarily in w1) */
201 if (dfunc != NULL)
202 {
203 (*dfunc)(x, n, prm, w1);
204 esl_vec_DScale(w1, n, -1.0);
205 }
206 else numeric_derivative(cfg, x, n, func, prm, w1, dat); /* resort to brute force */
207
208 /* Calculate the Polak-Ribiere coefficient */
209 for (coeff = 0., i1 = 0; i1 < n; i1++)
210 coeff += (w1[i1] - dx[i1]) * w1[i1];
211 coeff /= esl_vec_DDot(dx, dx, n);
212
213 /* Calculate the next conjugate gradient direction in w2 */
214 esl_vec_DCopy(w1, n, w2);
215 esl_vec_DAddScaled(w2, cg, coeff, n);
216
217 /* Finishing set up for next iteration: */
218 esl_vec_DCopy(w1, n, dx);
219 esl_vec_DCopy(w2, n, cg);
220
221 /* Now: x is the current point;
222 * fx is the function value at that point;
223 * dx is the current gradient at x;
224 * cg is the current conjugate gradient direction.
225 */
226 if (dat)
227 dat->fx[i] = fx;
228
229 /* Main convergence test. */
230 if (esl_DCompare(fx, oldfx, cg_rtol, cg_atol) == eslOK) break;
231
232 /* Second (failsafe) convergence test: a zero direction can happen,
233 * and it either means we're stuck or we're finished (most likely stuck)
234 */
235 for (i1 = 0; i1 < n; i1++)
236 if (cg[i1] != 0.) break;
237 if (i1 == n) break;
238
239 oldfx = fx;
240 }
241
242 free(wrk);
243 if (opt_fx) *opt_fx = fx;
244 return (i > max_iterations ? eslENOHALT: eslOK);
245
246 ERROR:
247 free(wrk);
248 if (opt_fx) *opt_fx = eslINFINITY;
249 return status;
250 }
251
252
253
254 /*****************************************************************
255 * 2. ESL_MIN_CFG: optional configuration/customization
256 *****************************************************************/
257
258
259 /* Function: esl_min_cfg_Create()
260 * Synopsis: Create customizable configuration for the minimizer
261 * Incept: SRE, Fri 20 Jul 2018 [Benasque]
262 *
263 * Args: n - number of parameters that'll be optimized
264 */
265 ESL_MIN_CFG *
266 esl_min_cfg_Create(int n)
267 {
268 ESL_MIN_CFG *cfg = NULL;
269 int status;
270
271 ESL_ALLOC(cfg, sizeof(ESL_MIN_CFG));
272 cfg->u = NULL;
273 ESL_ALLOC(cfg->u, sizeof(double) * n);
274
275 cfg->max_iterations = eslMIN_MAXITER;
276 cfg->cg_rtol = eslMIN_CG_RTOL;
277 cfg->cg_atol = eslMIN_CG_ATOL;
278 cfg->brent_rtol = eslMIN_BRENT_RTOL;
279 cfg->brent_atol = eslMIN_BRENT_ATOL;
280 cfg->brack_maxiter = eslMIN_BRACK_MAXITER;
281 cfg->deriv_step = eslMIN_DERIV_STEP;
282 cfg->n = n;
283 esl_vec_DSet(cfg->u, n, eslMIN_BRACK_STEP);
284 return cfg;
285
286 ERROR:
287 esl_min_cfg_Destroy(cfg);
288 return NULL;
289 }
290
291 /* Function: esl_min_cfg_Destroy()
292 * Incept: SRE, Fri 20 Jul 2018 [Benasque]
293 */
294 void
295 esl_min_cfg_Destroy(ESL_MIN_CFG *cfg)
296 {
297 if (cfg)
298 {
299 free(cfg->u);
300 free(cfg);
301 }
302 }
303
304 /*****************************************************************
305 * 3. ESL_MIN_DAT, for optional data collection
306 *****************************************************************/
307
308 /* Function: esl_min_dat_Create()
309 * Synopsis: Create an ESL_MIN_DAT for collecting stats from a run
310 * Incept: SRE, Fri 20 Jul 2018
311 *
312 * Purpose: Collects statistics on a CG minimizer run for each
313 * iteration 1..niter, plus the initial position 0.
314 *
315 * Args: cfg : optional custom config, or NULL.
316 */
317 ESL_MIN_DAT *
318 esl_min_dat_Create(ESL_MIN_CFG *cfg)
319 {
320 int max_iterations = cfg ? cfg->max_iterations : eslMIN_MAXITER;
321 ESL_MIN_DAT *dat = NULL;
322 int status;
323
324 ESL_ALLOC(dat, sizeof(ESL_MIN_DAT));
325 dat->fx = NULL;
326 dat->brack_n = NULL;
327 dat->brack_ax = dat->brack_bx = dat->brack_cx = NULL;
328 dat->brack_fa = dat->brack_fb = dat->brack_fc = NULL;
329 dat->brent_n = NULL;
330 dat->brent_x = NULL;
331 dat->nfunc = NULL;
332
333 ESL_ALLOC(dat->fx, sizeof(double) * (max_iterations + 1));
334 ESL_ALLOC(dat->brack_n, sizeof(int) * (max_iterations + 1));
335 ESL_ALLOC(dat->brack_ax, sizeof(double) * (max_iterations + 1));
336 ESL_ALLOC(dat->brack_bx, sizeof(double) * (max_iterations + 1));
337 ESL_ALLOC(dat->brack_cx, sizeof(double) * (max_iterations + 1));
338 ESL_ALLOC(dat->brack_fa, sizeof(double) * (max_iterations + 1));
339 ESL_ALLOC(dat->brack_fb, sizeof(double) * (max_iterations + 1));
340 ESL_ALLOC(dat->brack_fc, sizeof(double) * (max_iterations + 1));
341 ESL_ALLOC(dat->brent_n, sizeof(int) * (max_iterations + 1));
342 ESL_ALLOC(dat->brent_x, sizeof(double) * (max_iterations + 1));
343 ESL_ALLOC(dat->nfunc, sizeof(int) * (max_iterations + 1));
344
345 /* initialize boundary conditions, unused vals at iteration 0 (initial point);
346 * only dat->fx[0], ->nfunc[0] have data
347 */
348 dat->brack_n[0] = 0;
349 dat->brack_ax[0] = dat->brack_bx[0] = dat->brack_cx[0] = 0.;
350 dat->brack_fa[0] = dat->brack_fb[0] = dat->brack_fc[0] = 0.;
351 dat->brent_n[0] = 0;
352 dat->brent_x[0] = 0.;
353
354 return dat;
355
356 ERROR:
357 esl_min_dat_Destroy(dat);
358 return NULL;
359 }
360
361
362 /* Function: esl_min_dat_Destroy()
363 * Synopsis: Free an ESL_MIN_DAT
364 * Incept: SRE, Fri 20 Jul 2018 [Benasque]
365 */
366 void
367 esl_min_dat_Destroy(ESL_MIN_DAT *dat)
368 {
369 if (dat)
370 {
371 free(dat->fx);
372 free(dat->brack_n);
373 free(dat->brack_ax);
374 free(dat->brack_bx);
375 free(dat->brack_cx);
376 free(dat->brack_fa);
377 free(dat->brack_fb);
378 free(dat->brack_fc);
379 free(dat->brent_n);
380 free(dat->brent_x);
381 free(dat->nfunc);
382 free(dat);
383 }
384 }
385
386
387 /* Function: esl_min_dat_Dump()
388 * Synopsis: Dump a table of stats from a minimizer run.
389 * Incept: SRE, Fri 20 Jul 2018 [Benasque]
390 */
391 int
392 esl_min_dat_Dump(FILE *fp, ESL_MIN_DAT *dat)
393 {
394 int iter;
395
396 esl_dataheader(fp, 6, "iter", 16, "fx", 16, "diff",
397 7, "brack_n", 16, "brack_ax", 16, "brack_bx", 16, "brack_cx",
398 16,"brack_fa", 16, "brack_fb", 16, "brack_fc",
399 7, "brent_n", 16, "brent_x", 5, "nfunc",
400 0);
401
402 for (iter = 0; iter <= dat->niter; iter++)
403 {
404 fprintf(fp, "%6d %16g %16g %7d %16g %16g %16g %16g %16g %16g %7d %16g %5d\n",
405 iter,
406 dat->fx[iter],
407 iter > 0 ? dat->fx[iter-1] - dat->fx[iter] : 0.,
408 dat->brack_n[iter],
409 dat->brack_ax[iter], dat->brack_bx[iter], dat->brack_cx[iter],
410 dat->brack_fa[iter], dat->brack_fb[iter], dat->brack_fc[iter],
411 dat->brent_n[iter], dat->brent_x[iter], dat->nfunc[iter]);
412 }
413 return eslOK;
414 }
415
416
417 /*****************************************************************
418 * 4. Internal functions: numeric deriv, bracketing, 1D line min
419 *****************************************************************/
420
421
422 /* Return the negative gradient at a point, determined numerically.
423 */
424 static void
425 numeric_derivative(ESL_MIN_CFG *cfg, double *x, int n,
426 double (*func)(double *, int, void*),
427 void *prm, double *dx, ESL_MIN_DAT *dat)
428 {
429 double relstep = cfg ? cfg->deriv_step : eslMIN_DERIV_STEP;
430 double *u = cfg ? cfg->u : NULL;
431 int i;
432 double delta;
433 double f1, f2;
434 double tmp;
435
436 for (i = 0; i < n; i++)
437 {
438 if (u) delta = fabs(u[i] * relstep);
439 else delta = fabs(relstep);
440
441 tmp = x[i];
442 x[i] = tmp + delta;
443 f1 = (*func)(x, n, prm);
444 x[i] = tmp - delta;
445 f2 = (*func)(x, n, prm);
446 x[i] = tmp;
447
448 dx[i] = (-0.5 * (f1-f2)) / delta;
449
450 if (dat) dat->nfunc[dat->niter] += 2;
451 ESL_DASSERT1((! isnan(dx[i])));
452 }
453 }
454
455 /* bracket():
456 * SRE, Wed Jul 27 11:43:32 2005 [St. Louis]
457 *
458 * Purpose: Bracket a minimum.
459 *
460 * The minimization is quasi-one-dimensional,
461 * starting from an initial <n>-dimension vector <ori>
462 * in the <n>-dimensional direction <d>.
463 *
464 * Caller passes a ptr to the objective function <*func()>,
465 * and a void pointer to any necessary conditional
466 * parameters <prm>. The objective function will
467 * be evaluated at a point <x> by calling
468 * <(*func)(x, n, prm)>. The caller's function
469 * is responsible to casting <prm> to whatever it's
470 * supposed to be, which might be a ptr to a structure,
471 * for example; typically, for a parameter optimization
472 * problem, this holds the observed data.
473 *
474 * The routine works in scalar multipliers relative
475 * to origin <ori> and direction <d>; that is, a new <n>-dimensional
476 * point <b> is defined as <ori> + <bx><d>, for a scalar <bx>.
477 *
478 * The routine identifies a triplet <ax>, <bx>, <cx> such
479 * that $a < b < c$ and such that a minimum is known to
480 * exist in the $(a,b)$ interval because $f(b) < f(a),
481 * f(c)$. Also, the <a..b> and <b...c> intervals are in
482 * a golden ratio; the <b..c> interval is 1.618 times larger
483 * than <a..b>.
484 *
485 * Since <d> is usually in the direction of the gradient,
486 * the points <ax>,<bx>,<cx> might be expected to be $\geq 0$;
487 * however, when <ori> is already close to the minimum,
488 * it is often faster to bracket the minimum using
489 * a negative <ax>. The caller might then try to be "clever"
490 * and assume that the minimum is in the <bx..cx> interval
491 * when <ax> is negative, rather than the full <ax..cx>
492 * interval. That cleverness can fail, though, if <ori>
493 * is already in fact the minimum, because the line minimizer
494 * in brent() assumes a non-inclusive interval. Use
495 * <ax..cx> as the bracket.
496 *
497 * Args: cfg - OPTIONAL configuration of tunable params, or NULL
498 * ori - n-dimensional starting vector
499 * d - n-dimensional direction to minimize along
500 * n - # of dimensions
501 * firststep - bx is initialized to this scalar multiplier
502 * *func() - objective function to minimize
503 * prm - void * to any constant data that *func() needs
504 * wrk - workspace: 1 allocated n-dimensional vector
505 * ret_ax - RETURN: ax < bx < cx scalar bracketing triplet
506 * ret_bx - RETURN: ...ax may be negative
507 * ret_cx - RETURN:
508 * ret_fa - RETURN: function evaluated at a,b,c
509 * ret_fb - RETURN: ... f(b) < f(a),f(c)
510 * ret_fc - RETURN:
511 * opt_dat - optRETURN: stats collection, if caller provided for it
512 *
513 * Returns: <eslOK> on success.
514 *
515 * Throws: <eslENORESULT> if it fails to converge.
516 *
517 * Xref: STL9/130.
518 */
519 static int
520 bracket(ESL_MIN_CFG *cfg, double *ori, double *d, int n, double firststep,
521 double (*func)(double *, int, void *), void *prm,
522 double *wrk,
523 double *ret_ax, double *ret_bx, double *ret_cx,
524 double *ret_fa, double *ret_fb, double *ret_fc, ESL_MIN_DAT *dat)
525 {
526 int max_iterations = cfg ? cfg->brack_maxiter : eslMIN_BRACK_MAXITER;
527 double ax,bx,cx; /* scalar multipliers */
528 double fa,fb,fc; /* f() evaluations at those points */
529 double swapper;
530 int niter;
531
532 /* Set and evaluate our first two points f(a) and f(b), which
533 * are initially at 0.0 and <firststep>.
534 */
535 ax = 0.; /* always start w/ ax at the origin, ax=0 */
536 fa = (*func)(ori, n, prm);
537
538 bx = firststep;
539 esl_vec_DCopy(ori, n, wrk);
540 esl_vec_DAddScaled(wrk, d, bx, n);
541 fb = (*func)(wrk, n, prm);
542
543 /* In principle, we usually know that the minimum m lies to the
544 * right of a, m>=a, because d is likely to be a gradient. You
545 * might think we want 0 = a < b < c. In practice, there's problems
546 * with that. It's far easier to identify bad points (f(x) > f(a))
547 * than to identify good points (f(x) < f(a)), because letting f(x)
548 * blow up to infinity is fine as far as bracketing is concerned.
549 * It can be almost as hard to identify a point b that f(b) < f(a)
550 * as it is to find the minimum in the first place!
551 * Counterintuitively, in cases where f(b)>f(a), it's better
552 * to just swap the a,b labels and look for c on the wrong side
553 * of a! This often works immediately, if f(a) was reasonably
554 * close to the minimum and f(b) and f(c) are both terrible.
555 */
556 if (fb > fa)
557 {
558 swapper = ax; ax = bx; bx = swapper;
559 swapper = fa; fa = fb; fb = swapper;
560 }
561
562 /* Make our first guess at c.
563 * Remember, we don't know that b>a any more, and c might go negative.
564 * We'll either have: a..b...c with a=0;
565 * or: c...b..a with b=0.
566 * In many cases, we'll immediately be done.
567 */
568 cx = bx + (bx-ax)*1.618;
569 esl_vec_DCopy(ori, n, wrk);
570 esl_vec_DAddScaled(wrk, d, cx, n);
571 fc = (*func)(wrk, n, prm);
572
573 /* We're not satisfied until fb < fa, fc;
574 * throughout the routine, we guarantee that fb < fa;
575 * so we just check fc.
576 */
577 niter = 0;
578 while (fc <= fb)
579 {
580 /* Slide over, discarding the a point; choose
581 * new c point even further away.
582 */
583 ax = bx; bx = cx;
584 fa = fb; fb = fc;
585 cx = bx+(bx-ax)*1.618;
586 esl_vec_DCopy(ori, n, wrk);
587 esl_vec_DAddScaled(wrk, d, cx, n);
588 fc = (*func)(wrk, n, prm);
589
590 /* This is a rare instance. We've reach the minimum
591 * by trying to bracket it. Also check that not all
592 * three points are the same.
593 */
594 if (ax != bx && bx != cx && fa == fb && fb == fc) break;
595
596 niter++;
597 if (niter > max_iterations) ESL_EXCEPTION(eslENORESULT, "Failed to bracket a minimum.");
598 }
599
600 /* We're about to return. Assure the caller that the points
601 * are in order a < b < c, not the other way.
602 */
603 if (ax > cx)
604 {
605 swapper = ax; ax = cx; cx = swapper;
606 swapper = fa; fa = fc; fc = swapper;
607 }
608
609 if (dat)
610 {
611 dat->brack_n[dat->niter] = niter;
612 dat->nfunc[dat->niter] += niter + 3;
613 dat->brack_ax[dat->niter] = ax;
614 dat->brack_bx[dat->niter] = bx;
615 dat->brack_cx[dat->niter] = cx;
616 dat->brack_fa[dat->niter] = fa;
617 dat->brack_fb[dat->niter] = fb;
618 dat->brack_fc[dat->niter] = fc;
619 }
620
621 /* Optional verbosity (depending on compile-time eslDEBUGLEVEL) */
622 ESL_DPRINTF2(("bracket(), in %2d iterations, brackets a minimum: a,b,c = %10.4g %10.4g %10.4g\n", niter, ax, bx, cx));
623 ESL_DPRINTF2(("bracket(): fa,fb,fc = %10.4g %10.4g %10.4g\n", fa, fb, fc));
624
625 /* Return. */
626 *ret_ax = ax; *ret_bx = bx; *ret_cx = cx;
627 *ret_fa = fa; *ret_fb = fb; *ret_fc = fc;
628 return eslOK;
629 }
630
631 /* brent():
632 * SRE, Sun Jul 10 19:07:05 2005 [St. Louis]
633 *
634 * Purpose: Quasi-one-dimensional minimization of a function <*func()>
635 * in <n>-dimensions, along vector <dir> starting from a
636 * point <ori>. Identifies a scalar $x$ that approximates
637 * the position of the minimum along this direction, in a
638 * given bracketing interval (<a,b>). The minimum must
639 * have been bracketed by the caller in the <(a,b)>
640 * interval. <a> is often 0, because we often start at the
641 * <ori>.
642 *
643 * A quasi-1D scalar coordinate $x$ (such as <a> or <b>) is
644 * transformed to a point $\mathbf{p}$ in n-space as:
645 * $\mathbf{p} = \mathbf{\mbox{ori}} + x
646 * \mathbf{\mbox{dir}}$.
647 *
648 * Any extra (fixed) data needed to calculate <func> can be
649 * passed through the void <prm> pointer.
650 *
651 * <dat->brent_rtol> and <dat->brent_atol> define the
652 * relative convergence tolerance, $\mbox{rtol} |x| +
653 * atol$. <rtol> should not be less than the square root of
654 * the machine precision. The <DBL_EPSILON> is 2.2e-16 on
655 * many machines with 64-bit doubles, so <rtol> is on the
656 * order of 1e-8 or more. <atol> is a yet smaller number, used
657 * to avoid nonconvergence in the pathological case $x=0$.
658 *
659 * Upon convergence (which is guaranteed), returns <xvec>,
660 * the n-dimensional minimum. Optionally, will also return
661 * <ret_x>, the scalar <x> that resulted in that
662 * n-dimensional minimum, and <ret_fx>, the objective
663 * function <*func(x)> at the minimum.
664 *
665 * This is an implementation of the R.P. Brent (1973)
666 * algorithm for one-dimensional minimization without
667 * derivatives (modified from Brent's ALGOL60 code). Uses a
668 * combination of bisection search and parabolic
669 * interpolation; should exhibit superlinear convergence in
670 * most functions.
671 *
672 *
673 * Args: cfg - OPTIONAL customization of tunable params, or NULL
674 * ori - n-vector at origin
675 * dir - direction vector (gradient) we're following from ori
676 * n - dimensionality of ori, dir, and xvec
677 * (*func) - ptr to caller's objective function
678 * prm - ptr to any additional data (*func)() needs
679 * a,b - minimum is bracketed on interval [a,b]
680 * xvec - RETURN: minimum, as an n-vector (caller allocated)
681 * opt_x - optRETURN: scalar multiplier that gave xvec
682 * opt_fx - optRETURN: f(x)
683 * dat - optRETURN: statistics collection, or NULL
684 *
685 * Returns: (void)
686 *
687 * Reference: See [Brent73], Chapter 5. My version is derived directly
688 * from Brent's description and his ALGOL60 code. I've
689 * preserved his variable names as much as possible, to
690 * make the routine follow his published description
691 * closely. The Brent algorithm is also discussed in
692 * Numerical Recipes [Press88].
693 */
694 static void
695 brent(ESL_MIN_CFG *cfg, double *ori, double *dir, int n,
696 double (*func)(double *, int, void *), void *prm, double a, double b,
697 double *xvec, double *opt_x, double *opt_fx, ESL_MIN_DAT *dat)
698 {
699 double eps = cfg ? cfg->brent_rtol : eslMIN_BRENT_RTOL;
700 double t = cfg ? cfg->brent_atol : eslMIN_BRENT_ATOL;
701 double tol; /* tolerance = eps|x| + t */
702 double w,x,v,u; /* with [a,b]: Brent's six points */
703 double m; /* midpoint of current [a,b] interval */
704 double fu,fv,fw,fx; /* function evaluations */
705 double p,q; /* numerator, denominator of parabolic interpolation */
706 double r;
707 double d,e; /* last, next-to-last values of p/q */
708 double c = 1. - (1./eslCONST_GOLD); /* Brent's c; 0.381966; golden ratio */
709 int niter; /* number of iterations */
710
711 x=v=w= a + c*(b-a); /* initial guess of x by golden section */
712 esl_vec_DCopy(ori, n, xvec); /* build xvec from ori, dir, x */
713 esl_vec_DAddScaled(xvec, dir, x, n);
714 fx=fv=fw = (*func)(xvec, n, prm); /* initial function evaluation */
715
716 d = e = 0.;
717 niter = 0;
718 while (1) /* algorithm is guaranteed to converge. no maxiter needed. */
719 {
720 m = 0.5 * (a+b);
721 tol = eps*fabs(x) + t;
722 if (fabs(x-m) <= 2*tol - 0.5*(b-a)) break; /* convergence test. */
723 niter++;
724
725 p = q = r = 0.;
726 if (fabs(e) > tol)
727 { /* Compute parabolic interpolation, u = x + p/q */
728 r = (x-w)*(fx-fv);
729 q = (x-v)*(fx-fw);
730 p = (x-v)*q - (x-w)*r;
731 q = 2*(q-r);
732 if (q > 0) { p = -p; } else {q = -q;}
733 r = e;
734 e=d; /* e is now the next-to-last p/q */
735 }
736
737 if (fabs(p) < fabs(0.5*q*r) || p < q*(a-x) || p < q*(b-x))
738 { /* Seems well-behaved? Use parabolic interpolation to compute new point u */
739 d = p/q; /* d remembers last p/q */
740 u = x+d; /* trial point, for now... */
741
742 if (2.0*(u-a) < tol || 2.0*(b-u) < tol) /* don't evaluate func too close to a,b */
743 d = (x < m)? tol : -tol;
744 }
745 else /* Badly behaved? Use golden section search to compute u. */
746 {
747 e = (x<m)? b-x : a-x; /* e = largest interval */
748 d = c*e;
749 }
750
751 /* Evaluate f(), but not too close to x. */
752 if (fabs(d) >= tol) u = x+d;
753 else if (d > 0) u = x+tol;
754 else u = x-tol;
755 esl_vec_DCopy(ori, n, xvec); /* build xvec from ori, dir, u */
756 esl_vec_DAddScaled(xvec, dir, u, n);
757 fu = (*func)(xvec, n, prm); /* f(u) */
758
759 /* Bookkeeping. */
760 if (fu <= fx)
761 {
762 if (u < x) b = x; else a = x;
763 v = w; fv = fw; w = x; fw = fx; x = u; fx = fu;
764 }
765 else
766 {
767 if (u < x) a = u; else b = u;
768 if (fu <= fw || w == x)
769 { v = w; fv = fw; w = u; fw = fu; }
770 else if (fu <= fv || v==x || v ==w)
771 { v = u; fv = fu; }
772 }
773 }
774
775 if (dat)
776 {
777 dat->brent_n[dat->niter] = niter;
778 dat->brent_x[dat->niter] = x;
779 dat->nfunc [dat->niter] += niter + 1;
780 }
781
782 /* Optional verbosity, depending on compile-time eslDEBUGLEVEL */
783 ESL_DPRINTF2((" brent(), in %d iterations, finds 1D minimum at %10.4g, f() = %10.4g\n", niter, x, fx));
784
785 /* Return */
786 esl_vec_DCopy(ori, n, xvec); /* build final xvec from ori, dir, x */
787 esl_vec_DAddScaled(xvec, dir, x, n);
788 if (opt_x) *opt_x = x;
789 if (opt_fx) *opt_fx = fx;
790 }
791
792 /*****************************************************************
793 * 5. Unit tests
794 *****************************************************************/
795 #ifdef eslMINIMIZER_TESTDRIVE
796
797 /* f(x) = \sum_i a_i (x_i - b_i)^2
798 * with an analytic minimum at x = b for a_i >= 0
799 */
800 static double
801 test_func(double *x, int n, void *prm)
802 {
803 double *a = (double *) prm;
804 double *b = ((double *) prm) + n;
805 double fx = 0.;
806 int i;
807 for (i = 0; i < n; i++) fx += a[i] * (x[i] - b[i]) * (x[i] - b[i]);
808 return fx;
809 }
810 /* df(x)/dx_i = 2 a_i (x_i - b_i) */
811 static void
812 test_dfunc(double *x, int n, void *prm, double *dx)
813 {
814 double *a = (double *) prm;
815 double *b = ((double *) prm) + n;
816 int i;
817 for (i = 0; i < n; i++)
818 dx[i] = 2. * a[i] * (x[i] - b[i]);
819 }
820
821 static void
822 utest_simplefunc(ESL_RANDOMNESS *rng)
823 {
824 char msg[] = "esl_minimizer simplefunc test failed";
825 int n = 1 + esl_rnd_Roll(rng, 10); // 1..10
826 double *prm = malloc(sizeof(double) * 2 * n);
827 double *a = prm;
828 double *b = prm+n;
829 double *x = malloc(sizeof(double) * n);
830 double fx;
831 int i;
832
833 /* choose fixed params and an initial x[] randomly */
834 for (i = 0; i < n; i++)
835 {
836 a[i] = esl_random(rng) * 10.; // [0,10)
837 b[i] = esl_random(rng) * 20. - 10.; // [-10,10)
838 x[i] = esl_random(rng) * 20. - 10.;
839 }
840
841 esl_min_ConjugateGradientDescent(NULL, x, n, &test_func, &test_dfunc, (void *) prm, &fx, NULL);
842
843 for (i = 0; i < n; i++)
844 if ( esl_DCompare( b[i], x[i], 1e-5, 1e-10) != eslOK) esl_fatal(msg);
845 if (esl_DCompare(0., fx, 0., 1e-5) != eslOK) esl_fatal(msg);
846
847 free(prm);
848 free(x);
849 }
850
851 #endif /*eslMINIMIZER_TESTDRIVE*/
852
853
854 /*****************************************************************
855 * 6. Test driver
856 *****************************************************************/
857 #ifdef eslMINIMIZER_TESTDRIVE
858 #include <esl_config.h>
859
860 #include "easel.h"
861 #include "esl_getopts.h"
862 #include "esl_minimizer.h"
863 #include "esl_random.h"
864
865 static ESL_OPTIONS options[] = {
866 /* name type default env range toggles reqs incomp help docgroup*/
867 { "-h", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show brief help summary", 0 },
868 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number generator seed", 0 },
869 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
870 };
871
872 int
873 main(int argc, char **argv)
874 {
875 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv,
876 "test driver for minimizer",
877 "[-options]");
878 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
879
880 esl_fprintf(stderr, "## %s\n", argv[0]);
881 esl_fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
882
883 utest_simplefunc(rng); // test can stochastically fail - use fixed RNG seed in production code
884
885 esl_fprintf(stderr, "# status = ok\n");
886 esl_getopts_Destroy(go);
887 esl_randomness_Destroy(rng);
888 return 0;
889 }
890 #endif /*eslMINIMIZER_TESTDRIVE*/
891
892
893 /*****************************************************************
894 * 7. Example
895 *****************************************************************/
896 #ifdef eslMINIMIZER_EXAMPLE
897 /*::cexcerpt::minimizer_example::begin::*/
898 /* compile: gcc -g -Wall -I. -o example -DeslMINIMIZER_EXAMPLE esl_minimizer.c esl_vectorops.c easel.c -lm
899 * run: ./example
900 */
901 #include <stdio.h>
902
903 #include "easel.h"
904 #include "esl_vectorops.h"
905 #include "esl_minimizer.h"
906
907 /* a simple multidimensional quadratic w/ a minimum at 0:
908 * $f(x) = a_1 x_1^2 + ... a_n x_n^2$
909 */
910 static double
911 example_func(double *x, int n, void *prm)
912 {
913 double *a;
914 double fx;
915 int i;
916
917 a = (double *) prm; /* cast the data vector */
918 for (fx = 0., i = 0; i < n; i++)
919 fx += a[i] * x[i] * x[i];
920 return fx;
921 }
922 /* gradient of the f(x): d/dx_i = 2 a_i x_i
923 */
924 static void
925 example_dfunc(double *x, int n, void *prm, double *dx)
926 {
927 double *a;
928 int i;
929
930 a = (double *) prm; /* cast the data vector */
931 for (i = 0; i < n; i++)
932 dx[i] = 2.0 * a[i] * x[i];
933 }
934 int
935 main(int argc, char **argv)
936 {
937 ESL_MIN_DAT *dat = esl_min_dat_Create(NULL);
938 int n = 6;
939 double a[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
940 double x[6] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0 };
941 double fx;
942 int i;
943
944 esl_min_ConjugateGradientDescent(NULL, x, n,
945 &example_func, &example_dfunc, (void *) a,
946 &fx, dat);
947
948 printf("At minimum: f(x) = %g\n", fx);
949 printf("vector x = ");
950 for (i = 0; i < 6; i++) printf("%g ", x[i]);
951 printf("\n");
952
953 esl_min_dat_Dump(stdout, dat);
954
955 esl_min_dat_Destroy(dat);
956 return 0;
957 }
958 /*::cexcerpt::minimizer_example::end::*/
959 #endif /*eslMINIMIZER_EXAMPLE*/