fixed problem with demo sequencing, added CLISP error note
[CommonLispStat.git] / optimize.lisp
blob2316982a4d142f10993d460d17594f6d4ca438a6
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.
6 (in-package :cl-user)
8 (defpackage :lisp-stat-optimize
9 (:use :common-lisp
10 :lisp-stat-ffi-int
11 :lisp-stat-object-system
12 :lisp-stat-types
13 :lisp-stat-compound-data
14 :lisp-stat-math
15 :lisp-stat-float
16 :lisp-stat-basics
17 :lisp-stat-matrix
18 :lisp-stat-linalg-data
19 :lisp-stat-linalg)
20 (:shadowing-import-from :lisp-stat-object-system
21 slot-value call-method call-next-method)
22 (:shadowing-import-from :lisp-stat-math
23 expt + - * / ** mod rem abs 1+ 1- log exp sqrt sin cos tan
24 asin acos atan sinh cosh tanh asinh acosh atanh float random
25 truncate floor ceiling round minusp zerop plusp evenp oddp
26 < <= = /= >= > complex conjugate realpart imagpart phase
27 min max logand logior logxor lognot ffloor fceiling
28 ftruncate fround signum cis)
29 (:export
30 ;; derivatives
31 numgrad numhess
33 ;; optimization
34 newtonmax nelmeadmax))
36 ;; matrix is in statistics, but should that be a predecessor?
38 ;;; FIXME:AJR: There is a need to figure out the proper symbols to
39 ;;; export. more importantly should there be any specialty package
40 ;;; that are exported for maximization?
42 (in-package :lisp-stat-optimize)
44 (defvar *maximize-callback-function* nil
45 "Used in generic optimization to determine function name -- symbol or string?")
47 (defvar *maximize-callback-arg* nil
48 "args to function to maximize")
51 ;;;
52 ;;; CFFI support using library for optimization work.
53 ;;;
55 ;; There is a problem with this particular approach, in terms of
56 ;; circular dependencies. We can not have this out-of-object call
57 ;; into optimize, at least not from here.
58 (cffi:defcallback ccl-maximize-callback :void ((n :int)
59 (px :pointer)
60 (pfval :pointer)
61 (pgrad :pointer)
62 (phess :pointer)
63 (pderivs :pointer))
64 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs))
66 (cffi:defcfun ("register_maximize_callback" register-maximize-callback)
67 :void (x :pointer))
68 (register-maximize-callback (cffi:callback ccl-maximize-callback))
70 (cffi:defcfun ("ccl_numgrad_front" ccl-numgrad-front)
71 :int (x :int) (y :pointer) (z :pointer) (u :double) (v :pointer))
72 (defun numgrad-front (x y z u v)
73 (ccl-numgrad-front x y z (float u 1d0) v))
75 (cffi:defcfun ("ccl_numhess_front" ccl-numhess-front)
76 :int (x :int) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :double) (a :pointer))
77 (defun numhess-front (x y z u v w a)
78 (ccl-numhess-front x y z u v (float w 1d0) a))
80 (cffi:defcfun ("ccl_minfo_maximize" ccl-minfo-maximize)
81 :int (x :pointer) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :int))
82 (defun base-minfo-maximize (x y z u v w)
83 (ccl-minfo-maximize x y z u v w))
87 ;;;;
88 ;;;; minfo basics (internal??)
89 ;;;;
91 (defun init-minfo-ipar-values (n ipars &key
92 (TRUE 1)
93 (FALSE 0)
94 (k 0)
95 (m 0)
96 (itnlimit -1)
97 (backtrack TRUE)
98 (verbose 0)
99 (vals_suppl FALSE)
100 (exptilt TRUE)
101 (count 0)
102 (termcode 0))
103 "Initialize ipars (iteration parameters) by destructive modification."
104 (setf (aref ipars 0) n)
105 (setf (aref ipars 1) m)
106 (setf (aref ipars 2) k)
107 (setf (aref ipars 3) itnlimit)
108 (setf (aref ipars 4) backtrack)
109 (setf (aref ipars 5) verbose)
110 (setf (aref ipars 6) vals_suppl)
111 (setf (aref ipars 7) exptilt)
112 (setf (aref ipars 8) count)
113 (setf (aref ipars 9) termcode))
115 (defun init-minfo-dpar-values (h dpars &key
116 (typf 1.0)
117 (gradtol -1.0)
118 (steptol -1.0)
119 (maxstep -1.0)
120 (dflt 0.0)
121 (tilt 0.0)
122 (newtilt 0.0)
123 (hessadd 0.0))
124 "Initialize dpars (derivative parameters) by destructive modification."
125 (setf (aref dpars 0) typf)
126 (setf (aref dpars 1) h)
127 (setf (aref dpars 2) gradtol)
128 (setf (aref dpars 3) steptol)
129 (setf (aref dpars 4) maxstep)
130 (setf (aref dpars 5) dflt)
131 (setf (aref dpars 6) tilt)
132 (setf (aref dpars 7) newtilt)
133 (setf (aref dpars 8) hessadd))
135 (defun init-minfo-internals (n h internals)
136 (let ((ipars (aref internals 8))
137 (dpars (aref internals 9)))
138 (init-minfo-ipar-values n ipars)
139 (init-minfo-dpar-values h dpars)))
141 (defun new-minfo-internals (f x &key scale ((:derivstep h) -1.0))
142 (check-sequence x)
143 (check-real x)
144 (check-one-real h)
145 (let ((n (length x)))
146 (when scale
147 (check-sequence scale)
148 (check-real scale)
149 (if (/= n (length scale)) (error "scale and x not the same length")))
150 (let ((internals (make-array 12)))
151 (setf (aref internals 0) f)
152 (setf (aref internals 3) (if (consp x) (copy-list x) (coerce x 'list)))
153 (setf (aref internals 4)
154 (if scale (copy-seq scale) (make-array n :initial-element 1.0)))
155 (setf (aref internals 5) (make-list (+ 1 n (* n n))))
156 (setf (aref internals 8) (make-array 10))
157 (setf (aref internals 9) (make-array 9))
158 (init-minfo-internals n h internals)
159 internals)))
161 (defun minfo-maximize (internals &optional verbose)
162 "This function does what?"
163 (let* ((f (aref internals 0))
164 (x (aref internals 3))
165 (fvals (aref internals 5))
166 (n (length x))
167 (v (if verbose (if (integerp verbose) verbose 1) -1)))
168 (setf (aref internals 3) (copy-list x))
169 (setf (aref internals 5) (copy-list fvals))
170 (let ((*maximize-callback-function* f)
171 (*maximize-callback-arg* (make-list n)))
172 (let* ((x (aref internals 3))
173 (scale (aref internals 4))
174 (fvals (aref internals 5))
175 (ip (aref internals 8))
176 (dp (aref internals 9))
177 (px (la-data-to-vector x +mode-re+))
178 (pscale (la-data-to-vector scale +mode-re+))
179 (pfvals (la-vector (length fvals) +mode-re+))
180 (pip (la-data-to-vector ip +mode-in+))
181 (pdp (la-data-to-vector dp +mode-re+)))
182 (unwind-protect
183 (progn
184 (base-minfo-maximize px pfvals pscale pip pdp v)) ;; access to C
185 (la-vector-to-data px n +mode-re+ x)
186 (la-vector-to-data pfvals (+ 1 n (* n n)) +mode-re+ fvals)
187 (la-vector-to-data pip (length ip) +mode-in+ ip)
188 (la-vector-to-data pdp (length dp) +mode-re+ dp))
189 (get-buf)))))
193 ;;;;
194 ;;;; Mode Info Prototype
195 ;;;;
197 (defvar minfo-proto)
198 (defproto minfo-proto '(internals))
200 #+xlisp (send minfo-proto :add-method :isnew #'|minfo-isnew|)
201 #+xlisp (send minfo-proto :add-method :maximize #'|minfo-maximize|)
202 #+xlisp (send minfo-proto :add-method :loglaplace #'|minfo-loglap|)
203 #-xlisp
204 (defmeth minfo-proto :isnew (&rest args)
205 (setf (slot-value 'internals) (apply #'new-minfo-internals args)))
206 #-xlisp
207 (defmeth minfo-proto :maximize (&rest args)
208 (apply #'minfo-maximize (slot-value 'internals) args))
210 (defmeth minfo-proto :x () (aref (slot-value 'internals) 3))
211 (defmeth minfo-proto :scale () (aref (slot-value 'internals) 4))
212 (defmeth minfo-proto :derivstep () (aref (aref (slot-value 'internals) 9) 1))
213 (defmeth minfo-proto :tilt () (aref (aref (slot-value 'internals) 9) 6))
215 (defmeth minfo-proto :f (&optional (val nil set))
216 (when set
217 (send self :set-no-vals-supplied)
218 (setf (aref (slot-value 'internals) 0) val))
219 (aref (slot-value 'internals) 0))
221 (defmeth minfo-proto :set-no-vals-supplied ()
222 (setf (aref (aref (slot-value 'internals) 8) 6) 0))
224 (defmeth minfo-proto :exptilt (&optional (val nil set))
225 (if set
226 (let ((old (send self :exptilt)))
227 (setf (aref (aref (slot-value 'internals) 8) 7) (if val 1 0))
228 (if (and (not (or (and old val) (and (not old) (not val))))
229 (/= (send self :tilt) 0.0))
230 (send self :set-no-vals-supplied))))
231 (= 1 (aref (aref (slot-value 'internals) 8) 7)))
233 (defmeth minfo-proto :newtilt (&optional (val nil set))
234 (when set
235 (setf (aref (aref (slot-value 'internals) 9) 7) (float val))
236 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
237 (aref (aref (slot-value 'internals) 9) 7))
239 (defmeth minfo-proto :gfuns (&optional (val nil set))
240 (when set
241 (if (or (not (consp val))
242 (not (every #'functionp val)))
243 (error "not all functions"))
244 (setf (aref (slot-value 'internals) 1) val)
245 (setf (aref (aref (slot-value 'internals) 8) 1) (length val))
246 (setf (aref (slot-value 'internals) 10) (repeat 1.0 (length val)))
247 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
248 (aref (slot-value 'internals) 1))
250 (defmeth minfo-proto :cfuns (&optional (val nil set))
251 (when set
252 (if (or (not (consp val))
253 (not (every #'functionp val)))
254 (error "not all functions"))
255 (setf (aref (slot-value 'internals) 2) val)
256 (setf (aref (aref (slot-value 'internals) 8) 2) (length val))
257 (setf (aref (slot-value 'internals) 7) (repeat 0.0 (length val)))
258 (setf (aref (slot-value 'internals) 11) (repeat 0.0 (length val)))
259 (send self :set-no-vals-supplied))
260 (aref (slot-value 'internals) 2))
262 (defmeth minfo-proto :ctarget (&optional (val nil set))
263 (when set
264 (if (/= (length val) (length (send self :ctarget)))
265 (error "bad target length"))
266 (setf (aref (slot-value 'internals) 7) val))
267 (aref (slot-value 'internals) 7))
269 (defmeth minfo-proto :fvals ()
270 (let* ((fv (aref (slot-value 'internals) 5))
271 (n (length (send self :x)))
272 (val (select fv 0))
273 (grad (select fv (iseq 1 n)))
274 (hess (matrix (list n n) (select fv (iseq (+ 1 n) (+ n (* n n)))))))
275 (list val grad hess)))
277 (defmeth minfo-proto :copy ()
278 (let ((obj (make-object minfo-proto))
279 (internals (copy-seq (slot-value 'internals))))
280 (dotimes (i (length internals))
281 (let ((x (aref internals i)))
282 (if (sequencep x)
283 (setf (aref internals i) (copy-seq x)))))
284 (send obj :add-slot 'internals internals)
285 obj))
287 (defmeth minfo-proto :derivscale ()
288 (let* ((step (^ machine-epsilon (/ 1 6)))
289 (hess (numhess (send self :f) (send self :x) (send self :scale) step))
290 (scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess)))))))
291 (setf hess (numhess (send self :f) (send self :x) scale step))
292 (setf scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess))))))
293 (setf (aref (slot-value 'internals) 4) scale)
294 (setf (aref (aref (slot-value 'internals) 9) 1) step)))
296 (defmeth minfo-proto :verbose (&optional (val nil set))
297 (when set
298 (setf (aref (aref (slot-value 'internals) 8) 5)
299 (cond ((integerp val) val)
300 ((null val) 0)
301 (t 1))))
302 (aref (aref (slot-value 'internals) 8) 5))
304 (defmeth minfo-proto :backtrack (&optional (val nil set))
305 (if set (setf (aref (aref (slot-value 'internals) 8) 4) (if val 1 0)))
306 (aref (aref (slot-value 'internals) 8) 4))
308 (defmeth minfo-proto :maxiter (&optional (val nil set))
309 (if set (setf (aref (aref (slot-value 'internals) 8) 3)
310 (if (integerp val) val -1)))
311 (aref (aref (slot-value 'internals) 8) 3))
313 (defmeth minfo-proto :tiltscale (&optional (val nil set))
314 (when set
315 (if (/= (length val) (length (send self :gfuns)))
316 (error "wrong size tilt scale sequence"))
317 (setf (aref (slot-value 'internals) 10) val))
318 (aref (slot-value 'internals) 10))
320 ;;;;
321 ;;;;
322 ;;;; Newton's Method with Backtracking
323 ;;;;
324 ;;;;
326 (defun newtonmax (f start &key
327 scale
328 (derivstep -1.0)
329 (count-limit -1)
330 (verbose 1)
331 return-derivs)
332 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
333 Maximizes F starting from START using Newton's method with backtracking.
334 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
335 list of location, unction value, gradient and hessian at maximum.
336 SCALE should be a list of the typical magnitudes of the parameters.
337 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
338 of iteration information. COUNT-LIMIT limits the number of iterations"
339 (let ((verbose (if verbose (if (integerp verbose) verbose 1) 0))
340 (minfo (send minfo-proto :new f start
341 :scale scale :derivstep derivstep)))
342 (send minfo :maxiter count-limit)
343 (send minfo :derivscale)
344 (send minfo :maximize verbose)
345 (if return-derivs
346 (cons (send minfo :x) (- (send minfo :fvals)))
347 (send minfo :x))))
350 ;;; Nelder-Mead Simplex Method
353 ;;; Simplex Prototype
355 (defvar simplex-proto)
356 (defproto simplex-proto '(f simplex))
358 (defun nelmeadmax (f start &key
359 (size 1)
360 (epsilon (sqrt machine-epsilon))
361 (count-limit 500)
362 (verbose t)
363 (alpha 1.0)
364 (beta 0.5)
365 (gamma 2.0)
366 (delta 0.5))
367 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
368 (count-limit 500) (verbose t) alpha beta gamma delta)
369 Maximizes F using the Nelder-Mead simplex method. START can be a
370 starting simplex - a list of N+1 points, with N=dimension of problem,
371 or a single point. If start is a single point you should give the
372 size of the initial simplex as SIZE, a sequence of length N. Default is
373 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
374 control the behavior of simplex algorithm."
375 (let ((s (send simplex-proto :new f start size)))
376 (do ((best (send s :best-point) (send s :best-point))
377 (count 0 (+ count 1))
378 next)
379 ((or (< (send s :relative-range) epsilon) (>= count count-limit))
380 (if (and verbose (>= count count-limit))
381 (format t "Iteration limit exceeded.~%"))
382 (send s :point-location (send s :best-point)))
383 (setf next (send s :extrapolate-from-worst (- alpha)))
384 (if (send s :is-worse best next)
385 (setf next (send s :extrapolate-from-worst gamma))
386 (when (send s :is-worse next (send s :second-worst-point))
387 (setf next (send s :extrapolate-from-worst beta))
388 (if (send s :is-worse next (send s :worst-point))
389 (send s :shrink-to-best delta))))
390 (if verbose
391 (format t "Value = ~10g~%"
392 (send s :point-value (send s :best-point)))))))
397 ;;; Simplex Points
400 (defmeth simplex-proto :make-point (x)
401 (let ((f (send self :f)))
402 (if f
403 (let ((val (funcall f x)))
404 (cons (if (consp val) (car val) val) x))
405 (cons nil x))))
407 (defmeth simplex-proto :point-value (x) (car x))
409 (defmeth simplex-proto :point-location (x) (cdr x))
411 (defmeth simplex-proto :is-worse (x y)
412 (< (send self :point-value x) (send self :point-value y)))
415 ;;; Making New Simplices
418 (defmeth simplex-proto :isnew (f start &optional size)
419 (send self :simplex start size)
420 (send self :f f))
423 ;;; Slot Accessors and Mutators
426 (defmeth simplex-proto :simplex (&optional new size)
427 (if new
428 (let ((simplex
429 (if (and (consp new) (sequencep (car new)))
430 (if (/= (length new) (+ 1 (length (car new))))
431 (error "bad simplex data")
432 (copy-list new))
433 (let* ((n (length new))
434 (size (if size size (repeat 1 n)))
435 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
436 (diag (* 2 size (- (random (repeat 2 n)) .5)))
437 (pts (cons (repeat 0 n)
438 (mapcar #'(lambda (x) (coerce x 'list))
439 (column-list (diagonal diag))))))
440 (mapcar #'(lambda (x) (reduce #'+ (list (* size x) new))) pts)))))
441 (setf (slot-value 'simplex)
442 (mapcar #'(lambda (x) (send self :make-point x)) simplex))
443 (send self :sort-simplex)))
444 (slot-value 'simplex))
446 (defmeth simplex-proto :f (&optional f)
447 (when f
448 (setf (slot-value 'f) f)
449 (let ((simplex
450 (mapcar #'(lambda (x) (send self :point-location x))
451 (send self :simplex))))
452 (send self :simplex simplex)))
453 (slot-value 'f))
455 (defmeth simplex-proto :sort-simplex ()
456 (if (send self :f)
457 (setf (slot-value 'simplex)
458 (sort (slot-value 'simplex)
459 #'(lambda (x y) (send self :is-worse x y))))))
462 ;;; Other Methods Using List Representation of SImplex
465 (defmeth simplex-proto :best-point () (car (last (send self :simplex))))
466 (defmeth simplex-proto :worst-point () (first (send self :simplex)))
467 (defmeth simplex-proto :second-worst-point () (second (send self :simplex)))
468 (defmeth simplex-proto :replace-point (new old)
469 (let* ((simplex (send self :simplex))
470 (n (position old simplex)))
471 (when n
472 (setf (nth n simplex) new)
473 (send self :sort-simplex))))
474 (defmeth simplex-proto :mean-opposite-face (x)
475 (let ((face (mapcar #'(lambda (x) (send self :point-location x))
476 (remove x (send self :simplex)))))
477 (/ (reduce #'+ face) (length face))))
480 ;;; Iteration Step Methods
483 (defmeth simplex-proto :extrapolate-from-worst (fac)
484 (let* ((worst (send self :worst-point))
485 (wloc (send self :point-location worst))
486 (delta (- (send self :mean-opposite-face worst) wloc))
487 (new (send self :make-point (+ wloc (* (- 1 fac) delta)))))
488 (if (send self :is-worse worst new) (send self :replace-point new worst))
489 new))
491 (defmeth simplex-proto :shrink-to-best (fac)
492 (let* ((best (send self :best-point))
493 (bloc (send self :point-location best)))
494 (dolist (x (copy-list (send self :simplex)))
495 (if (not (eq x best))
496 (send self :replace-point
497 (send self :make-point
498 (+ bloc
499 (* fac
500 (- (send self :point-location x) bloc))))
501 x)))))
503 (defmeth simplex-proto :relative-range ()
504 (let ((best (send self :point-value (send self :best-point)))
505 (worst (send self :point-value (send self :worst-point))))
506 (* 2 (/ (abs (- best worst)) (+ 1 (abs best) (abs worst))))))
511 ;;;;
512 ;;;; Maximization and Numerical Derivatives
513 ;;;;
516 (defun data2double (n data ptr)
517 (declare (fixnum n))
518 (let* ((seq (compound-data-seq data))
519 (elem (make-next-element seq)))
520 (if (/= (length seq) n) (error "bad data size"))
521 (dotimes (i n)
522 (declare (fixnum i))
523 (la-put-double ptr i (get-next-element elem i)))))
525 (defun maximize-callback (n px pfval pgrad phess pderivs)
526 (la-vector-to-data px n +mode-re+ *maximize-callback-arg*)
527 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
528 (derivs (if (consp val) (- (length val) 1) 0)))
529 (la-put-integer pderivs 0 derivs)
530 (la-put-double pfval 0 (if (consp val) (first val) val))
531 (if (<= 1 derivs) (data2double n (second val) pgrad))
532 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
534 (defun numgrad (f x &optional scale (h -1.0))
535 "Args: (f x &optional scale derivstep)
536 Computes the numerical gradient of F at X."
537 (check-sequence x)
538 (check-real x)
539 (when scale
540 (check-sequence scale)
541 (check-real scale))
542 (check-one-real h)
543 (let* ((n (length x))
544 (result (make-list n)))
545 (if (and scale (/= n (length scale)))
546 (error "scale not the same length as x"))
547 (let ((*maximize-callback-function* f)
548 (*maximize-callback-arg* (make-list n)))
549 (let ((px (la-data-to-vector x +mode-re+))
550 (pgrad (la-vector n +mode-re+))
551 (pscale (la-data-to-vector
552 (if scale scale (make-list n :initial-element 1.0))
553 +mode-re+)))
554 (unwind-protect
555 (progn
556 (numgrad-front n px pgrad h pscale)
557 (la-vector-to-data pgrad n +mode-re+ result))
558 (la-free-vector px)
559 (la-free-vector pgrad)
560 (la-free-vector pscale))))
561 result))
563 (defun numhess (f x &optional scale (h -1.0) all)
564 "Args: (f x &optional scale derivstep)
565 Computes the numerical Hessian matrix of F at X."
566 (check-sequence x)
567 (check-real x)
568 (when scale
569 (check-sequence scale)
570 (check-real scale))
571 (check-one-real h)
572 (let* ((n (length x))
573 (result (if all
574 (list nil (make-list n) (make-array (list n n)))
575 (make-array (list n n)))))
576 (if (and scale (/= n (length scale)))
577 (error "scale not the same length as x"))
578 (let ((*maximize-callback-function* f)
579 (*maximize-callback-arg* (make-list n)))
580 (let ((hess-data (compound-data-seq (if all (third result) result)))
581 (px (la-data-to-vector x +mode-re+))
582 (pf (la-vector 1 +mode-re+))
583 (pgrad (la-vector n +mode-re+))
584 (phess (la-vector (* n n) +mode-re+))
585 (pscale (la-data-to-vector
586 (if scale scale (make-list n :initial-element 1.0))
587 +mode-re+)))
588 (unwind-protect
589 (progn
590 (numhess-front n px pf pgrad phess h pscale)
591 (when all
592 (setf (first result) (la-get-double pf 0))
593 (la-vector-to-data pgrad n +mode-re+ (second result)))
594 (la-vector-to-data phess (* n n) +mode-re+ hess-data))
595 (la-free-vector pf)
596 (la-free-vector px)
597 (la-free-vector pgrad)
598 (la-free-vector phess)
599 (la-free-vector pscale))))
600 result))