clean up loads, no substantial changes
[CommonLispStat.git] / optimize.lisp
blob9a10736109a57d3880f06359405caf5281be6a69
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 "Method: ()
280 Make a copy of an minfo instance."
281 (let ((obj (make-object minfo-proto))
282 (internals (copy-seq (slot-value 'internals))))
283 (dotimes (i (length internals))
284 (let ((x (aref internals i)))
285 (if (sequencep x)
286 (setf (aref internals i) (copy-seq x)))))
287 (send obj :add-slot 'internals internals)
288 obj))
290 (defmeth minfo-proto :derivscale ()
291 (let* ((step (^ machine-epsilon (/ 1 6)))
292 (hess (numhess (send self :f) (send self :x) (send self :scale) step))
293 (scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess)))))))
294 (setf hess (numhess (send self :f) (send self :x) scale step))
295 (setf scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess))))))
296 (setf (aref (slot-value 'internals) 4) scale)
297 (setf (aref (aref (slot-value 'internals) 9) 1) step)))
299 (defmeth minfo-proto :verbose (&optional (val nil set))
300 (when set
301 (setf (aref (aref (slot-value 'internals) 8) 5)
302 (cond ((integerp val) val)
303 ((null val) 0)
304 (t 1))))
305 (aref (aref (slot-value 'internals) 8) 5))
307 (defmeth minfo-proto :backtrack (&optional (val nil set))
308 (if set (setf (aref (aref (slot-value 'internals) 8) 4) (if val 1 0)))
309 (aref (aref (slot-value 'internals) 8) 4))
311 (defmeth minfo-proto :maxiter (&optional (val nil set))
312 (if set (setf (aref (aref (slot-value 'internals) 8) 3)
313 (if (integerp val) val -1)))
314 (aref (aref (slot-value 'internals) 8) 3))
316 (defmeth minfo-proto :tiltscale (&optional (val nil set))
317 (when set
318 (if (/= (length val) (length (send self :gfuns)))
319 (error "wrong size tilt scale sequence"))
320 (setf (aref (slot-value 'internals) 10) val))
321 (aref (slot-value 'internals) 10))
323 ;;;;
324 ;;;;
325 ;;;; Newton's Method with Backtracking
326 ;;;;
327 ;;;;
329 (defun newtonmax (f start &key
330 scale
331 (derivstep -1.0)
332 (count-limit -1)
333 (verbose 1)
334 return-derivs)
335 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
336 Maximizes F starting from START using Newton's method with backtracking.
337 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
338 list of location, unction value, gradient and hessian at maximum.
339 SCALE should be a list of the typical magnitudes of the parameters.
340 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
341 of iteration information. COUNT-LIMIT limits the number of iterations"
342 (let ((verbose (if verbose (if (integerp verbose) verbose 1) 0))
343 (minfo (send minfo-proto :new f start
344 :scale scale :derivstep derivstep)))
345 (send minfo :maxiter count-limit)
346 (send minfo :derivscale)
347 (send minfo :maximize verbose)
348 (if return-derivs
349 (cons (send minfo :x) (- (send minfo :fvals)))
350 (send minfo :x))))
353 ;;; Nelder-Mead Simplex Method
356 ;;; Simplex Prototype
358 (defvar simplex-proto)
359 (defproto simplex-proto '(f simplex))
361 (defun nelmeadmax (f start &key
362 (size 1)
363 (epsilon (sqrt machine-epsilon))
364 (count-limit 500)
365 (verbose t)
366 (alpha 1.0)
367 (beta 0.5)
368 (gamma 2.0)
369 (delta 0.5))
370 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
371 (count-limit 500) (verbose t) alpha beta gamma delta)
372 Maximizes F using the Nelder-Mead simplex method. START can be a
373 starting simplex - a list of N+1 points, with N=dimension of problem,
374 or a single point. If start is a single point you should give the
375 size of the initial simplex as SIZE, a sequence of length N. Default is
376 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
377 control the behavior of simplex algorithm."
378 (let ((s (send simplex-proto :new f start size)))
379 (do ((best (send s :best-point) (send s :best-point))
380 (count 0 (+ count 1))
381 next)
382 ((or (< (send s :relative-range) epsilon) (>= count count-limit))
383 (if (and verbose (>= count count-limit))
384 (format t "Iteration limit exceeded.~%"))
385 (send s :point-location (send s :best-point)))
386 (setf next (send s :extrapolate-from-worst (- alpha)))
387 (if (send s :is-worse best next)
388 (setf next (send s :extrapolate-from-worst gamma))
389 (when (send s :is-worse next (send s :second-worst-point))
390 (setf next (send s :extrapolate-from-worst beta))
391 (if (send s :is-worse next (send s :worst-point))
392 (send s :shrink-to-best delta))))
393 (if verbose
394 (format t "Value = ~10g~%"
395 (send s :point-value (send s :best-point)))))))
400 ;;; Simplex Points
403 (defmeth simplex-proto :make-point (x)
404 (let ((f (send self :f)))
405 (if f
406 (let ((val (funcall f x)))
407 (cons (if (consp val) (car val) val) x))
408 (cons nil x))))
410 (defmeth simplex-proto :point-value (x) (car x))
412 (defmeth simplex-proto :point-location (x) (cdr x))
414 (defmeth simplex-proto :is-worse (x y)
415 (< (send self :point-value x) (send self :point-value y)))
418 ;;; Making New Simplices
421 (defmeth simplex-proto :isnew (f start &optional size)
422 (send self :simplex start size)
423 (send self :f f))
426 ;;; Slot Accessors and Mutators
429 (defmeth simplex-proto :simplex (&optional new size)
430 (if new
431 (let ((simplex
432 (if (and (consp new) (sequencep (car new)))
433 (if (/= (length new) (+ 1 (length (car new))))
434 (error "bad simplex data")
435 (copy-list new))
436 (let* ((n (length new))
437 (size (if size size (repeat 1 n)))
438 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
439 (diag (* 2 size (- (random (repeat 2 n)) .5)))
440 (pts (cons (repeat 0 n)
441 (mapcar #'(lambda (x) (coerce x 'list))
442 (column-list (diagonal diag))))))
443 (mapcar #'(lambda (x) (reduce #'+ (list (* size x) new))) pts)))))
444 (setf (slot-value 'simplex)
445 (mapcar #'(lambda (x) (send self :make-point x)) simplex))
446 (send self :sort-simplex)))
447 (slot-value 'simplex))
449 (defmeth simplex-proto :f (&optional f)
450 (when f
451 (setf (slot-value 'f) f)
452 (let ((simplex
453 (mapcar #'(lambda (x) (send self :point-location x))
454 (send self :simplex))))
455 (send self :simplex simplex)))
456 (slot-value 'f))
458 (defmeth simplex-proto :sort-simplex ()
459 (if (send self :f)
460 (setf (slot-value 'simplex)
461 (sort (slot-value 'simplex)
462 #'(lambda (x y) (send self :is-worse x y))))))
465 ;;; Other Methods Using List Representation of SImplex
468 (defmeth simplex-proto :best-point () (car (last (send self :simplex))))
469 (defmeth simplex-proto :worst-point () (first (send self :simplex)))
470 (defmeth simplex-proto :second-worst-point () (second (send self :simplex)))
471 (defmeth simplex-proto :replace-point (new old)
472 (let* ((simplex (send self :simplex))
473 (n (position old simplex)))
474 (when n
475 (setf (nth n simplex) new)
476 (send self :sort-simplex))))
477 (defmeth simplex-proto :mean-opposite-face (x)
478 (let ((face (mapcar #'(lambda (x) (send self :point-location x))
479 (remove x (send self :simplex)))))
480 (/ (reduce #'+ face) (length face))))
483 ;;; Iteration Step Methods
486 (defmeth simplex-proto :extrapolate-from-worst (fac)
487 (let* ((worst (send self :worst-point))
488 (wloc (send self :point-location worst))
489 (delta (- (send self :mean-opposite-face worst) wloc))
490 (new (send self :make-point (+ wloc (* (- 1 fac) delta)))))
491 (if (send self :is-worse worst new) (send self :replace-point new worst))
492 new))
494 (defmeth simplex-proto :shrink-to-best (fac)
495 (let* ((best (send self :best-point))
496 (bloc (send self :point-location best)))
497 (dolist (x (copy-list (send self :simplex)))
498 (if (not (eq x best))
499 (send self :replace-point
500 (send self :make-point
501 (+ bloc
502 (* fac
503 (- (send self :point-location x) bloc))))
504 x)))))
506 (defmeth simplex-proto :relative-range ()
507 (let ((best (send self :point-value (send self :best-point)))
508 (worst (send self :point-value (send self :worst-point))))
509 (* 2 (/ (abs (- best worst)) (+ 1 (abs best) (abs worst))))))
514 ;;;;
515 ;;;; Maximization and Numerical Derivatives
516 ;;;;
519 (defun data2double (n data ptr)
520 (declare (fixnum n))
521 (let* ((seq (compound-data-seq data))
522 (elem (make-next-element seq)))
523 (if (/= (length seq) n) (error "bad data size"))
524 (dotimes (i n)
525 (declare (fixnum i))
526 (la-put-double ptr i (get-next-element elem i)))))
528 (defun maximize-callback (n px pfval pgrad phess pderivs)
529 (la-vector-to-data px n +mode-re+ *maximize-callback-arg*)
530 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
531 (derivs (if (consp val) (- (length val) 1) 0)))
532 (la-put-integer pderivs 0 derivs)
533 (la-put-double pfval 0 (if (consp val) (first val) val))
534 (if (<= 1 derivs) (data2double n (second val) pgrad))
535 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
537 (defun numgrad (f x &optional scale (h -1.0))
538 "Args: (f x &optional scale derivstep)
539 Computes the numerical gradient of F at X."
540 (check-sequence x)
541 (check-real x)
542 (when scale
543 (check-sequence scale)
544 (check-real scale))
545 (check-one-real h)
546 (let* ((n (length x))
547 (result (make-list n)))
548 (if (and scale (/= n (length scale)))
549 (error "scale not the same length as x"))
550 (let ((*maximize-callback-function* f)
551 (*maximize-callback-arg* (make-list n)))
552 (let ((px (la-data-to-vector x +mode-re+))
553 (pgrad (la-vector n +mode-re+))
554 (pscale (la-data-to-vector
555 (if scale scale (make-list n :initial-element 1.0))
556 +mode-re+)))
557 (unwind-protect
558 (progn
559 (numgrad-front n px pgrad h pscale)
560 (la-vector-to-data pgrad n +mode-re+ result))
561 (la-free-vector px)
562 (la-free-vector pgrad)
563 (la-free-vector pscale))))
564 result))
566 (defun numhess (f x &optional scale (h -1.0) all)
567 "Args: (f x &optional scale derivstep)
568 Computes the numerical Hessian matrix of F at X."
569 (check-sequence x)
570 (check-real x)
571 (when scale
572 (check-sequence scale)
573 (check-real scale))
574 (check-one-real h)
575 (let* ((n (length x))
576 (result (if all
577 (list nil (make-list n) (make-array (list n n)))
578 (make-array (list n n)))))
579 (if (and scale (/= n (length scale)))
580 (error "scale not the same length as x"))
581 (let ((*maximize-callback-function* f)
582 (*maximize-callback-arg* (make-list n)))
583 (let ((hess-data (compound-data-seq (if all (third result) result)))
584 (px (la-data-to-vector x +mode-re+))
585 (pf (la-vector 1 +mode-re+))
586 (pgrad (la-vector n +mode-re+))
587 (phess (la-vector (* n n) +mode-re+))
588 (pscale (la-data-to-vector
589 (if scale scale (make-list n :initial-element 1.0))
590 +mode-re+)))
591 (unwind-protect
592 (progn
593 (numhess-front n px pf pgrad phess h pscale)
594 (when all
595 (setf (first result) (la-get-double pf 0))
596 (la-vector-to-data pgrad n +mode-re+ (second result)))
597 (la-vector-to-data phess (* n n) +mode-re+ hess-data))
598 (la-free-vector pf)
599 (la-free-vector px)
600 (la-free-vector pgrad)
601 (la-free-vector phess)
602 (la-free-vector pscale))))
603 result))