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