Export matrix stuff properly (?).
[CommonLispStat.git] / optimize.lisp
blob642d512cdb718392f487616a7c302b2f0969de15
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-types
12 :lisp-stat-basics
13 :lisp-stat-matrix
14 :lisp-stat-linalg)
15 (:shadowing-import-from :lisp-stat-object-system
16 slot-value call-method call-next-method)
17 (:export
18 ;; derivatives
19 numgrad numhess
21 ;; optimization
22 newtonmax nelmeadmax))
26 ;;; FIXME:AJR: There is a need to figure out the proper symbols to
27 ;;; export. more importantly should there be any specialty package
28 z;;; that are exported for maximization?
30 (in-package :lisp-stat-optimize)
32 (defvar *maximize-callback-function* nil
33 "Used in generic optimization to determine function name -- symbol or string?")
35 (defvar *maximize-callback-arg* nil
36 "args to function to maximize")
39 ;;;
40 ;;; CFFI support using library for optimization work.
41 ;;;
43 ;; There is a problem with this particular approach, in terms of
44 ;; circular dependencies. We can not have this out-of-object call
45 ;; into optimize, at least not from here.
46 (cffi:defcallback ccl-maximize-callback :void ((n :int)
47 (px :pointer)
48 (pfval :pointer)
49 (pgrad :pointer)
50 (phess :pointer)
51 (pderivs :pointer))
52 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs))
54 (cffi:defcfun ("register_maximize_callback" register-maximize-callback)
55 :void (x :pointer))
56 (register-maximize-callback (cffi:callback ccl-maximize-callback))
58 (cffi:defcfun ("ccl_numgrad_front" ccl-numgrad-front)
59 :int (x :int) (y :pointer) (z :pointer) (u :double) (v :pointer))
60 (defun numgrad-front (x y z u v)
61 (ccl-numgrad-front x y z (float u 1d0) v))
63 (cffi:defcfun ("ccl_numhess_front" ccl-numhess-front)
64 :int (x :int) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :double) (a :pointer))
65 (defun numhess-front (x y z u v w a)
66 (ccl-numhess-front x y z u v (float w 1d0) a))
68 (cffi:defcfun ("ccl_minfo_maximize" ccl-minfo-maximize)
69 :int (x :pointer) (y :pointer) (z :pointer) (u :pointer) (v :pointer) (w :int))
70 (defun base-minfo-maximize (x y z u v w)
71 (ccl-minfo-maximize x y z u v w))
75 ;;;;
76 ;;;; minfo basics (internal??)
77 ;;;;
79 (defun init-minfo-ipar-values (n ipars &key
80 (TRUE 1)
81 (FALSE 0)
82 (k 0)
83 (m 0)
84 (itnlimit -1)
85 (backtrack TRUE)
86 (verbose 0)
87 (vals_suppl FALSE)
88 (exptilt TRUE)
89 (count 0)
90 (termcode 0))
91 "Initialize ipars (iteration parameters) by destructive modification."
92 (setf (aref ipars 0) n)
93 (setf (aref ipars 1) m)
94 (setf (aref ipars 2) k)
95 (setf (aref ipars 3) itnlimit)
96 (setf (aref ipars 4) backtrack)
97 (setf (aref ipars 5) verbose)
98 (setf (aref ipars 6) vals_suppl)
99 (setf (aref ipars 7) exptilt)
100 (setf (aref ipars 8) count)
101 (setf (aref ipars 9) termcode))
103 (defun init-minfo-dpar-values (h dpars &key
104 (typf 1.0)
105 (gradtol -1.0)
106 (steptol -1.0)
107 (maxstep -1.0)
108 (dflt 0.0)
109 (tilt 0.0)
110 (newtilt 0.0)
111 (hessadd 0.0))
112 "Initialize dpars (derivative parameters) by destructive modification."
113 (setf (aref dpars 0) typf)
114 (setf (aref dpars 1) h)
115 (setf (aref dpars 2) gradtol)
116 (setf (aref dpars 3) steptol)
117 (setf (aref dpars 4) maxstep)
118 (setf (aref dpars 5) dflt)
119 (setf (aref dpars 6) tilt)
120 (setf (aref dpars 7) newtilt)
121 (setf (aref dpars 8) hessadd))
123 (defun init-minfo-internals (n h internals)
124 (let ((ipars (aref internals 8))
125 (dpars (aref internals 9)))
126 (init-minfo-ipar-values n ipars)
127 (init-minfo-dpar-values h dpars)))
129 (defun new-minfo-internals (f x &key scale ((:derivstep h) -1.0))
130 (check-sequence x)
131 (check-real x)
132 (check-one-real h)
133 (let ((n (length x)))
134 (when scale
135 (check-sequence scale)
136 (check-real scale)
137 (if (/= n (length scale)) (error "scale and x not the same length")))
138 (let ((internals (make-array 12)))
139 (setf (aref internals 0) f)
140 (setf (aref internals 3) (if (consp x) (copy-list x) (coerce x 'list)))
141 (setf (aref internals 4)
142 (if scale (copy-seq scale) (make-array n :initial-element 1.0)))
143 (setf (aref internals 5) (make-list (+ 1 n (* n n))))
144 (setf (aref internals 8) (make-array 10))
145 (setf (aref internals 9) (make-array 9))
146 (init-minfo-internals n h internals)
147 internals)))
149 (defun minfo-maximize (internals &optional verbose)
150 "This function does what?"
151 (let* ((f (aref internals 0))
152 (x (aref internals 3))
153 (fvals (aref internals 5))
154 (n (length x))
155 (v (if verbose (if (integerp verbose) verbose 1) -1)))
156 (setf (aref internals 3) (copy-list x))
157 (setf (aref internals 5) (copy-list fvals))
158 (let ((*maximize-callback-function* f)
159 (*maximize-callback-arg* (make-list n)))
160 (let* ((x (aref internals 3))
161 (scale (aref internals 4))
162 (fvals (aref internals 5))
163 (ip (aref internals 8))
164 (dp (aref internals 9))
165 (px (la-data-to-vector x mode-re))
166 (pscale (la-data-to-vector scale mode-re))
167 (pfvals (la-vector (length fvals) mode-re))
168 (pip (la-data-to-vector ip mode-in))
169 (pdp (la-data-to-vector dp mode-re)))
170 (unwind-protect
171 (progn
172 (base-minfo-maximize px pfvals pscale pip pdp v)) ;; access to C
173 (la-vector-to-data px n mode-re x)
174 (la-vector-to-data pfvals (+ 1 n (* n n)) mode-re fvals)
175 (la-vector-to-data pip (length ip) mode-in ip)
176 (la-vector-to-data pdp (length dp) mode-re dp))
177 (get-buf)))))
181 ;;;;
182 ;;;; Mode Info Prototype
183 ;;;;
185 (defproto minfo-proto '(internals))
187 #+xlisp (send minfo-proto :add-method :isnew #'|minfo-isnew|)
188 #+xlisp (send minfo-proto :add-method :maximize #'|minfo-maximize|)
189 #+xlisp (send minfo-proto :add-method :loglaplace #'|minfo-loglap|)
190 #-xlisp
191 (defmeth minfo-proto :isnew (&rest args)
192 (setf (slot-value 'internals) (apply #'new-minfo-internals args)))
193 #-xlisp
194 (defmeth minfo-proto :maximize (&rest args)
195 (apply #'minfo-maximize (slot-value 'internals) args))
197 (defmeth minfo-proto :x () (aref (slot-value 'internals) 3))
198 (defmeth minfo-proto :scale () (aref (slot-value 'internals) 4))
199 (defmeth minfo-proto :derivstep () (aref (aref (slot-value 'internals) 9) 1))
200 (defmeth minfo-proto :tilt () (aref (aref (slot-value 'internals) 9) 6))
202 (defmeth minfo-proto :f (&optional (val nil set))
203 (when set
204 (send self :set-no-vals-supplied)
205 (setf (aref (slot-value 'internals) 0) val))
206 (aref (slot-value 'internals) 0))
208 (defmeth minfo-proto :set-no-vals-supplied ()
209 (setf (aref (aref (slot-value 'internals) 8) 6) 0))
211 (defmeth minfo-proto :exptilt (&optional (val nil set))
212 (if set
213 (let ((old (send self :exptilt)))
214 (setf (aref (aref (slot-value 'internals) 8) 7) (if val 1 0))
215 (if (and (not (or (and old val) (and (not old) (not val))))
216 (/= (send self :tilt) 0.0))
217 (send self :set-no-vals-supplied))))
218 (= 1 (aref (aref (slot-value 'internals) 8) 7)))
220 (defmeth minfo-proto :newtilt (&optional (val nil set))
221 (when set
222 (setf (aref (aref (slot-value 'internals) 9) 7) (float val))
223 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
224 (aref (aref (slot-value 'internals) 9) 7))
226 (defmeth minfo-proto :gfuns (&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) 1) val)
232 (setf (aref (aref (slot-value 'internals) 8) 1) (length val))
233 (setf (aref (slot-value 'internals) 10) (repeat 1.0 (length val)))
234 (if (/= (send self :tilt) 0.0) (send self :set-no-vals-supplied)))
235 (aref (slot-value 'internals) 1))
237 (defmeth minfo-proto :cfuns (&optional (val nil set))
238 (when set
239 (if (or (not (consp val))
240 (not (every #'functionp val)))
241 (error "not all functions"))
242 (setf (aref (slot-value 'internals) 2) val)
243 (setf (aref (aref (slot-value 'internals) 8) 2) (length val))
244 (setf (aref (slot-value 'internals) 7) (repeat 0.0 (length val)))
245 (setf (aref (slot-value 'internals) 11) (repeat 0.0 (length val)))
246 (send self :set-no-vals-supplied))
247 (aref (slot-value 'internals) 2))
249 (defmeth minfo-proto :ctarget (&optional (val nil set))
250 (when set
251 (if (/= (length val) (length (send self :ctarget)))
252 (error "bad target length"))
253 (setf (aref (slot-value 'internals) 7) val))
254 (aref (slot-value 'internals) 7))
256 (defmeth minfo-proto :fvals ()
257 (let* ((fv (aref (slot-value 'internals) 5))
258 (n (length (send self :x)))
259 (val (select fv 0))
260 (grad (select fv (iseq 1 n)))
261 (hess (matrix (list n n) (select fv (iseq (+ 1 n) (+ n (* n n)))))))
262 (list val grad hess)))
264 (defmeth minfo-proto :copy ()
265 (let ((obj (make-object minfo-proto))
266 (internals (copy-seq (slot-value 'internals))))
267 (dotimes (i (length internals))
268 (let ((x (aref internals i)))
269 (if (sequencep x)
270 (setf (aref internals i) (copy-seq x)))))
271 (send obj :add-slot 'internals internals)
272 obj))
274 (defmeth minfo-proto :derivscale ()
275 (let* ((step (^ machine-epsilon (/ 1 6)))
276 (hess (numhess (send self :f) (send self :x) (send self :scale) step))
277 (scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess)))))))
278 (setf hess (numhess (send self :f) (send self :x) scale step))
279 (setf scale (pmax (abs (send self :x)) (sqrt (abs (/ (diagonal hess))))))
280 (setf (aref (slot-value 'internals) 4) scale)
281 (setf (aref (aref (slot-value 'internals) 9) 1) step)))
283 (defmeth minfo-proto :verbose (&optional (val nil set))
284 (when set
285 (setf (aref (aref (slot-value 'internals) 8) 5)
286 (cond ((integerp val) val)
287 ((null val) 0)
288 (t 1))))
289 (aref (aref (slot-value 'internals) 8) 5))
291 (defmeth minfo-proto :backtrack (&optional (val nil set))
292 (if set (setf (aref (aref (slot-value 'internals) 8) 4) (if val 1 0)))
293 (aref (aref (slot-value 'internals) 8) 4))
295 (defmeth minfo-proto :maxiter (&optional (val nil set))
296 (if set (setf (aref (aref (slot-value 'internals) 8) 3)
297 (if (integerp val) val -1)))
298 (aref (aref (slot-value 'internals) 8) 3))
300 (defmeth minfo-proto :tiltscale (&optional (val nil set))
301 (when set
302 (if (/= (length val) (length (send self :gfuns)))
303 (error "wrong size tilt scale sequence"))
304 (setf (aref (slot-value 'internals) 10) val))
305 (aref (slot-value 'internals) 10))
307 ;;;;
308 ;;;;
309 ;;;; Newton's Method with Backtracking
310 ;;;;
311 ;;;;
313 (defun newtonmax (f start &key
314 scale
315 (derivstep -1.0)
316 (count-limit -1)
317 (verbose 1)
318 return-derivs)
319 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
320 Maximizes F starting from START using Newton's method with backtracking.
321 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
322 list of location, unction value, gradient and hessian at maximum.
323 SCALE should be a list of the typical magnitudes of the parameters.
324 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
325 of iteration information. COUNT-LIMIT limits the number of iterations"
326 (let ((verbose (if verbose (if (integerp verbose) verbose 1) 0))
327 (minfo (send minfo-proto :new f start
328 :scale scale :derivstep derivstep)))
329 (send minfo :maxiter count-limit)
330 (send minfo :derivscale)
331 (send minfo :maximize verbose)
332 (if return-derivs
333 (cons (send minfo :x) (- (send minfo :fvals)))
334 (send minfo :x))))
336 ;;;;
337 ;;;;
338 ;;;; Nelder-Mead Simplex Method
339 ;;;;
340 ;;;;
342 (defun nelmeadmax (f start &key
343 (size 1)
344 (epsilon (sqrt machine-epsilon))
345 (count-limit 500)
346 (verbose t)
347 (alpha 1.0)
348 (beta 0.5)
349 (gamma 2.0)
350 (delta 0.5))
351 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
352 (count-limit 500) (verbose t) alpha beta gamma delta)
353 Maximizes F using the Nelder-Mead simplex method. START can be a
354 starting simplex - a list of N+1 points, with N=dimension of problem,
355 or a single point. If start is a single point you should give the
356 size of the initial simplex as SIZE, a sequence of length N. Default is
357 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
358 control the behavior of simplex algorithm."
359 (let ((s (send simplex-proto :new f start size)))
360 (do ((best (send s :best-point) (send s :best-point))
361 (count 0 (+ count 1))
362 next)
363 ((or (< (send s :relative-range) epsilon) (>= count count-limit))
364 (if (and verbose (>= count count-limit))
365 (format t "Iteration limit exceeded.~%"))
366 (send s :point-location (send s :best-point)))
367 (setf next (send s :extrapolate-from-worst (- alpha)))
368 (if (send s :is-worse best next)
369 (setf next (send s :extrapolate-from-worst gamma))
370 (when (send s :is-worse next (send s :second-worst-point))
371 (setf next (send s :extrapolate-from-worst beta))
372 (if (send s :is-worse next (send s :worst-point))
373 (send s :shrink-to-best delta))))
374 (if verbose
375 (format t "Value = ~10g~%"
376 (send s :point-value (send s :best-point)))))))
380 ;;; Simplex Prototype
383 (defproto simplex-proto '(f simplex))
386 ;;; Simplex Points
389 (defmeth simplex-proto :make-point (x)
390 (let ((f (send self :f)))
391 (if f
392 (let ((val (funcall f x)))
393 (cons (if (consp val) (car val) val) x))
394 (cons nil x))))
396 (defmeth simplex-proto :point-value (x) (car x))
398 (defmeth simplex-proto :point-location (x) (cdr x))
400 (defmeth simplex-proto :is-worse (x y)
401 (< (send self :point-value x) (send self :point-value y)))
404 ;;; Making New Simplices
407 (defmeth simplex-proto :isnew (f start &optional size)
408 (send self :simplex start size)
409 (send self :f f))
412 ;;; Slot Accessors and Mutators
415 (defmeth simplex-proto :simplex (&optional new size)
416 (if new
417 (let ((simplex
418 (if (and (consp new) (sequencep (car new)))
419 (if (/= (length new) (+ 1 (length (car new))))
420 (error "bad simplex data")
421 (copy-list new))
422 (let* ((n (length new))
423 (size (if size size (repeat 1 n)))
424 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
425 (diag (* 2 size (- (random (repeat 2 n)) .5)))
426 (pts (cons (repeat 0 n)
427 (mapcar #'(lambda (x) (coerce x 'list))
428 (column-list (diagonal diag))))))
429 (mapcar #'(lambda (x) (reduce #'+ (list (* size x) new))) pts)))))
430 (setf (slot-value 'simplex)
431 (mapcar #'(lambda (x) (send self :make-point x)) simplex))
432 (send self :sort-simplex)))
433 (slot-value 'simplex))
435 (defmeth simplex-proto :f (&optional f)
436 (when f
437 (setf (slot-value 'f) f)
438 (let ((simplex
439 (mapcar #'(lambda (x) (send self :point-location x))
440 (send self :simplex))))
441 (send self :simplex simplex)))
442 (slot-value 'f))
444 (defmeth simplex-proto :sort-simplex ()
445 (if (send self :f)
446 (setf (slot-value 'simplex)
447 (sort (slot-value 'simplex)
448 #'(lambda (x y) (send self :is-worse x y))))))
451 ;;; Other Methods Using List Representation of SImplex
454 (defmeth simplex-proto :best-point () (car (last (send self :simplex))))
455 (defmeth simplex-proto :worst-point () (first (send self :simplex)))
456 (defmeth simplex-proto :second-worst-point () (second (send self :simplex)))
457 (defmeth simplex-proto :replace-point (new old)
458 (let* ((simplex (send self :simplex))
459 (n (position old simplex)))
460 (when n
461 (setf (nth n simplex) new)
462 (send self :sort-simplex))))
463 (defmeth simplex-proto :mean-opposite-face (x)
464 (let ((face (mapcar #'(lambda (x) (send self :point-location x))
465 (remove x (send self :simplex)))))
466 (/ (reduce #'+ face) (length face))))
469 ;;; Iteration Step Methods
472 (defmeth simplex-proto :extrapolate-from-worst (fac)
473 (let* ((worst (send self :worst-point))
474 (wloc (send self :point-location worst))
475 (delta (- (send self :mean-opposite-face worst) wloc))
476 (new (send self :make-point (+ wloc (* (- 1 fac) delta)))))
477 (if (send self :is-worse worst new) (send self :replace-point new worst))
478 new))
480 (defmeth simplex-proto :shrink-to-best (fac)
481 (let* ((best (send self :best-point))
482 (bloc (send self :point-location best)))
483 (dolist (x (copy-list (send self :simplex)))
484 (if (not (eq x best))
485 (send self :replace-point
486 (send self :make-point
487 (+ bloc
488 (* fac
489 (- (send self :point-location x) bloc))))
490 x)))))
492 (defmeth simplex-proto :relative-range ()
493 (let ((best (send self :point-value (send self :best-point)))
494 (worst (send self :point-value (send self :worst-point))))
495 (* 2 (/ (abs (- best worst)) (+ 1 (abs best) (abs worst))))))
500 ;;;;
501 ;;;; Maximization and Numerical Derivatives
502 ;;;;
505 (defun data2double (n data ptr)
506 (declare (fixnum n))
507 (let* ((seq (compound-data-seq data))
508 (elem (make-next-element seq)))
509 (if (/= (length seq) n) (error "bad data size"))
510 (dotimes (i n)
511 (declare (fixnum i))
512 (la-put-double ptr i (get-next-element elem i)))))
514 (defun maximize-callback (n px pfval pgrad phess pderivs)
515 (la-vector-to-data px n mode-re *maximize-callback-arg*)
516 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
517 (derivs (if (consp val) (- (length val) 1) 0)))
518 (la-put-integer pderivs 0 derivs)
519 (la-put-double pfval 0 (if (consp val) (first val) val))
520 (if (<= 1 derivs) (data2double n (second val) pgrad))
521 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
523 (defun numgrad (f x &optional scale (h -1.0))
524 "Args: (f x &optional scale derivstep)
525 Computes the numerical gradient of F at X."
526 (check-sequence x)
527 (check-real x)
528 (when scale
529 (check-sequence scale)
530 (check-real scale))
531 (check-one-real h)
532 (let* ((n (length x))
533 (result (make-list n)))
534 (if (and scale (/= n (length scale)))
535 (error "scale not the same length as x"))
536 (let ((*maximize-callback-function* f)
537 (*maximize-callback-arg* (make-list n)))
538 (let ((px (la-data-to-vector x mode-re))
539 (pgrad (la-vector n mode-re))
540 (pscale (la-data-to-vector
541 (if scale scale (make-list n :initial-element 1.0))
542 mode-re)))
543 (unwind-protect
544 (progn
545 (numgrad-front n px pgrad h pscale)
546 (la-vector-to-data pgrad n mode-re result))
547 (la-free-vector px)
548 (la-free-vector pgrad)
549 (la-free-vector pscale))))
550 result))
552 (defun numhess (f x &optional scale (h -1.0) all)
553 "Args: (f x &optional scale derivstep)
554 Computes the numerical Hessian matrix of F at X."
555 (check-sequence x)
556 (check-real x)
557 (when scale
558 (check-sequence scale)
559 (check-real scale))
560 (check-one-real h)
561 (let* ((n (length x))
562 (result (if all
563 (list nil (make-list n) (make-array (list n n)))
564 (make-array (list n n)))))
565 (if (and scale (/= n (length scale)))
566 (error "scale not the same length as x"))
567 (let ((*maximize-callback-function* f)
568 (*maximize-callback-arg* (make-list n)))
569 (let ((hess-data (compound-data-seq (if all (third result) result)))
570 (px (la-data-to-vector x mode-re))
571 (pf (la-vector 1 mode-re))
572 (pgrad (la-vector n mode-re))
573 (phess (la-vector (* n n) mode-re))
574 (pscale (la-data-to-vector
575 (if scale scale (make-list n :initial-element 1.0))
576 mode-re)))
577 (unwind-protect
578 (progn
579 (numhess-front n px pf pgrad phess h pscale)
580 (when all
581 (setf (first result) (la-get-double pf 0))
582 (la-vector-to-data pgrad n mode-re (second result)))
583 (la-vector-to-data phess (* n n) mode-re hess-data))
584 (la-free-vector pf)
585 (la-free-vector px)
586 (la-free-vector pgrad)
587 (la-free-vector phess)
588 (la-free-vector pscale))))
589 result))