keyword not opt
[CommonLispStat.git] / optimize.lisp
blobe80c4723e1330ceddff806378734bc32a23bcda5
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-object-system
11 :lisp-stat-basics)
12 (:shadowing-import-from :lisp-stat-object-system
13 slot-value call-method call-next-method)
14 (:export
15 ;; derivatives
16 numgrad numhess
18 ;; optimization
19 newtonmax nelmeadmax))
23 ;;; FIXME:AJR: There is a need to figure out the proper symbols to
24 ;;; export. more importantly should there be any specialty package
25 z;;; that are exported for maximization?
27 (in-package :lisp-stat-optimize)
29 (defvar *maximize-callback-function* nil
30 "Used in generic optimization to determine function name -- symbol or string?")
32 (defvar *maximize-callback-arg* nil
33 "args to function to maximize")
35 ;;;;
36 ;;;; minfo basics (internal??)
37 ;;;;
39 (defun init-minfo-ipar-values (n ipars &key
40 (TRUE 1)
41 (FALSE 0)
42 (k 0)
43 (m 0)
44 (itnlimit -1)
45 (backtrack TRUE)
46 (verbose 0)
47 (vals_suppl FALSE)
48 (exptilt TRUE)
49 (count 0)
50 (termcode 0))
51 "Initialize ipars (iteration parameters) by destructive modification."
52 (setf (aref ipars 0) n)
53 (setf (aref ipars 1) m)
54 (setf (aref ipars 2) k)
55 (setf (aref ipars 3) itnlimit)
56 (setf (aref ipars 4) backtrack)
57 (setf (aref ipars 5) verbose)
58 (setf (aref ipars 6) vals_suppl)
59 (setf (aref ipars 7) exptilt)
60 (setf (aref ipars 8) count)
61 (setf (aref ipars 9) termcode))
63 (defun init-minfo-dpar-values (h dpars &key
64 (typf 1.0)
65 (gradtol -1.0)
66 (steptol -1.0)
67 (maxstep -1.0)
68 (dflt 0.0)
69 (tilt 0.0)
70 (newtilt 0.0)
71 (hessadd 0.0))
72 "Initialize dpars (derivative parameters) by destructive modification."
73 (setf (aref dpars 0) typf)
74 (setf (aref dpars 1) h)
75 (setf (aref dpars 2) gradtol)
76 (setf (aref dpars 3) steptol)
77 (setf (aref dpars 4) maxstep)
78 (setf (aref dpars 5) dflt)
79 (setf (aref dpars 6) tilt)
80 (setf (aref dpars 7) newtilt)
81 (setf (aref dpars 8) hessadd))
83 (defun init-minfo-internals (n h internals)
84 (let ((ipars (aref internals 8))
85 (dpars (aref internals 9)))
86 (init-minfo-ipar-values n ipars)
87 (init-minfo-dpar-values h dpars)))
89 (defun new-minfo-internals (f x &key scale ((:derivstep h) -1.0))
90 (check-sequence x)
91 (check-real x)
92 (check-one-real h)
93 (let ((n (length x)))
94 (when scale
95 (check-sequence scale)
96 (check-real scale)
97 (if (/= n (length scale)) (error "scale and x not the same length")))
98 (let ((internals (make-array 12)))
99 (setf (aref internals 0) f)
100 (setf (aref internals 3) (if (consp x) (copy-list x) (coerce x 'list)))
101 (setf (aref internals 4)
102 (if scale (copy-seq scale) (make-array n :initial-element 1.0)))
103 (setf (aref internals 5) (make-list (+ 1 n (* n n))))
104 (setf (aref internals 8) (make-array 10))
105 (setf (aref internals 9) (make-array 9))
106 (init-minfo-internals n h internals)
107 internals)))
109 (defun minfo-maximize (internals &optional verbose)
110 "This function does what?"
111 (let* ((f (aref internals 0))
112 (x (aref internals 3))
113 (fvals (aref internals 5))
114 (n (length x))
115 (v (if verbose (if (integerp verbose) verbose 1) -1)))
116 (setf (aref internals 3) (copy-list x))
117 (setf (aref internals 5) (copy-list fvals))
118 (let ((*maximize-callback-function* f)
119 (*maximize-callback-arg* (make-list n)))
120 (let* ((x (aref internals 3))
121 (scale (aref internals 4))
122 (fvals (aref internals 5))
123 (ip (aref internals 8))
124 (dp (aref internals 9))
125 (px (la-data-to-vector x mode-re))
126 (pscale (la-data-to-vector scale mode-re))
127 (pfvals (la-vector (length fvals) mode-re))
128 (pip (la-data-to-vector ip mode-in))
129 (pdp (la-data-to-vector dp mode-re)))
130 (unwind-protect
131 (progn
132 (base-minfo-maximize px pfvals pscale pip pdp v)) ;; access to C
133 (la-vector-to-data px n mode-re x)
134 (la-vector-to-data pfvals (+ 1 n (* n n)) mode-re fvals)
135 (la-vector-to-data pip (length ip) mode-in ip)
136 (la-vector-to-data pdp (length dp) mode-re dp))
137 (get-buf)))))
141 ;;;;
142 ;;;; Mode Info Prototype
143 ;;;;
145 (defproto minfo-proto '(internals))
147 #+xlisp (send minfo-proto :add-method :isnew #'|minfo-isnew|)
148 #+xlisp (send minfo-proto :add-method :maximize #'|minfo-maximize|)
149 #+xlisp (send minfo-proto :add-method :loglaplace #'|minfo-loglap|)
150 #-xlisp
151 (defmeth minfo-proto :isnew (&rest args)
152 (setf (slot-value 'internals) (apply #'new-minfo-internals args)))
153 #-xlisp
154 (defmeth minfo-proto :maximize (&rest args)
155 (apply #'minfo-maximize (slot-value 'internals) args))
157 (defmeth minfo-proto :x () (aref (slot-value 'internals) 3))
158 (defmeth minfo-proto :scale () (aref (slot-value 'internals) 4))
159 (defmeth minfo-proto :derivstep () (aref (aref (slot-value 'internals) 9) 1))
160 (defmeth minfo-proto :tilt () (aref (aref (slot-value 'internals) 9) 6))
162 (defmeth minfo-proto :f (&optional (val nil set))
163 (when set
164 (send self :set-no-vals-supplied)
165 (setf (aref (slot-value 'internals) 0) val))
166 (aref (slot-value 'internals) 0))
168 (defmeth minfo-proto :set-no-vals-supplied ()
169 (setf (aref (aref (slot-value 'internals) 8) 6) 0))
171 (defmeth minfo-proto :exptilt (&optional (val nil set))
172 (if set
173 (let ((old (send self :exptilt)))
174 (setf (aref (aref (slot-value 'internals) 8) 7) (if val 1 0))
175 (if (and (not (or (and old val) (and (not old) (not val))))
176 (/= (send self :tilt) 0.0))
177 (send self :set-no-vals-supplied))))
178 (= 1 (aref (aref (slot-value 'internals) 8) 7)))
180 (defmeth minfo-proto :newtilt (&optional (val nil set))
181 (when set
182 (setf (aref (aref (slot-value 'internals) 9) 7) (float val))
183 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
184 (aref (aref (slot-value 'internals) 9) 7))
186 (defmeth minfo-proto :gfuns (&optional (val nil set))
187 (when set
188 (if (or (not (consp val))
189 (not (every #'functionp val)))
190 (error "not all functions"))
191 (setf (aref (slot-value 'internals) 1) val)
192 (setf (aref (aref (slot-value 'internals) 8) 1) (length val))
193 (setf (aref (slot-value 'internals) 10) (repeat 1.0 (length val)))
194 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
195 (aref (slot-value 'internals) 1))
197 (defmeth minfo-proto :cfuns (&optional (val nil set))
198 (when set
199 (if (or (not (consp val))
200 (not (every #'functionp val)))
201 (error "not all functions"))
202 (setf (aref (slot-value 'internals) 2) val)
203 (setf (aref (aref (slot-value 'internals) 8) 2) (length val))
204 (setf (aref (slot-value 'internals) 7) (repeat 0.0 (length val)))
205 (setf (aref (slot-value 'internals) 11) (repeat 0.0 (length val)))
206 (send self :set-no-vals-supplied))
207 (aref (slot-value 'internals) 2))
209 (defmeth minfo-proto :ctarget (&optional (val nil set))
210 (when set
211 (if (/= (length val) (length (send self :ctarget)))
212 (error "bad target length"))
213 (setf (aref (slot-value 'internals) 7) val))
214 (aref (slot-value 'internals) 7))
216 (defmeth minfo-proto :fvals ()
217 (let* ((fv (aref (slot-value 'internals) 5))
218 (n (length (send self :x)))
219 (val (select fv 0))
220 (grad (select fv (iseq 1 n)))
221 (hess (matrix (list n n) (select fv (iseq (+ 1 n) (+ n (* n n)))))))
222 (list val grad hess)))
224 (defmeth minfo-proto :copy ()
225 (let ((obj (make-object minfo-proto))
226 (internals (copy-seq (slot-value 'internals))))
227 (dotimes (i (length internals))
228 (let ((x (aref internals i)))
229 (if (sequencep x)
230 (setf (aref internals i) (copy-seq x)))))
231 (send obj :add-slot 'internals internals)
232 obj))
234 (defmeth minfo-proto :derivscale ()
235 (let* ((step (^ machine-epsilon (/ 1 6)))
236 (hess (numhess (send self :f) (send self :x) (send self :scale) step))
237 (scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess)))))))
238 (setf hess (numhess (send self :f) (send self :x) scale step))
239 (setf scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess))))))
240 (setf (aref (slot-value 'internals) 4) scale)
241 (setf (aref (aref (slot-value 'internals) 9) 1) step)))
243 (defmeth minfo-proto :verbose (&optional (val nil set))
244 (when set
245 (setf (aref (aref (slot-value 'internals) 8) 5)
246 (cond ((integerp val) val)
247 ((null val) 0)
248 (t 1))))
249 (aref (aref (slot-value 'internals) 8) 5))
251 (defmeth minfo-proto :backtrack (&optional (val nil set))
252 (if set (setf (aref (aref (slot-value 'internals) 8) 4) (if val 1 0)))
253 (aref (aref (slot-value 'internals) 8) 4))
255 (defmeth minfo-proto :maxiter (&optional (val nil set))
256 (if set (setf (aref (aref (slot-value 'internals) 8) 3)
257 (if (integerp val) val -1)))
258 (aref (aref (slot-value 'internals) 8) 3))
260 (defmeth minfo-proto :tiltscale (&optional (val nil set))
261 (when set
262 (if (/= (length val) (length (send self :gfuns)))
263 (error "wrong size tilt scale sequence"))
264 (setf (aref (slot-value 'internals) 10) val))
265 (aref (slot-value 'internals) 10))
267 ;;;;
268 ;;;;
269 ;;;; Newton's Method with Backtracking
270 ;;;;
271 ;;;;
273 (defun newtonmax (f start &key
274 scale
275 (derivstep -1.0)
276 (count-limit -1)
277 (verbose 1)
278 return-derivs)
279 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
280 Maximizes F starting from START using Newton's method with backtracking.
281 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
282 list of location, unction value, gradient and hessian at maximum.
283 SCALE should be a list of the typical magnitudes of the parameters.
284 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
285 of iteration information. COUNT-LIMIT limits the number of iterations"
286 (let ((verbose (if verbose (if (integerp verbose) verbose 1) 0))
287 (minfo (send minfo-proto :new f start
288 :scale scale :derivstep derivstep)))
289 (send minfo :maxiter count-limit)
290 (send minfo :derivscale)
291 (send minfo :maximize verbose)
292 (if return-derivs
293 (cons (send minfo :x) (- (send minfo :fvals)))
294 (send minfo :x))))
296 ;;;;
297 ;;;;
298 ;;;; Nelder-Mead Simplex Method
299 ;;;;
300 ;;;;
302 (defun nelmeadmax (f start &key
303 (size 1)
304 (epsilon (sqrt machine-epsilon))
305 (count-limit 500)
306 (verbose t)
307 (alpha 1.0)
308 (beta 0.5)
309 (gamma 2.0)
310 (delta 0.5))
311 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
312 (count-limit 500) (verbose t) alpha beta gamma delta)
313 Maximizes F using the Nelder-Mead simplex method. START can be a
314 starting simplex - a list of N+1 points, with N=dimension of problem,
315 or a single point. If start is a single point you should give the
316 size of the initial simplex as SIZE, a sequence of length N. Default is
317 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
318 control the behavior of simplex algorithm."
319 (let ((s (send simplex-proto :new f start size)))
320 (do ((best (send s :best-point) (send s :best-point))
321 (count 0 (+ count 1))
322 next)
323 ((or (< (send s :relative-range) epsilon) (>= count count-limit))
324 (if (and verbose (>= count count-limit))
325 (format t "Iteration limit exceeded.~%"))
326 (send s :point-location (send s :best-point)))
327 (setf next (send s :extrapolate-from-worst (- alpha)))
328 (if (send s :is-worse best next)
329 (setf next (send s :extrapolate-from-worst gamma))
330 (when (send s :is-worse next (send s :second-worst-point))
331 (setf next (send s :extrapolate-from-worst beta))
332 (if (send s :is-worse next (send s :worst-point))
333 (send s :shrink-to-best delta))))
334 (if verbose
335 (format t "Value = ~10g~%"
336 (send s :point-value (send s :best-point)))))))
340 ;;; Simplex Prototype
343 (defproto simplex-proto '(f simplex))
346 ;;; Simplex Points
349 (defmeth simplex-proto :make-point (x)
350 (let ((f (send self :f)))
351 (if f
352 (let ((val (funcall f x)))
353 (cons (if (consp val) (car val) val) x))
354 (cons nil x))))
356 (defmeth simplex-proto :point-value (x) (car x))
358 (defmeth simplex-proto :point-location (x) (cdr x))
360 (defmeth simplex-proto :is-worse (x y)
361 (< (send self :point-value x) (send self :point-value y)))
364 ;;; Making New Simplices
367 (defmeth simplex-proto :isnew (f start &optional size)
368 (send self :simplex start size)
369 (send self :f f))
372 ;;; Slot Accessors and Mutators
375 (defmeth simplex-proto :simplex (&optional new size)
376 (if new
377 (let ((simplex
378 (if (and (consp new) (sequencep (car new)))
379 (if (/= (length new) (+ 1 (length (car new))))
380 (error "bad simplex data")
381 (copy-list new))
382 (let* ((n (length new))
383 (size (if size size (repeat 1 n)))
384 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
385 (diag (* 2 size (- (random (repeat 2 n)) .5)))
386 (pts (cons (repeat 0 n)
387 (mapcar #'(lambda (x) (coerce x 'list))
388 (column-list (diagonal diag))))))
389 (mapcar #'(lambda (x) (+ (* size x) new)) pts)))))
390 (setf (slot-value 'simplex)
391 (mapcar #'(lambda (x) (send self :make-point x)) simplex))
392 (send self :sort-simplex)))
393 (slot-value 'simplex))
395 (defmeth simplex-proto :f (&optional f)
396 (when f
397 (setf (slot-value 'f) f)
398 (let ((simplex
399 (mapcar #'(lambda (x) (send self :point-location x))
400 (send self :simplex))))
401 (send self :simplex simplex)))
402 (slot-value 'f))
404 (defmeth simplex-proto :sort-simplex ()
405 (if (send self :f)
406 (setf (slot-value 'simplex)
407 (sort (slot-value 'simplex)
408 #'(lambda (x y) (send self :is-worse x y))))))
411 ;;; Other Methods Using List Representation of SImplex
414 (defmeth simplex-proto :best-point () (car (last (send self :simplex))))
415 (defmeth simplex-proto :worst-point () (first (send self :simplex)))
416 (defmeth simplex-proto :second-worst-point () (second (send self :simplex)))
417 (defmeth simplex-proto :replace-point (new old)
418 (let* ((simplex (send self :simplex))
419 (n (position old simplex)))
420 (when n
421 (setf (nth n simplex) new)
422 (send self :sort-simplex))))
423 (defmeth simplex-proto :mean-opposite-face (x)
424 (let ((face (mapcar #'(lambda (x) (send self :point-location x))
425 (remove x (send self :simplex)))))
426 (/ (reduce #'+ face) (length face))))
429 ;;; Iteration Step Methods
432 (defmeth simplex-proto :extrapolate-from-worst (fac)
433 (let* ((worst (send self :worst-point))
434 (wloc (send self :point-location worst))
435 (delta (- (send self :mean-opposite-face worst) wloc))
436 (new (send self :make-point (+ wloc (* (- 1 fac) delta)))))
437 (if (send self :is-worse worst new) (send self :replace-point new worst))
438 new))
440 (defmeth simplex-proto :shrink-to-best (fac)
441 (let* ((best (send self :best-point))
442 (bloc (send self :point-location best)))
443 (dolist (x (copy-list (send self :simplex)))
444 (if (not (eq x best))
445 (send self :replace-point
446 (send self :make-point
447 (+ bloc
448 (* fac
449 (- (send self :point-location x) bloc))))
450 x)))))
452 (defmeth simplex-proto :relative-range ()
453 (let ((best (send self :point-value (send self :best-point)))
454 (worst (send self :point-value (send self :worst-point))))
455 (* 2 (/ (abs (- best worst)) (+ 1 (abs best) (abs worst))))))
460 ;;;;
461 ;;;; Maximization and Numerical Derivatives
462 ;;;;
465 (defun data2double (n data ptr)
466 (declare (fixnum n))
467 (let* ((seq (compound-data-seq data))
468 (elem (make-next-element seq)))
469 (if (/= (length seq) n) (error "bad data size"))
470 (dotimes (i n)
471 (declare (fixnum i))
472 (la-put-double ptr i (get-next-element elem i)))))
474 (defun maximize-callback (n px pfval pgrad phess pderivs)
475 (la-vector-to-data px n mode-re *maximize-callback-arg*)
476 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
477 (derivs (if (consp val) (- (length val) 1) 0)))
478 (la-put-integer pderivs 0 derivs)
479 (la-put-double pfval 0 (if (consp val) (first val) val))
480 (if (<= 1 derivs) (data2double n (second val) pgrad))
481 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
483 (defun numgrad (f x &optional scale (h -1.0))
484 "Args: (f x &optional scale derivstep)
485 Computes the numerical gradient of F at X."
486 (check-sequence x)
487 (check-real x)
488 (when scale
489 (check-sequence scale)
490 (check-real scale))
491 (check-one-real h)
492 (let* ((n (length x))
493 (result (make-list n)))
494 (if (and scale (/= n (length scale)))
495 (error "scale not the same length as x"))
496 (let ((*maximize-callback-function* f)
497 (*maximize-callback-arg* (make-list n)))
498 (let ((px (la-data-to-vector x mode-re))
499 (pgrad (la-vector n mode-re))
500 (pscale (la-data-to-vector
501 (if scale scale (make-list n :initial-element 1.0))
502 mode-re)))
503 (unwind-protect
504 (progn
505 (numgrad-front n px pgrad h pscale)
506 (la-vector-to-data pgrad n mode-re result))
507 (la-free-vector px)
508 (la-free-vector pgrad)
509 (la-free-vector pscale))))
510 result))
512 (defun numhess (f x &optional scale (h -1.0) all)
513 "Args: (f x &optional scale derivstep)
514 Computes the numerical Hessian matrix of F at X."
515 (check-sequence x)
516 (check-real x)
517 (when scale
518 (check-sequence scale)
519 (check-real scale))
520 (check-one-real h)
521 (let* ((n (length x))
522 (result (if all
523 (list nil (make-list n) (make-array (list n n)))
524 (make-array (list n n)))))
525 (if (and scale (/= n (length scale)))
526 (error "scale not the same length as x"))
527 (let ((*maximize-callback-function* f)
528 (*maximize-callback-arg* (make-list n)))
529 (let ((hess-data (compound-data-seq (if all (third result) result)))
530 (px (la-data-to-vector x mode-re))
531 (pf (la-vector 1 mode-re))
532 (pgrad (la-vector n mode-re))
533 (phess (la-vector (* n n) mode-re))
534 (pscale (la-data-to-vector
535 (if scale scale (make-list n :initial-element 1.0))
536 mode-re)))
537 (unwind-protect
538 (progn
539 (numhess-front n px pf pgrad phess h pscale)
540 (when all
541 (setf (first result) (la-get-double pf 0))
542 (la-vector-to-data pgrad n mode-re (second result)))
543 (la-vector-to-data phess (* n n) mode-re hess-data))
544 (la-free-vector pf)
545 (la-free-vector px)
546 (la-free-vector pgrad)
547 (la-free-vector phess)
548 (la-free-vector pscale))))
549 result))