roots-multi.lisp 19.1 KB
Newer Older
1 2
;;; Multivariate roots.                
;;; Liam Healy 2008-01-12 12:49:08
Liam Healy's avatar
Liam Healy committed
3
;;; Time-stamp: <2009-02-16 09:56:43EST roots-multi.lisp>
lhealy's avatar
lhealy committed
4
;;; $Id$
5 6 7

(in-package :gsl)

8 9
;;; /usr/include/gsl/gsl_multiroots.h

10 11 12 13 14 15
;;; Currently, functions defined for root solving will be passed
;;; scalars and should return scalars as multiple values.  A possible
;;; future enhancement is to optionally pass marrays and return
;;; marrays instead.  This would allow directly manipulation of
;;; marrays by the user function.  Notes Mon Jan 19 2009.

16 17 18 19
;;;;****************************************************************************
;;;; Initialization
;;;;****************************************************************************

20
(defmobject multi-dimensional-root-solver-f "gsl_multiroot_fsolver"
21
  ((type :pointer) ((first dimensions) sizet))
22 23
  "multi-dimensional root solver with function only"
  :documentation			; FDL
24 25 26 27
  "Make an instance of a solver of the type specified for a system of
   the specified number of dimensions.  Optionally
   set or reset an existing solver to use the function and the
   initial guess gsl-vector."
28
  :initialize-suffix "set"
29
  :initialize-args ((callback :pointer) ((mpointer initial) :pointer))
30 31
  :superclasses (callback-included)
  :ci-class-slots (gsl-mfunction marray (function))
32
  :arglists-function
33
  (lambda (set)
34 35
    `((type &optional function-or-dimension (initial nil ,set))
      (:type type
36 37
	     :dimensions
	     (if ,set (dimensions initial) function-or-dimension))
38
      (:functions (list function-or-dimension) :initial initial)))
39
  :inputs (initial))
40

41 42 43 44 45 46 47 48 49 50 51 52 53
(def-make-callbacks
    multi-dimensional-root-solver-f (function dimension &optional (scalars t))
  (if scalars
      `(defmcallback ,function
	   :success-failure
	 ((:double ,dimension)) ((:set :double ,dimension))
	 T
	 ,function)
      `(defmcallback ,function
	   :success-failure
	 (:pointer) (:pointer)
	 T
	 ,function)))
54

55
(defmobject multi-dimensional-root-solver-fdf "gsl_multiroot_fdfsolver"
56
  ((type :pointer) ((first dimensions) sizet))
57 58
  "multi-dimensional root solver with function and derivative"
  :documentation			; FDL
59 60 61 62
  "Make an instance of a derivative solver of the type specified for
   a system of the specified number of dimensions.  Optionally
   set or reset an existing solver to use the function and derivative
   (fdf) and the initial guess."
63
  :initialize-suffix "set"
64 65 66
  :initialize-args ((callback :pointer) ((mpointer initial) :pointer))
  :superclasses (callback-included)
  :ci-class-slots (gsl-mfunction-fdf marray (function df fdf))
67
  :arglists-function
68
  (lambda (set)
69 70 71 72 73
    `((type &optional function-or-dimension (initial nil ,set))
      (:type type
	     :dimensions
	     (if ,set (dimensions initial) function-or-dimension))
      (:functions function-or-dimension :initial initial)))
74
  :inputs (initial))
75

76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
(def-make-callbacks
    multi-dimensional-root-solver-fdf
    (function df fdf dimension &optional (array t))
  `(progn
     (defmcallback ,function
	 :success-failure
       ((:double ,dimension)) ((:set :double ,dimension))
       ,array
       ,function)
     (defmcallback ,df
	 :success-failure
       ((:double ,dimension)) ((:set :double ,dimension ,dimension))
       ,array
       ,df)
     (defmcallback ,fdf
	 :success-failure
       ((:double ,dimension))
       ((:set :double ,dimension) (:set :double ,dimension ,dimension))
       ,array
       ,fdf)))
96

97
(defmfun name ((solver multi-dimensional-root-solver-f))
98
  "gsl_multiroot_fsolver_name"
99 100
  (((mpointer solver) :pointer))
  :definition :method
101
  :c-return :string
102
  :documentation			; FDL
103 104
  "The name of the solver.")

105
(defmfun name ((solver multi-dimensional-root-solver-fdf))
106
  "gsl_multiroot_fdfsolver_name"
107 108
  (((mpointer solver) :pointer))
  :definition :method
109
  :c-return :string
110
  :documentation			; FDL
111 112 113 114 115 116
  "The name of the solver.")

;;;;****************************************************************************
;;;; Iteration
;;;;****************************************************************************

117
(defmfun iterate ((solver multi-dimensional-root-solver-f))
118
  "gsl_multiroot_fsolver_iterate"
119
  (((mpointer solver) :pointer))
120
  :definition :method
121
  :documentation			; FDL
122 123 124 125 126 127
  "Perform a single iteration of the solver.  The following errors may
   be signalled: 'bad-function-supplied, the iteration encountered a
   singular point where the function or its derivative evaluated to
   infinity or NaN, or 'gsl-division-by-zero, the derivative of the
   function vanished at the iteration point, preventing the algorithm
   from continuing without a division by zero.")
128

129
(defmfun iterate ((solver multi-dimensional-root-solver-fdf))
130
  "gsl_multiroot_fdfsolver_iterate"
131
  (((mpointer solver) :pointer))
132
  :definition :method
133
  :documentation			; FDL
134 135 136 137 138 139
  "Perform a single iteration of the solver.  The following errors may
   be signalled: 'bad-function-supplied, the iteration encountered a
   singular point where the function or its derivative evaluated to
   infinity or NaN, or 'gsl-division-by-zero, the derivative of the
   function vanished at the iteration point, preventing the algorithm
   from continuing without a division by zero.")
140

141
(defmfun solution ((solver multi-dimensional-root-solver-f))
142
  "gsl_multiroot_fsolver_root"
143
  (((mpointer solver) :pointer))
144
  :definition :method
145 146
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
147
  :documentation			; FDL
148 149
  "The current estimate of the root for the solver.")

150
(defmfun solution ((solver multi-dimensional-root-solver-fdf))
151
  "gsl_multiroot_fdfsolver_root"
152
  (((mpointer solver) :pointer))
153
  :definition :method
154 155
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
156 157 158
  :documentation
  "The current estimate of the root for the solver.")

159
(defmfun function-value ((solver multi-dimensional-root-solver-f))
160
  "gsl_multiroot_fsolver_f"
161
  (((mpointer solver) :pointer))
162
  :definition :method
163 164
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
165
  :documentation			; FDL
166 167
  "The function value f(x) at the current estimate x of the root for the solver.")

168
(defmfun function-value ((solver multi-dimensional-root-solver-fdf))
169
  "gsl_multiroot_fdfsolver_f"
170
  (((mpointer solver) :pointer))
171
  :definition :method
172 173
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
174
  :documentation			; FDL
175 176
  "The function value f(x) at the current estimate x of the root for the solver.")

177
(defmfun last-step ((solver multi-dimensional-root-solver-f))
178
  "gsl_multiroot_fsolver_dx"
179
  (((mpointer solver) :pointer))
180
  :definition :method
181 182
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
183
  :documentation			; FDL
184 185
  "The last step dx taken by the solver.")

186
(defmfun last-step ((solver multi-dimensional-root-solver-fdf))
187
  "gsl_multiroot_fsolver_dx"
188
  (((mpointer solver) :pointer))
189
  :definition :method
190 191
  :c-return (crtn :pointer)
  :return ((make-marray 'double-float :from-pointer crtn))
192
  :documentation			; FDL
193 194 195 196 197 198 199
  "The last step dx taken by the solver.")

;;;;****************************************************************************
;;;; Search stopping conditions
;;;;****************************************************************************

;;; The only place we need to pick apart the gsl_multiroot_fsolver
200
;;; struct is here.  We could use last-step etc., but then we'd have
201 202 203 204 205 206 207 208 209 210 211
;;; to discriminate on mfsolver vs. mfdfsolver.
(cffi:defcstruct gsl-multiroot-fsolver
  ;; See /usr/include/gsl/gsl_multiroots.h
  (type :pointer)
  (function :pointer)
  (x :pointer)
  (f :pointer)
  (dx :pointer)
  (state :pointer))

(defun multiroot-slot (solver slot)
212
  (cffi:foreign-slot-value (mpointer solver) 'gsl-multiroot-fsolver slot))
213

liam's avatar
liam committed
214
(defmfun multiroot-test-delta (solver absolute-error relative-error)
215 216 217 218 219
  "gsl_multiroot_test_delta"
  (((multiroot-slot solver 'dx) :pointer)
   ((multiroot-slot solver 'x) :pointer)
   (absolute-error :double) (relative-error :double))
  :c-return :success-continue
220
  :documentation			; FDL
221 222 223 224 225 226 227
  "Test for the convergence of the sequence by comparing the
   last step dx with the absolute error and relative
   errors given to the current position x.  The test returns
   T if the following condition is achieved:
   |dx_i| < epsabs + epsrel |x_i|
   for each component of x and returns NIL otherwise.")

liam's avatar
liam committed
228
(defmfun multiroot-test-residual (solver absolute-error)
229 230 231
  "gsl_multiroot_test_residual"
  (((multiroot-slot solver 'f) :pointer) (absolute-error :double))
  :c-return :success-failure
232
  :documentation			; FDL
233 234 235 236 237 238 239 240 241 242 243 244
  "Test the residual value f against the absolute error,
   returning T if the following condition is achieved:
   \sum_i |f_i| < absolute_error
   and returns NIL otherwise.  This criterion is suitable
   for situations where the precise location of the root x is
   unimportant provided a value can be found where the
   residual is small enough.")

;;;;****************************************************************************
;;;; Algorithms using derivatives
;;;;****************************************************************************

Liam Healy's avatar
Liam Healy committed
245
(defmpar +powells-hybrid+ "gsl_multiroot_fdfsolver_hybridsj"
246
  ;; FDL
247
  "This is a modified version of Powell's Hybrid method as implemented in
liam's avatar
liam committed
248
   the hybrj algorithm in minpack.  Minpack was written by Jorge
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
   J. More, Burton S. Garbow and Kenneth E. Hillstrom.  The Hybrid
   algorithm retains the fast convergence of Newton's method but will also
   reduce the residual when Newton's method is unreliable. 

   The algorithm uses a generalized trust region to keep each step under
   control.  In order to be accepted a proposed new position x' must
   satisfy the condition |D (x' - x)| < \delta, where D is a
   diagonal scaling matrix and \delta is the size of the trust
   region.  The components of D are computed internally, using the
   column norms of the Jacobian to estimate the sensitivity of the residual
   to each component of x.  This improves the behavior of the
   algorithm for badly scaled functions.

   On each iteration the algorithm first determines the standard Newton
   step by solving the system J dx = - f.  If this step falls inside
   the trust region it is used as a trial step in the next stage.  If not,
   the algorithm uses the linear combination of the Newton and gradient
   directions which is predicted to minimize the norm of the function while
   staying inside the trust region,
   dx = - \alpha J^{-1} f(x) - \beta \nabla |f(x)|^2.
   This combination of Newton and gradient directions is referred to as a
   dogleg step.

   The proposed step is now tested by evaluating the function at the
   resulting point, x'.  If the step reduces the norm of the function
   sufficiently then it is accepted and size of the trust region is
   increased.  If the proposed step fails to improve the solution then the
   size of the trust region is decreased and another trial step is
   computed.

   The speed of the algorithm is increased by computing the changes to the
   Jacobian approximately, using a rank-1 update.  If two successive
   attempts fail to reduce the residual then the full Jacobian is
   recomputed.  The algorithm also monitors the progress of the solution
   and returns an error if several steps fail to make any improvement,
284
   'no-progress
285 286
   the iteration is not making any progress, preventing the algorithm from
   continuing.
287
   'jacobian-not-improving
288 289 290
   re-evaluations of the Jacobian indicate that the iteration is not
   making any progress, preventing the algorithm from continuing.")

Liam Healy's avatar
Liam Healy committed
291
(defmpar +powells-hybrid-unscaled+ "gsl_multiroot_fdfsolver_hybridj"
292
  ;; FDL
293 294 295 296 297
  "This algorithm is an unscaled version of *powells-hybrid*.  The steps are
   controlled by a spherical trust region |x' - x| < \delta, instead
   of a generalized region.  This can be useful if the generalized region
   estimated by *powells-hybrid* is inappropriate.")

Liam Healy's avatar
Liam Healy committed
298
(defmpar +newton-mfdfsolver+ "gsl_multiroot_fdfsolver_newton"
299
  ;; FDL
300 301 302 303 304 305 306 307 308 309 310 311
  "Newton's Method is the standard root-polishing algorithm.  The algorithm
   begins with an initial guess for the location of the solution.  On each
   iteration a linear approximation to the function F is used to
   estimate the step which will zero all the components of the residual.
   The iteration is defined by the following sequence,
   x -> x' = x - J{-1} f(x)
   where the Jacobian matrix J is computed from the derivative
   functions provided by f.  The step dx is obtained by solving
   the linear system,
   J dx = - f(x)
   using LU decomposition.")

Liam Healy's avatar
Liam Healy committed
312
(defmpar +gnewton-mfdfsolver+ "gsl_multiroot_fdfsolver_gnewton"
313
  ;; FDL
314 315 316 317 318 319 320 321 322 323 324 325 326
  "A modified version of Newton's method which attempts to improve
   global convergence by requiring every step to reduce the Euclidean norm
   of the residual, |f(x)|.  If the Newton step leads to an increase
   in the norm then a reduced step of relative size,
   t = (\sqrt(1 + 6 r) - 1) / (3 r)
   is proposed, with r being the ratio of norms
   |f(x')|^2/|f(x)|^2.  This procedure is repeated until a suitable step
   size is found.")

;;;;****************************************************************************
;;;; Algorithms without derivatives
;;;;****************************************************************************

Liam Healy's avatar
Liam Healy committed
327
(defmpar +hybrid-scaled+ "gsl_multiroot_fsolver_hybrids"
328 329
  ;; FDL
  "This is a version of the Hybrid algorithm which replaces calls to the
330 331 332 333 334 335
     Jacobian function by its finite difference approximation.  The finite
     difference approximation is computed using gsl_multiroots_fdjac
     with a relative step size of GSL_SQRT_DBL_EPSILON.")
;; Where is this function and parameter?  Only thing that shows in the
;; library is gsl_multiroot_fdjacobian.
 
Liam Healy's avatar
Liam Healy committed
336
(defmpar +hybrid-unscaled+ "gsl_multiroot_fsolver_hybrid"
337
  ;; FDL
338 339 340
  "A finite difference version of the Hybrid algorithm without
   internal scaling.")

Liam Healy's avatar
Liam Healy committed
341
(defmpar +discrete-newton+ "gsl_multiroot_fsolver_dnewton"
342
  ;; FDL
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  "The discrete Newton algorithm is the simplest method of solving a
   multidimensional system.  It uses the Newton iteration
   x -> x - J^{-1} f(x)
   where the Jacobian matrix J is approximated by taking finite
   differences of the function f.  The approximation scheme used by
   this implementation is
   J_{ij} = (f_i(x + \delta_j) - f_i(x)) /  \delta_j
   where \delta_j is a step of size \sqrt\epsilon |x_j| with
   \epsilon being the machine precision 
   (\epsilon \approx 2.22 \times 10^-16}).
   The order of convergence of Newton's algorithm is quadratic, but the
   finite differences require n^2 function evaluations on each
   iteration.  The algorithm may become unstable if the finite differences
   are not a good approximation to the true derivatives.")

Liam Healy's avatar
Liam Healy committed
358
(defmpar +broyden+ "gsl_multiroot_fsolver_broyden"
359
  ;; FDL
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
  "The Broyden algorithm is a version of the discrete Newton
   algorithm which attempts to avoids the expensive update of the Jacobian
   matrix on each iteration.  The changes to the Jacobian are also
   approximated, using a rank-1 update,
   J^{-1} \to J^{-1} - (J^{-1} df - dx) dx^T J^{-1} / dx^T J^{-1} df
   where the vectors dx and df are the changes in x
   and f.  On the first iteration the inverse Jacobian is estimated
   using finite differences, as in the discrete Newton algorithm.
    
   This approximation gives a fast update but is unreliable if the changes
   are not small, and the estimate of the inverse Jacobian becomes worse as
   time passes.  The algorithm has a tendency to become unstable unless it
   starts close to the root.  The Jacobian is refreshed if this instability
   is detected (consult the source for details).

   This algorithm is included only for demonstration purposes, and is not
   recommended for serious use.")

;;;;****************************************************************************
;;;; Examples
;;;;****************************************************************************

(defparameter *powell-A* 1.0d4)
383
(defun powell (arg0 arg1)
384
  "Powell's test function."
385 386 387
  (values
   (- (* *powell-A* arg0 arg1) 1)
   (+ (exp (- arg0)) (exp (- arg1)) (- (1+ (/ *powell-A*))))))
388
;; not used?
389 390 391 392 393 394

;;; This is the example given in Sec. 34.8.

(defparameter *rosenbrock-a* 1.0d0)
(defparameter *rosenbrock-b* 10.0d0)

395
(defun rosenbrock (arg0 arg1)
396
  "Rosenbrock test function."
397 398 399
  (values
   (* *rosenbrock-a* (- 1 arg0))
   (* *rosenbrock-b* (- arg1 (expt arg0 2)))))
400

401 402
(make-callbacks multi-dimensional-root-solver-f rosenbrock 2)

403
(defun roots-multi-example-no-derivative
Liam Healy's avatar
Liam Healy committed
404
    (&optional (method +hybrid-scaled+) (print-steps t))
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
  "Solving Rosenbrock, the example given in Sec. 34.8 of the GSL manual."
  (let ((max-iter 1000)
	(solver (make-multi-dimensional-root-solver-f 
		 method 'rosenbrock #m(-10.0d0 -5.0d0))))
    (loop for iter from 0
       with fnval and argval
       while (and (< iter max-iter)
		  (not (multiroot-test-residual solver 1.0d-7)))
       do
       (iterate solver)
       (setf fnval (function-value solver)
	     argval (solution solver))
       (when print-steps
	 (format t "iter=~d~8tx0=~12,8g~24tx1=~12,8g~38tf0=~12,8g~52tf1=~12,8g~&"
		 iter
		 (maref argval 0)
		 (maref argval 1)
		 (maref fnval 0)
		 (maref fnval 1)))
       finally (return
		 (values (maref argval 0)
			 (maref argval 1)
			 (maref fnval 0)
			 (maref fnval 1))))))

430
(defun rosenbrock-df (arg0 arg1)
431
  "The partial derivatives of the Rosenbrock functions."
432 433 434 435 436 437 438
  (declare (ignore arg1))
  (values (- *rosenbrock-a*)
	  0.0d0
	  (* -2 *rosenbrock-b* arg0)
	  *rosenbrock-b*))

;;; Why is it necessary to define a function that calls the two other functions?
439
(defun rosenbrock-fdf (arg0 arg1)
440 441 442 443 444
  (multiple-value-bind (v0 v1)
      (rosenbrock arg0 arg1)
    (multiple-value-bind (j0 j1 j2 j3)
	(rosenbrock-df arg0 arg1)
      (values v0 v1 j0 j1 j2 j3))))
445

446 447 448
(make-callbacks multi-dimensional-root-solver-fdf
		rosenbrock rosenbrock-df rosenbrock-fdf 2)

449
(defun roots-multi-example-derivative
Liam Healy's avatar
Liam Healy committed
450
    (&optional (method +gnewton-mfdfsolver+) (print-steps t))
451 452 453
  "Solving Rosenbrock with derivatives, the example given in Sec. 34.8
   of the GSL manual."
  (flet ((print-state (iter argval fnval)
454 455 456 457 458 459 460
	   (when print-steps
	     (format t "iter=~d~8tx0=~12,8g~24tx1=~12,8g~38tf0=~12,8g~52tf1=~12,8g~&"
		     iter
		     (maref argval 0)
		     (maref argval 1)
		     (maref fnval 0)
		     (maref fnval 1)))))
461 462
    (let ((max-iter 1000)
	  (solver (make-multi-dimensional-root-solver-fdf
463
		   method
464
		   '(rosenbrock rosenbrock-df rosenbrock-fdf)
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
		   #m(-10.0d0 -5.0d0))))
      (loop for iter from 0
	 with fnval = (function-value solver)
	 and argval = (solution solver)
	 while (and (< iter max-iter)
		    (not (multiroot-test-residual solver 1.0d-7)))
	 initially (print-state iter argval fnval)
	 do
	 (iterate solver)
	 (setf fnval (function-value solver)
	       argval (solution solver))
	 (print-state iter argval fnval)
	 finally (return
		   (values (maref argval 0)
			   (maref argval 1)
			   (maref fnval 0)
			   (maref fnval 1)))))))
482

483 484
;; To see step-by-step information as the solution progresses, make
;; the last argument T.
485
(save-test roots-multi
Liam Healy's avatar
Liam Healy committed
486 487 488 489 490 491 492 493
 (roots-multi-example-no-derivative +hybrid-unscaled+ nil)
 (roots-multi-example-no-derivative +hybrid-scaled+ nil)
 (roots-multi-example-no-derivative +discrete-newton+ nil)
 (roots-multi-example-no-derivative +broyden+ nil)
 (roots-multi-example-derivative +newton-mfdfsolver+ nil)
 (roots-multi-example-derivative +gnewton-mfdfsolver+ nil)
 (roots-multi-example-derivative +powells-hybrid+ nil)
 (roots-multi-example-derivative +powells-hybrid-unscaled+ nil))