example (works) of setting dfref
[CommonLispStat.git] / src / numerics / optimize.lisp
blobdafc420a7d4feebb8ad10d373b4ad608cbfa16f0
1 ;;; -*- mode: lisp -*-
2 ;;; Copyright (c) 2005--2007, by A.J. Rossini <blindglobe@gmail.com>
3 ;;; See COPYRIGHT file for any additional restrictions (BSD license).
4 ;;; Since 1991, ANSI was finally finished. Edited for ANSI Common Lisp.
7 ;; matrix is in statistics, but should that be a predecessor?
9 ;;; FIXME:AJR: There is a need to figure out the proper symbols to
10 ;;; export. more importantly should there be any specialty package
11 ;;; that are exported for maximization?
13 (in-package :lisp-stat-optimize)
15 #+openmcl
16 (defctype size-t :unsigned-long)
17 #+sbcl
18 (defctype size-t :unsigned-int)
20 (defvar *maximize-callback-function* nil
21 "Used in generic optimization to determine function name -- symbol or string?")
23 (defvar *maximize-callback-arg* nil
24 "args to function to maximize")
27 ;;;
28 ;;; CFFI support using library for optimization work.
29 ;;;
31 ;; There is a problem with this particular approach, in terms of
32 ;; circular dependencies. We can not have this out-of-object call
33 ;; into optimize, at least not from here.
34 (cffi:defcallback ccl-maximize-callback :void ((n :int)
35 (px :pointer)
36 (pfval :pointer)
37 (pgrad :pointer)
38 (phess :pointer)
39 (pderivs :pointer))
40 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs))
42 (cffi:defcfun ("register_maximize_callback" register-maximize-callback)
43 :void (x :pointer))
44 (register-maximize-callback (cffi:callback ccl-maximize-callback))
46 (cffi:defcfun ("ccl_numgrad_front" ccl-numgrad-front)
47 :void (x size-t) (y :pointer) (z :pointer) (u :double) (v :pointer))
48 (defun numgrad-front (x y z u v)
49 (ccl-numgrad-front x y z (float u 1d0) v))
51 (cffi:defcfun ("ccl_numhess_front" ccl-numhess-front)
52 :void (x size-t) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :double) (a :pointer))
53 (defun numhess-front (x y z u v w a)
54 (ccl-numhess-front x y z u v (float w 1d0) a))
56 (cffi:defcfun ("ccl_minfo_maximize" ccl-minfo-maximize)
57 :void (x :pointer) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :int))
58 (defun base-minfo-maximize (x y z u v w)
59 (ccl-minfo-maximize x y z u v w))
63 ;;;;
64 ;;;; minfo basics (internal??)
65 ;;;;
67 (defun init-minfo-ipar-values (n ipars &key
68 (TRUE 1)
69 (FALSE 0)
70 (k 0)
71 (m 0)
72 (itnlimit -1)
73 (backtrack TRUE)
74 (verbose 0)
75 (vals_suppl FALSE)
76 (exptilt TRUE)
77 (count 0)
78 (termcode 0))
79 "Initialize ipars (iteration parameters) by destructive modification."
80 (setf (aref ipars 0) n)
81 (setf (aref ipars 1) m)
82 (setf (aref ipars 2) k)
83 (setf (aref ipars 3) itnlimit)
84 (setf (aref ipars 4) backtrack)
85 (setf (aref ipars 5) verbose)
86 (setf (aref ipars 6) vals_suppl)
87 (setf (aref ipars 7) exptilt)
88 (setf (aref ipars 8) count)
89 (setf (aref ipars 9) termcode))
91 (defun init-minfo-dpar-values (h dpars &key
92 (typf 1.0)
93 (gradtol -1.0)
94 (steptol -1.0)
95 (maxstep -1.0)
96 (dflt 0.0)
97 (tilt 0.0)
98 (newtilt 0.0)
99 (hessadd 0.0))
100 "Initialize dpars (derivative parameters) by destructive modification."
101 (setf (aref dpars 0) typf)
102 (setf (aref dpars 1) h)
103 (setf (aref dpars 2) gradtol)
104 (setf (aref dpars 3) steptol)
105 (setf (aref dpars 4) maxstep)
106 (setf (aref dpars 5) dflt)
107 (setf (aref dpars 6) tilt)
108 (setf (aref dpars 7) newtilt)
109 (setf (aref dpars 8) hessadd))
111 (defun init-minfo-internals (n h internals)
112 (let ((ipars (aref internals 8))
113 (dpars (aref internals 9)))
114 (init-minfo-ipar-values n ipars)
115 (init-minfo-dpar-values h dpars)))
117 (defun new-minfo-internals (f x &key scale ((:derivstep h) -1.0))
118 (check-sequence x)
119 (check-real x)
120 (check-one-real h)
121 (let ((n (length x)))
122 (when scale
123 (check-sequence scale)
124 (check-real scale)
125 (if (/= n (length scale)) (error "scale and x not the same length")))
126 (let ((internals (make-array 12)))
127 (setf (aref internals 0) f)
128 (setf (aref internals 3) (if (consp x) (copy-list x) (coerce x 'list)))
129 (setf (aref internals 4)
130 (if scale (copy-seq scale) (make-array n :initial-element 1.0)))
131 (setf (aref internals 5) (make-list (+ 1 n (* n n))))
132 (setf (aref internals 8) (make-array 10))
133 (setf (aref internals 9) (make-array 9))
134 (init-minfo-internals n h internals)
135 internals)))
137 (defun minfo-maximize (internals &optional verbose)
138 "This function does what?"
139 (let* ((f (aref internals 0))
140 (x (aref internals 3))
141 (fvals (aref internals 5))
142 (n (length x))
143 (v (if verbose (if (integerp verbose) verbose 1) -1)))
144 (setf (aref internals 3) (copy-list x))
145 (setf (aref internals 5) (copy-list fvals))
146 (let ((*maximize-callback-function* f)
147 (*maximize-callback-arg* (make-list n)))
148 (let* ((x (aref internals 3))
149 (scale (aref internals 4))
150 (fvals (aref internals 5))
151 (ip (aref internals 8))
152 (dp (aref internals 9))
153 (px (la-data-to-vector x +mode-re+))
154 (pscale (la-data-to-vector scale +mode-re+))
155 (pfvals (la-vector (length fvals) +mode-re+))
156 (pip (la-data-to-vector ip +mode-in+))
157 (pdp (la-data-to-vector dp +mode-re+)))
158 (unwind-protect
159 (progn
160 (base-minfo-maximize px pfvals pscale pip pdp v)) ;; access to C
161 (la-vector-to-data px n +mode-re+ x)
162 (la-vector-to-data pfvals (+ 1 n (* n n)) +mode-re+ fvals)
163 (la-vector-to-data pip (length ip) +mode-in+ ip)
164 (la-vector-to-data pdp (length dp) +mode-re+ dp))
165 (get-buf)))))
169 ;;;;
170 ;;;; Mode Info Prototype
171 ;;;;
173 (defvar minfo-proto)
174 (defproto minfo-proto '(internals))
176 #+xlisp (send minfo-proto :add-method :isnew #'|minfo-isnew|)
177 #+xlisp (send minfo-proto :add-method :maximize #'|minfo-maximize|)
178 #+xlisp (send minfo-proto :add-method :loglaplace #'|minfo-loglap|)
179 #-xlisp
180 (defmeth minfo-proto :isnew (&rest args)
181 (setf (slot-value 'internals) (apply #'new-minfo-internals args)))
182 #-xlisp
183 (defmeth minfo-proto :maximize (&rest args)
184 (apply #'minfo-maximize (slot-value 'internals) args))
186 (defmeth minfo-proto :x () (aref (slot-value 'internals) 3))
187 (defmeth minfo-proto :scale () (aref (slot-value 'internals) 4))
188 (defmeth minfo-proto :derivstep () (aref (aref (slot-value 'internals) 9) 1))
189 (defmeth minfo-proto :tilt () (aref (aref (slot-value 'internals) 9) 6))
191 (defmeth minfo-proto :f (&optional (val nil set))
192 (when set
193 (send self :set-no-vals-supplied)
194 (setf (aref (slot-value 'internals) 0) val))
195 (aref (slot-value 'internals) 0))
197 (defmeth minfo-proto :set-no-vals-supplied ()
198 (setf (aref (aref (slot-value 'internals) 8) 6) 0))
200 (defmeth minfo-proto :exptilt (&optional (val nil set))
201 (if set
202 (let ((old (send self :exptilt)))
203 (setf (aref (aref (slot-value 'internals) 8) 7) (if val 1 0))
204 (if (and (not (or (and old val) (and (not old) (not val))))
205 (/= (send self :tilt) 0.0))
206 (send self :set-no-vals-supplied))))
207 (= 1 (aref (aref (slot-value 'internals) 8) 7)))
209 (defmeth minfo-proto :newtilt (&optional (val nil set))
210 (when set
211 (setf (aref (aref (slot-value 'internals) 9) 7) (float val))
212 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
213 (aref (aref (slot-value 'internals) 9) 7))
215 (defmeth minfo-proto :gfuns (&optional (val nil set))
216 (when set
217 (if (or (not (consp val))
218 (not (every #'functionp val)))
219 (error "not all functions"))
220 (setf (aref (slot-value 'internals) 1) val)
221 (setf (aref (aref (slot-value 'internals) 8) 1) (length val))
222 (setf (aref (slot-value 'internals) 10) (repeat 1.0 (length val)))
223 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
224 (aref (slot-value 'internals) 1))
226 (defmeth minfo-proto :cfuns (&optional (val nil set))
227 (when set
228 (if (or (not (consp val))
229 (not (every #'functionp val)))
230 (error "not all functions"))
231 (setf (aref (slot-value 'internals) 2) val)
232 (setf (aref (aref (slot-value 'internals) 8) 2) (length val))
233 (setf (aref (slot-value 'internals) 7) (repeat 0.0 (length val)))
234 (setf (aref (slot-value 'internals) 11) (repeat 0.0 (length val)))
235 (send self :set-no-vals-supplied))
236 (aref (slot-value 'internals) 2))
238 (defmeth minfo-proto :ctarget (&optional (val nil set))
239 (when set
240 (if (/= (length val) (length (send self :ctarget)))
241 (error "bad target length"))
242 (setf (aref (slot-value 'internals) 7) val))
243 (aref (slot-value 'internals) 7))
245 (defmeth minfo-proto :fvals ()
246 (let* ((fv (aref (slot-value 'internals) 5))
247 (n (length (send self :x)))
248 (val (select fv 0))
249 (grad (select fv (iseq 1 n)))
250 (hess (matrix (list n n) (select fv (iseq (+ 1 n) (+ n (* n n)))))))
251 (list val grad hess)))
253 (defmeth minfo-proto :copy ()
254 "Method: ()
256 Make a copy of an minfo instance."
257 (let ((obj (make-object minfo-proto))
258 (internals (copy-seq (slot-value 'internals))))
259 (dotimes (i (length internals))
260 (let ((x (aref internals i)))
261 (if (typep x 'sequence)
262 (setf (aref internals i) (copy-seq x)))))
263 (send obj :add-slot 'internals internals)
264 obj))
266 (defmeth minfo-proto :derivscale ()
267 (let* ((step (^ machine-epsilon (/ 1 6)))
268 (hess (numhess (send self :f) (send self :x) (send self :scale) step))
269 (scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess)))))))
270 (setf hess (numhess (send self :f) (send self :x) scale step))
271 (setf scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess))))))
272 (setf (aref (slot-value 'internals) 4) scale)
273 (setf (aref (aref (slot-value 'internals) 9) 1) step)))
275 (defmeth minfo-proto :verbose (&optional (val nil set))
276 (when set
277 (setf (aref (aref (slot-value 'internals) 8) 5)
278 (cond ((integerp val) val)
279 ((null val) 0)
280 (t 1))))
281 (aref (aref (slot-value 'internals) 8) 5))
283 (defmeth minfo-proto :backtrack (&optional (val nil set))
284 (if set (setf (aref (aref (slot-value 'internals) 8) 4) (if val 1 0)))
285 (aref (aref (slot-value 'internals) 8) 4))
287 (defmeth minfo-proto :maxiter (&optional (val nil set))
288 (if set (setf (aref (aref (slot-value 'internals) 8) 3)
289 (if (integerp val) val -1)))
290 (aref (aref (slot-value 'internals) 8) 3))
292 (defmeth minfo-proto :tiltscale (&optional (val nil set))
293 (when set
294 (if (/= (length val) (length (send self :gfuns)))
295 (error "wrong size tilt scale sequence"))
296 (setf (aref (slot-value 'internals) 10) val))
297 (aref (slot-value 'internals) 10))
299 ;;;;
300 ;;;;
301 ;;;; Newton's Method with Backtracking
302 ;;;;
303 ;;;;
305 (defun newtonmax (f start &key
306 scale
307 (derivstep -1.0)
308 (count-limit -1)
309 (verbose 1)
310 return-derivs)
311 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
312 Maximizes F starting from START using Newton's method with backtracking.
313 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
314 list of location, unction value, gradient and hessian at maximum.
315 SCALE should be a list of the typical magnitudes of the parameters.
316 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
317 of iteration information. COUNT-LIMIT limits the number of iterations"
318 (let ((verbose (if verbose (if (integerp verbose) verbose 1) 0))
319 (minfo (send minfo-proto :new f start
320 :scale scale :derivstep derivstep)))
321 (send minfo :maxiter count-limit)
322 (send minfo :derivscale)
323 (send minfo :maximize verbose)
324 (if return-derivs
325 (cons (send minfo :x) (- (send minfo :fvals)))
326 (send minfo :x))))
329 ;;; Nelder-Mead Simplex Method
332 ;;; Simplex Prototype
334 (defvar simplex-proto)
335 (defproto simplex-proto '(f simplex))
337 (defun nelmeadmax (f start &key
338 (size 1)
339 (epsilon (sqrt machine-epsilon))
340 (count-limit 500)
341 (verbose t)
342 (alpha 1.0)
343 (beta 0.5)
344 (gamma 2.0)
345 (delta 0.5))
346 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
347 (count-limit 500) (verbose t) alpha beta gamma delta)
348 Maximizes F using the Nelder-Mead simplex method. START can be a
349 starting simplex - a list of N+1 points, with N=dimension of problem,
350 or a single point. If start is a single point you should give the
351 size of the initial simplex as SIZE, a sequence of length N. Default is
352 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
353 control the behavior of simplex algorithm."
354 (let ((s (send simplex-proto :new f start size)))
355 (do ((best (send s :best-point) (send s :best-point))
356 (count 0 (+ count 1))
357 next)
358 ((or (< (send s :relative-range) epsilon) (>= count count-limit))
359 (if (and verbose (>= count count-limit))
360 (format t "Iteration limit exceeded.~%"))
361 (send s :point-location (send s :best-point)))
362 (setf next (send s :extrapolate-from-worst (- alpha)))
363 (if (send s :is-worse best next)
364 (setf next (send s :extrapolate-from-worst gamma))
365 (when (send s :is-worse next (send s :second-worst-point))
366 (setf next (send s :extrapolate-from-worst beta))
367 (if (send s :is-worse next (send s :worst-point))
368 (send s :shrink-to-best delta))))
369 (if verbose
370 (format t "Value = ~10g~%"
371 (send s :point-value (send s :best-point)))))))
376 ;;; Simplex Points
379 (defmeth simplex-proto :make-point (x)
380 (let ((f (send self :f)))
381 (if f
382 (let ((val (funcall f x)))
383 (cons (if (consp val) (car val) val) x))
384 (cons nil x))))
386 (defmeth simplex-proto :point-value (x) (car x))
388 (defmeth simplex-proto :point-location (x) (cdr x))
390 (defmeth simplex-proto :is-worse (x y)
391 (< (send self :point-value x) (send self :point-value y)))
394 ;;; Making New Simplices
397 (defmeth simplex-proto :isnew (f start &optional size)
398 (send self :simplex start size)
399 (send self :f f))
402 ;;; Slot Accessors and Mutators
405 (defmeth simplex-proto :simplex (&optional new size)
406 (if new
407 (let ((simplex
408 (if (and (consp new) (typep (car new) 'sequence))
409 (if (/= (length new) (+ 1 (length (car new))))
410 (error "bad simplex data")
411 (copy-list new))
412 (let* ((n (length new))
413 (size (if size size (repeat 1 n)))
414 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
415 (diag (* 2 size (- (random (repeat 2 n)) .5)))
416 (pts (cons (repeat 0 n)
417 (mapcar #'(lambda (x) (coerce x 'list))
418 (column-list (diagonal diag))))))
419 (mapcar #'(lambda (x) (reduce #'+ (list (* size x) new))) pts)))))
420 (setf (slot-value 'simplex)
421 (mapcar #'(lambda (x) (send self :make-point x)) simplex))
422 (send self :sort-simplex)))
423 (slot-value 'simplex))
425 (defmeth simplex-proto :f (&optional f)
426 (when f
427 (setf (slot-value 'f) f)
428 (let ((simplex
429 (mapcar #'(lambda (x) (send self :point-location x))
430 (send self :simplex))))
431 (send self :simplex simplex)))
432 (slot-value 'f))
434 (defmeth simplex-proto :sort-simplex ()
435 (if (send self :f)
436 (setf (slot-value 'simplex)
437 (sort (slot-value 'simplex)
438 #'(lambda (x y) (send self :is-worse x y))))))
441 ;;; Other Methods Using List Representation of SImplex
444 (defmeth simplex-proto :best-point () (car (last (send self :simplex))))
445 (defmeth simplex-proto :worst-point () (first (send self :simplex)))
446 (defmeth simplex-proto :second-worst-point () (second (send self :simplex)))
447 (defmeth simplex-proto :replace-point (new old)
448 (let* ((simplex (send self :simplex))
449 (n (position old simplex)))
450 (when n
451 (setf (nth n simplex) new)
452 (send self :sort-simplex))))
453 (defmeth simplex-proto :mean-opposite-face (x)
454 (let ((face (mapcar #'(lambda (x) (send self :point-location x))
455 (remove x (send self :simplex)))))
456 (/ (reduce #'+ face) (length face))))
459 ;;; Iteration Step Methods
462 (defmeth simplex-proto :extrapolate-from-worst (fac)
463 (let* ((worst (send self :worst-point))
464 (wloc (send self :point-location worst))
465 (delta (- (send self :mean-opposite-face worst) wloc))
466 (new (send self :make-point (+ wloc (* (- 1 fac) delta)))))
467 (if (send self :is-worse worst new) (send self :replace-point new worst))
468 new))
470 (defmeth simplex-proto :shrink-to-best (fac)
471 (let* ((best (send self :best-point))
472 (bloc (send self :point-location best)))
473 (dolist (x (copy-list (send self :simplex)))
474 (if (not (eq x best))
475 (send self :replace-point
476 (send self :make-point
477 (+ bloc
478 (* fac
479 (- (send self :point-location x) bloc))))
480 x)))))
482 (defmeth simplex-proto :relative-range ()
483 (let ((best (send self :point-value (send self :best-point)))
484 (worst (send self :point-value (send self :worst-point))))
485 (* 2 (/ (abs (- best worst)) (+ 1 (abs best) (abs worst))))))
490 ;;;;
491 ;;;; Maximization and Numerical Derivatives
492 ;;;;
495 (defun data2double (n data ptr)
496 (declare (fixnum n))
497 (let* ((seq (compound-data-seq data))
498 (elem (make-next-element seq)))
499 (if (/= (length seq) n) (error "bad data size"))
500 (dotimes (i n)
501 (declare (fixnum i))
502 (la-put-double ptr i (get-next-element elem i)))))
504 (defun maximize-callback (n px pfval pgrad phess pderivs)
505 (la-vector-to-data px n +mode-re+ *maximize-callback-arg*)
506 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
507 (derivs (if (consp val) (- (length val) 1) 0)))
508 (la-put-integer pderivs 0 derivs)
509 (la-put-double pfval 0 (if (consp val) (first val) val))
510 (if (<= 1 derivs) (data2double n (second val) pgrad))
511 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
513 (defun numgrad (f x &optional scale (h -1.0))
514 "Args: (f x &optional scale derivstep)
515 Computes the numerical gradient of F at X."
516 (check-sequence x)
517 (check-real x)
518 (when scale
519 (check-sequence scale)
520 (check-real scale))
521 (check-one-real h)
522 (let* ((n (length x))
523 (result (make-list n)))
524 (if (and scale (/= n (length scale)))
525 (error "scale not the same length as x"))
526 (let ((*maximize-callback-function* f)
527 (*maximize-callback-arg* (make-list n)))
528 (let ((px (la-data-to-vector x +mode-re+))
529 (pgrad (la-vector n +mode-re+))
530 (pscale (la-data-to-vector
531 (if scale scale (make-list n :initial-element 1.0))
532 +mode-re+)))
533 (unwind-protect
534 (progn
535 (numgrad-front n px pgrad h pscale)
536 (la-vector-to-data pgrad n +mode-re+ result))
537 (la-free-vector px)
538 (la-free-vector pgrad)
539 (la-free-vector pscale))))
540 result))
542 (defun numhess (f x &optional scale (h -1.0) all)
543 "Args: (f x &optional scale derivstep)
544 Computes the numerical Hessian matrix of F at X."
545 (check-sequence x)
546 (check-real x)
547 (when scale
548 (check-sequence scale)
549 (check-real scale))
550 (check-one-real h)
551 (let* ((n (length x))
552 (result (if all
553 (list nil (make-list n) (make-array (list n n)))
554 (make-array (list n n)))))
555 (if (and scale (/= n (length scale)))
556 (error "scale not the same length as x"))
557 (let ((*maximize-callback-function* f)
558 (*maximize-callback-arg* (make-list n)))
559 (let ((hess-data (compound-data-seq (if all (third result) result)))
560 (px (la-data-to-vector x +mode-re+))
561 (pf (la-vector 1 +mode-re+))
562 (pgrad (la-vector n +mode-re+))
563 (phess (la-vector (* n n) +mode-re+))
564 (pscale (la-data-to-vector
565 (if scale scale (make-list n :initial-element 1.0))
566 +mode-re+)))
567 (unwind-protect
568 (progn
569 (numhess-front n px pf pgrad phess h pscale)
570 (when all
571 (setf (first result) (la-get-double pf 0))
572 (la-vector-to-data pgrad n +mode-re+ (second result)))
573 (la-vector-to-data phess (* n n) +mode-re+ hess-data))
574 (la-free-vector pf)
575 (la-free-vector px)
576 (la-free-vector pgrad)
577 (la-free-vector phess)
578 (la-free-vector pscale))))
579 result))