Debian Codegraph @

easel/esl_rootfinder.c

raw symbols SCIP
1 /* Finding roots.
2 *
3 * Contents:
4 * 1. The ESL_ROOTFINDER object.
5 * 2. One-dimensional root finding.
6 * 3. Unit tests.
7 * 4. Test driver.
8 * 5. Examples.
9 */
10 #include <esl_config.h>
11
12 #include <math.h>
13
14 #include "easel.h"
15 #include "esl_rootfinder.h"
16
17 /*****************************************************************
18 * 1. The ESL_ROOTFINDER object.
19 *****************************************************************/
20
21 /* Function: esl_rootfinder_Create()
22 * Synopsis: Creates ESL_ROOTFINDER for an $f(x)$
23 * Incept: SRE, Tue Apr 10 19:54:09 2007 [Janelia]
24 *
25 * Purpose: Create a rootfinder to find a root of a function $f(x) = 0$.
26 * <(*func)()> is a pointer to an implementation of the
27 * function $f(x)$. <params> is a generic pointer to any
28 * parameters or storage needed in <(*func)()> other than
29 * the value of $x$.
30 *
31 * Caller implements a <func()> that takes three arguments.
32 * The first two are the value <x>, and a void pointer to
33 * any additional parameters that $f(x)$ depends on. The
34 * result, $f(x)$, is returned via the third argument. This
35 * function must return <eslOK> to indicate success. Upon
36 * error, it may throw any error code it wishes.
37 *
38 *
39 * Args: (*func)() - ptr to function that evaluates f(x)
40 * params - ptr to parameters to be passed to (*func)()
41 *
42 * Returns: pointer to a new <ESL_ROOTFINDER> structure.
43 *
44 * Throws: <NULL> on allocation failure.
45 */
46 ESL_ROOTFINDER *
47 esl_rootfinder_Create(int (*func)(double, void*, double*), void *params)
48 {
49 int status;
50 ESL_ROOTFINDER *R = NULL;
51
52 ESL_ALLOC(R, sizeof(ESL_ROOTFINDER));
53 R->func = func;
54 R->fdf = NULL; /* unused */
55 R->params = params;
56 R->xl = -eslINFINITY; /* not set yet */
57 R->fl = 0.; /* not set yet */
58 R->xr = eslINFINITY; /* not set yet */
59 R->fr = 0.; /* not set yet */
60 R->x0 = 0.; /* not set yet */
61 R->f0 = 0.; /* not set yet */
62 R->x = 0.; /* not set yet */
63 R->fx = 0.; /* not set yet */
64 R->dfx = 0.; /* unused */
65 R->iter = 0;
66 R->abs_tolerance = 1e-12;
67 R->rel_tolerance = 1e-12;
68 R->residual_tol = 0.;
69 R->max_iter = 100;
70 return R;
71
72 ERROR:
73 esl_rootfinder_Destroy(R);
74 return NULL;
75 }
76
77
78 /* Function: esl_rootfinder_CreateFDF()
79 * Synopsis: Creates ESL_ROOTFINDER that uses both $f(x)$, $f'(x)$
80 * Incept: SRE, Tue Apr 10 20:47:42 2007 [Janelia]
81 *
82 * Purpose: Create a rootfinder that will find
83 * a root of a function $f(x) = 0$ using first derivative
84 * information $f'(x)$.
85 *
86 * Caller provides a pointer <*fdf()> to a function that
87 * takes four arguments. The first two are the current <x>
88 * value, and a void pointer to any additional parameters
89 * that $f(x)$ depends on. <*fdf()> calculates the function
90 * $f(x)$ and the derivative $f'(x)$ and returns them
91 * through the remaining two arguments.
92 *
93 * Args: (*fdf)() - ptr to function that returns f(x) and f'(x)
94 * params - ptr to parameters to be passed to (*fdf)()
95 *
96 * Returns: pointer to a new <ESL_ROOTFINDER> structure.
97 *
98 * Throws: <NULL> on allocation failure.
99 */
100 ESL_ROOTFINDER *
101 esl_rootfinder_CreateFDF(int (*fdf)(double, void*, double*, double*), void *params)
102 {
103 int status;
104 ESL_ROOTFINDER *R = NULL;
105
106 ESL_ALLOC(R, sizeof(ESL_ROOTFINDER));
107 R->func = NULL;
108 R->fdf = fdf;
109 R->params = params;
110 R->xl = -eslINFINITY;
111 R->fl = 0.; /* unused */
112 R->xr = eslINFINITY;
113 R->fr = 0.; /* unused */
114 R->x0 = 0.;
115 R->f0 = 0.;
116 R->x = 0.; /* not set yet */
117 R->fx = 0.; /* not set yet */
118 R->dfx = 0.; /* not set yet */
119 R->iter = 0;
120 R->abs_tolerance = 1e-15;
121 R->rel_tolerance = 1e-15;
122 R->residual_tol = 0.;
123 R->max_iter = 100;
124 return R;
125
126 ERROR:
127 esl_rootfinder_Destroy(R);
128 return NULL;
129 }
130
131 /* Function: esl_rootfinder_SetBrackets()
132 * Incept: SRE, Wed Apr 11 08:35:10 2007 [Janelia]
133 *
134 * Purpose: Declare that a root is in the open interval
135 * <(xl..xr)>.
136 *
137 * The function will be evaluated at both points.
138 *
139 * Args: R - rootfinder structure
140 * xl,xr - root lies in open interval (xl..xr)
141 *
142 * Returns: <eslOK> on success.
143 *
144 * Throws: <eslEINVAL> if <xl,xr> cannot bracket a root,
145 * because $f(x_l)$ and $f(x_r)$ do not have opposite
146 * signs.
147 *
148 * Additionally, if either evaluation fails in the
149 * caller-provided function, the error code from that
150 * failure will be thrown.
151 */
152 int
153 esl_rootfinder_SetBrackets(ESL_ROOTFINDER *R, double xl, double xr)
154 {
155 int status;
156 double dfx;
157
158 R->xl = xl;
159 R->xr = xr;
160 if (R->func != NULL) {
161 if ((status = (*R->func)(R->xl, R->params, &(R->fl))) != eslOK) return status;
162 if ((status = (*R->func)(R->xr, R->params, &(R->fr))) != eslOK) return status;
163 } else {
164 if ((status = (*R->fdf) (R->xl, R->params, &(R->fl), &dfx)) != eslOK) return status;
165 if ((status = (*R->fdf) (R->xr, R->params, &(R->fr), &dfx)) != eslOK) return status;
166 }
167 if (R->fl * R->fr >= 0) ESL_EXCEPTION(eslEINVAL, "xl,xr do not bracket a root");
168 return eslOK;
169 }
170
171 int
172 esl_rootfinder_SetAbsoluteTolerance(ESL_ROOTFINDER *R, double tol)
173 {
174 R->abs_tolerance = tol;
175 return eslOK;
176 }
177
178 int
179 esl_rootfinder_SetRelativeTolerance(ESL_ROOTFINDER *R, double tol)
180 {
181 R->rel_tolerance = tol;
182 return eslOK;
183 }
184
185 int
186 esl_rootfinder_SetResidualTolerance(ESL_ROOTFINDER *R, double tol)
187 {
188 R->residual_tol = tol;
189 return eslOK;
190 }
191
192 int
193 esl_rootfinder_SetMaxIterations(ESL_ROOTFINDER *R, int maxiter)
194 {
195 R->max_iter = maxiter;
196 return eslOK;
197 }
198
199
200 void
201 esl_rootfinder_Destroy(ESL_ROOTFINDER *R)
202 {
203 if (R == NULL) return;
204 free(R);
205 }
206
207
208 /*****************************************************************
209 * 2. One-dimensional root finding.
210 *****************************************************************/
211
212 /* Function: esl_root_Bisection()
213 * Synopsis: Find a root of $f(x)$ by bisection method.
214 * Incept: SRE, Wed Apr 11 08:40:11 2007 [Janelia]
215 *
216 * Purpose: Find a root in the open interval <xl..xr> by the bisection method,
217 * and return it in <ret_x>.
218 *
219 * The bisection method is guaranteed to succeed, provided
220 * that <xl>,<xr> do indeed bracket a root, though it may
221 * be slow.
222 *
223 * The rootfinder <R> can be created either by
224 * <esl_rootfinder_Create()> or
225 * <esl_rootfinder_CreateFDF()>; if the latter (if the
226 * function in the rootfinder <R> includes derivative
227 * information), the bisection method will just ignore
228 * the derivative.
229 *
230 * Args: R - a rootfinder object for the function
231 * xl,xr - bounds of an open interval in which a root lies
232 * ret_x - RETURN: a root that satisfies $f(x) = 0$.
233 *
234 * Returns: <eslOK> on success, and <ret_x> points to a root.
235 *
236 * Throws: <eslEINVAL> if <xl,xr> do not bracket a root.
237 * <eslENOHALT> if the method exceeds the maximum number of
238 * iterations set in <R>.
239 *
240 * Additionally, any failure code that the caller-provided
241 * function $f(x)$ throws.
242 */
243 int
244 esl_root_Bisection(ESL_ROOTFINDER *R, double xl, double xr, double *ret_x)
245 {
246 int status;
247 double xmag;
248
249 if ((status = esl_rootfinder_SetBrackets(R, xl, xr)) != eslOK) goto ERROR;
250
251 while (1) {
252 R->iter++;
253 if (R->iter > R->max_iter) ESL_XEXCEPTION(eslENOHALT, "failed to converge in Bisection");
254
255 /* Bisect and evaluate the function */
256 R->x = (R->xl+R->xr)/2.;
257 if (R->func != NULL) {
258 if ((status = (*R->func)(R->x, R->params, &(R->fx))) != eslOK) ESL_XEXCEPTION(status, "user-provided function failed");
259 } else {
260 if ((status = (*R->fdf) (R->x, R->params, &(R->fx), &(R->dfx))) != eslOK) ESL_XEXCEPTION(status, "user-provided function failed");
261 }
262
263 /* Test for convergence */
264 xmag = (R->xl < 0. && R->xr > 0.) ? 0. : R->x;
265 if (R->fx == 0.) break; /* an exact root, lucky */
266 if (((R->xr-R->xl) < R->abs_tolerance + R->rel_tolerance*xmag) || fabs(R->fx) < R->residual_tol) break;
267
268 /* Narrow the bracket; pay attention to directionality */
269 if (R->fl > 0.) {
270 if (R->fx > 0.) { R->xl = R->x; R->fl = R->fx; }
271 else { R->xr = R->x; R->fr = R->fx; }
272 } else {
273 if (R->fx < 0.) { R->xl = R->x; R->fl = R->fx; }
274 else { R->xr = R->x; R->fr = R->fx; }
275 }
276 }
277
278 *ret_x = R->x;
279 return eslOK;
280
281 ERROR:
282 *ret_x = 0.0;
283 return status;
284 }
285
286
287 /* Function: esl_root_NewtonRaphson()
288 * Synopsis: Find a root of $f(x)$ by Newton/Raphson method.
289 * Incept: SRE, Wed Apr 11 08:56:28 2007 [Janelia]
290 *
291 * Purpose: Find a root by the Newton/Raphson method, starting from
292 * an initial guess <guess>. Return the root in <ret_x>.
293 *
294 * The Newton/Raphson method is not guaranteed to succeed,
295 * but when it does, it is much faster than bisection.
296 *
297 * Newton/Raphson uses first derivative information, so the
298 * rootfinder <R> must be created with
299 * <esl_rootfinder_CreateFDF()> for a function that evaluates
300 * both $f(x)$ and $f'(x)$.
301 *
302 * Args: R - a rootfinder object for $f(x)$ and $f'(x)$
303 * guess - an initial guess for the root
304 * ret_x - RETURN: a root that satisfies $f(x) = 0$.
305 *
306 * Returns: <eslOK> on success, and <ret_x> points to a root.
307 *
308 * Throws: <eslENOHALT> if the method exceeds the maximum number of
309 * iterations set in <R>.
310 *
311 * Additionally, any failure code that the caller-provided
312 * function $f(x)$ throws.
313 */
314 int
315 esl_root_NewtonRaphson(ESL_ROOTFINDER *R, double guess, double *ret_x)
316 {
317 int status;
318
319 R->x = guess;
320 if ((status = (*R->fdf)(R->x, R->params, &(R->fx), &(R->dfx))) != eslOK) return status;
321
322 while (1) {
323 R->iter++;
324 if (R->iter > R->max_iter) ESL_EXCEPTION(eslENOHALT, "failed to converge in Newton");
325
326 /* printf("current: x=%20g f(x) = %20g f'(x) = %20g\n", R->x, R->fx, R->dfx); */
327
328 /* Take a Newton/Raphson step. */
329 R->x0 = R->x;
330 R->f0 = R->fx;
331 R->x = R->x - R->fx / R->dfx;
332 (*R->fdf)(R->x, R->params, &(R->fx), &(R->dfx));
333
334 /* Test for convergence. */
335 if (R->fx == 0) break; /* an exact root, lucky */
336 if ( (fabs(R->x - R->x0) < R->abs_tolerance + R->rel_tolerance*R->x) || fabs(R->fx) < R->residual_tol) break;
337 }
338
339 *ret_x = R->x;
340 return eslOK;
341 }
342
343
344
345
346 /*****************************************************************
347 * 3. Unit tests.
348 *****************************************************************/
349 #ifdef eslROOTFINDER_TESTDRIVE
350 /* For the unit tests, we'll use a quadratic function
351 * f(x) = ax^2 + bx + c = 0
352 * f'(x) = 2ax + b
353 * where it's easy to set up known roots.
354 */
355 struct polyparams { double a,b,c; };
356
357 static int quadratic_f(double x, void *params, double *ret_fx)
358 {
359 struct polyparams *p = (struct polyparams *) params;
360 *ret_fx = (p->a * x * x + p->b * x + p->c);
361 return eslOK;
362 }
363
364 static int quadratic_fdf(double x, void *params, double *ret_fx, double *ret_dfx)
365 {
366 struct polyparams *p = (struct polyparams *) params;
367
368 *ret_fx = (p->a * x * x + p->b * x + p->c);
369 *ret_dfx = (2 * p->a) * x + p->b;
370 return eslOK;
371 }
372
373 static void
374 utest_Bisection(void)
375 {
376 char msg[] = "esl_rootfinder:: bisection unit test failed";
377 ESL_ROOTFINDER *R = NULL;
378 struct polyparams p;
379 double x;
380
381 /* (5x-1)(x+2) = 5x^2 + 9x - 2 with roots 0.2, -2 */
382 p.a = 5.;
383 p.b = 9.;
384 p.c = -2.;
385
386 /* find the positive root, 0.2 */
387 if (( R = esl_rootfinder_Create(quadratic_f, &p) ) == NULL) esl_fatal(msg);
388 if ( esl_root_Bisection(R, 0., 100., &x) != eslOK) esl_fatal(msg);
389 if ( fabs(x-0.2) > R->abs_tolerance) esl_fatal(msg);
390 esl_rootfinder_Destroy(R);
391
392 /* find the negative root, -2.0 */
393 if (( R = esl_rootfinder_CreateFDF(quadratic_fdf, &p) ) == NULL) esl_fatal(msg);
394 if ( esl_root_Bisection(R, -100., 0., &x) != eslOK) esl_fatal(msg);
395 if ( fabs(x+2.) > R->abs_tolerance) esl_fatal(msg);
396 esl_rootfinder_Destroy(R);
397 }
398
399
400 static void
401 utest_Newton(void)
402 {
403 ESL_ROOTFINDER *R = NULL;
404 struct polyparams p;
405 double x;
406
407 /* (5x-1)(x+2) = 5x^2 + 9x - 2 with roots 0.2, -2 */
408 p.a = 5.;
409 p.b = 9.;
410 p.c = -2.;
411
412 R = esl_rootfinder_CreateFDF(quadratic_fdf, &p);
413 esl_root_NewtonRaphson(R, 1., &x); /* find the positive root, 0.2 */
414 if (fabs(x-0.2) > R->abs_tolerance) esl_fatal("didn't find root 0.2");
415 esl_rootfinder_Destroy(R);
416
417 R = esl_rootfinder_CreateFDF(quadratic_fdf, &p);
418 esl_root_NewtonRaphson(R, -3., &x); /* find the negative root, -2.0 */
419 if (fabs(x+2.) > R->abs_tolerance) esl_fatal("didn't find root -2");
420 esl_rootfinder_Destroy(R);
421 }
422
423 #endif /*eslROOTFINDER_TESTDRIVE*/
424
425
426 /*****************************************************************
427 * 4. Test driver.
428 *****************************************************************/
429 /*
430 gcc -g -Wall -I. -L. -DeslROOTFINDER_TESTDRIVE -o test esl_rootfinder.c -leasel -lm
431 ./test
432 */
433 #ifdef eslROOTFINDER_TESTDRIVE
434
435 int
436 main(int argc, char **argv)
437 {
438 utest_Bisection();
439 utest_Newton();
440
441 return eslOK;
442 }
443
444 #endif /*eslROOTFINDER_TESTDRIVE*/
445
446 /*****************************************************************
447 * 5. Examples.
448 *****************************************************************/
449
450 /* An example of bisection.
451 * gcc -g -Wall -o example -I. -DeslROOTFINDER_EXAMPLE esl_rootfinder.c easel.c -lm
452 */
453 #ifdef eslROOTFINDER_EXAMPLE
454 /*::cexcerpt::rootfinder_example::begin::*/
455 #include "easel.h"
456 #include "esl_rootfinder.h"
457
458 struct polyparams { double a,b,c; };
459
460 int quadratic_f(double x, void *params, double *ret_fx)
461 {
462 struct polyparams *p = (struct polyparams *) params;
463 *ret_fx = (p->a * x * x + p->b * x + p->c);
464 return eslOK;
465 }
466
467 int main(void)
468 {
469 ESL_ROOTFINDER *R = NULL;
470 struct polyparams p;
471 double x, fx;
472
473 p.a = 5.;
474 p.b = 2.;
475 p.c = -1.;
476
477 R = esl_rootfinder_Create(quadratic_f, &p);
478 esl_root_Bisection(R, 0., 100., &x);
479
480 quadratic_f(x, &p, &fx);
481 printf("Find an x such that f(x) = %.0fx^2 + %.0fx + %.0f = 0 ...\n", p.a, p.b, p.c);
482 printf("x = %f (f(x) = %f)\n", x, fx);
483
484 esl_rootfinder_Destroy(R);
485 return 0;
486 }
487 /*::cexcerpt::rootfinder_example::end::*/
488 #endif /*eslROOTFINDER_EXAMPLE*/
489
490
491 /* An example of Newton/Raphson.
492 * gcc -g -Wall -o example -I. -DeslROOTFINDER_EXAMPLE2 esl_rootfinder.c easel.c -lm
493 */
494 #ifdef eslROOTFINDER_EXAMPLE2
495 /*::cexcerpt::rootfinder_example2::begin::*/
496 #include "easel.h"
497 #include "esl_rootfinder.h"
498
499 struct polyparams { double a,b,c; };
500
501 int quadratic_fdf(double x, void *params, double *ret_fx, double *ret_dfx)
502 {
503 struct polyparams *p = (struct polyparams *) params;
504
505 *ret_fx = (p->a * x * x + p->b * x + p->c);
506 *ret_dfx = (2 * p->a) * x + p->b;
507 return eslOK;
508 }
509
510 int main(void)
511 {
512 ESL_ROOTFINDER *R = NULL;
513 struct polyparams p;
514 double x;
515
516 p.a = 5.;
517 p.b = 2.;
518 p.c = -1.;
519
520 R = esl_rootfinder_CreateFDF(quadratic_fdf, &p);
521 esl_root_NewtonRaphson(R, -1., &x);
522
523 printf("Find an x such that f(x) = %.0fx^2 + %.0fx + %.0f = 0 ...\n", p.a, p.b, p.c);
524 printf("x = %f\n", x);
525
526 esl_rootfinder_Destroy(R);
527 return 0;
528 }
529 /*::cexcerpt::rootfinder_example2::end::*/
530 #endif /*eslROOTFINDER_EXAMPLE2*/
531