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.
8 (defpackage :lisp-stat-optimize
11 :lisp-stat-object-system
13 :lisp-stat-compound-data
18 :lisp-stat-linalg-data
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
)
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")
52 ;;; CFFI support using library for optimization work.
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
)
64 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs
))
66 (cffi:defcfun
("register_maximize_callback" register-maximize-callback
)
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
))
88 ;;;; minfo basics (internal??)
91 (defun init-minfo-ipar-values (n ipars
&key
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
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))
145 (let ((n (length x
)))
147 (check-sequence 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
)
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))
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
+)))
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
))
194 ;;;; Mode Info Prototype
197 (defproto minfo-proto
'(internals))
199 #+xlisp
(send minfo-proto
:add-method
:isnew
#'|minfo-isnew|
)
200 #+xlisp
(send minfo-proto
:add-method
:maximize
#'|minfo-maximize|
)
201 #+xlisp
(send minfo-proto
:add-method
:loglaplace
#'|minfo-loglap|
)
203 (defmeth minfo-proto
:isnew
(&rest args
)
204 (setf (slot-value 'internals
) (apply #'new-minfo-internals args
)))
206 (defmeth minfo-proto
:maximize
(&rest args
)
207 (apply #'minfo-maximize
(slot-value 'internals
) args
))
209 (defmeth minfo-proto
:x
() (aref (slot-value 'internals
) 3))
210 (defmeth minfo-proto
:scale
() (aref (slot-value 'internals
) 4))
211 (defmeth minfo-proto
:derivstep
() (aref (aref (slot-value 'internals
) 9) 1))
212 (defmeth minfo-proto
:tilt
() (aref (aref (slot-value 'internals
) 9) 6))
214 (defmeth minfo-proto
:f
(&optional
(val nil set
))
216 (send self
:set-no-vals-supplied
)
217 (setf (aref (slot-value 'internals
) 0) val
))
218 (aref (slot-value 'internals
) 0))
220 (defmeth minfo-proto
:set-no-vals-supplied
()
221 (setf (aref (aref (slot-value 'internals
) 8) 6) 0))
223 (defmeth minfo-proto
:exptilt
(&optional
(val nil set
))
225 (let ((old (send self
:exptilt
)))
226 (setf (aref (aref (slot-value 'internals
) 8) 7) (if val
1 0))
227 (if (and (not (or (and old val
) (and (not old
) (not val
))))
228 (/= (send self
:tilt
) 0.0))
229 (send self
:set-no-vals-supplied
))))
230 (= 1 (aref (aref (slot-value 'internals
) 8) 7)))
232 (defmeth minfo-proto
:newtilt
(&optional
(val nil set
))
234 (setf (aref (aref (slot-value 'internals
) 9) 7) (float val
))
235 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
236 (aref (aref (slot-value 'internals
) 9) 7))
238 (defmeth minfo-proto
:gfuns
(&optional
(val nil set
))
240 (if (or (not (consp val
))
241 (not (every #'functionp val
)))
242 (error "not all functions"))
243 (setf (aref (slot-value 'internals
) 1) val
)
244 (setf (aref (aref (slot-value 'internals
) 8) 1) (length val
))
245 (setf (aref (slot-value 'internals
) 10) (repeat 1.0 (length val
)))
246 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
247 (aref (slot-value 'internals
) 1))
249 (defmeth minfo-proto
:cfuns
(&optional
(val nil set
))
251 (if (or (not (consp val
))
252 (not (every #'functionp val
)))
253 (error "not all functions"))
254 (setf (aref (slot-value 'internals
) 2) val
)
255 (setf (aref (aref (slot-value 'internals
) 8) 2) (length val
))
256 (setf (aref (slot-value 'internals
) 7) (repeat 0.0 (length val
)))
257 (setf (aref (slot-value 'internals
) 11) (repeat 0.0 (length val
)))
258 (send self
:set-no-vals-supplied
))
259 (aref (slot-value 'internals
) 2))
261 (defmeth minfo-proto
:ctarget
(&optional
(val nil set
))
263 (if (/= (length val
) (length (send self
:ctarget
)))
264 (error "bad target length"))
265 (setf (aref (slot-value 'internals
) 7) val
))
266 (aref (slot-value 'internals
) 7))
268 (defmeth minfo-proto
:fvals
()
269 (let* ((fv (aref (slot-value 'internals
) 5))
270 (n (length (send self
:x
)))
272 (grad (select fv
(iseq 1 n
)))
273 (hess (matrix (list n n
) (select fv
(iseq (+ 1 n
) (+ n
(* n n
)))))))
274 (list val grad hess
)))
276 (defmeth minfo-proto
:copy
()
277 (let ((obj (make-object minfo-proto
))
278 (internals (copy-seq (slot-value 'internals
))))
279 (dotimes (i (length internals
))
280 (let ((x (aref internals i
)))
282 (setf (aref internals i
) (copy-seq x
)))))
283 (send obj
:add-slot
'internals internals
)
286 (defmeth minfo-proto
:derivscale
()
287 (let* ((step (^ machine-epsilon
(/ 1 6)))
288 (hess (numhess (send self
:f
) (send self
:x
) (send self
:scale
) step
))
289 (scale (pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
)))))))
290 (setf hess
(numhess (send self
:f
) (send self
:x
) scale step
))
291 (setf scale
(pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
))))))
292 (setf (aref (slot-value 'internals
) 4) scale
)
293 (setf (aref (aref (slot-value 'internals
) 9) 1) step
)))
295 (defmeth minfo-proto
:verbose
(&optional
(val nil set
))
297 (setf (aref (aref (slot-value 'internals
) 8) 5)
298 (cond ((integerp val
) val
)
301 (aref (aref (slot-value 'internals
) 8) 5))
303 (defmeth minfo-proto
:backtrack
(&optional
(val nil set
))
304 (if set
(setf (aref (aref (slot-value 'internals
) 8) 4) (if val
1 0)))
305 (aref (aref (slot-value 'internals
) 8) 4))
307 (defmeth minfo-proto
:maxiter
(&optional
(val nil set
))
308 (if set
(setf (aref (aref (slot-value 'internals
) 8) 3)
309 (if (integerp val
) val -
1)))
310 (aref (aref (slot-value 'internals
) 8) 3))
312 (defmeth minfo-proto
:tiltscale
(&optional
(val nil set
))
314 (if (/= (length val
) (length (send self
:gfuns
)))
315 (error "wrong size tilt scale sequence"))
316 (setf (aref (slot-value 'internals
) 10) val
))
317 (aref (slot-value 'internals
) 10))
321 ;;;; Newton's Method with Backtracking
325 (defun newtonmax (f start
&key
331 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
332 Maximizes F starting from START using Newton's method with backtracking.
333 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
334 list of location, unction value, gradient and hessian at maximum.
335 SCALE should be a list of the typical magnitudes of the parameters.
336 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
337 of iteration information. COUNT-LIMIT limits the number of iterations"
338 (let ((verbose (if verbose
(if (integerp verbose
) verbose
1) 0))
339 (minfo (send minfo-proto
:new f start
340 :scale scale
:derivstep derivstep
)))
341 (send minfo
:maxiter count-limit
)
342 (send minfo
:derivscale
)
343 (send minfo
:maximize verbose
)
345 (cons (send minfo
:x
) (- (send minfo
:fvals
)))
350 ;;;; Nelder-Mead Simplex Method
354 (defun nelmeadmax (f start
&key
356 (epsilon (sqrt machine-epsilon
))
363 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
364 (count-limit 500) (verbose t) alpha beta gamma delta)
365 Maximizes F using the Nelder-Mead simplex method. START can be a
366 starting simplex - a list of N+1 points, with N=dimension of problem,
367 or a single point. If start is a single point you should give the
368 size of the initial simplex as SIZE, a sequence of length N. Default is
369 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
370 control the behavior of simplex algorithm."
371 (let ((s (send simplex-proto
:new f start size
)))
372 (do ((best (send s
:best-point
) (send s
:best-point
))
373 (count 0 (+ count
1))
375 ((or (< (send s
:relative-range
) epsilon
) (>= count count-limit
))
376 (if (and verbose
(>= count count-limit
))
377 (format t
"Iteration limit exceeded.~%"))
378 (send s
:point-location
(send s
:best-point
)))
379 (setf next
(send s
:extrapolate-from-worst
(- alpha
)))
380 (if (send s
:is-worse best next
)
381 (setf next
(send s
:extrapolate-from-worst gamma
))
382 (when (send s
:is-worse next
(send s
:second-worst-point
))
383 (setf next
(send s
:extrapolate-from-worst beta
))
384 (if (send s
:is-worse next
(send s
:worst-point
))
385 (send s
:shrink-to-best delta
))))
387 (format t
"Value = ~10g~%"
388 (send s
:point-value
(send s
:best-point
)))))))
392 ;;; Simplex Prototype
395 (defproto simplex-proto
'(f simplex
))
401 (defmeth simplex-proto
:make-point
(x)
402 (let ((f (send self
:f
)))
404 (let ((val (funcall f x
)))
405 (cons (if (consp val
) (car val
) val
) x
))
408 (defmeth simplex-proto
:point-value
(x) (car x
))
410 (defmeth simplex-proto
:point-location
(x) (cdr x
))
412 (defmeth simplex-proto
:is-worse
(x y
)
413 (< (send self
:point-value x
) (send self
:point-value y
)))
416 ;;; Making New Simplices
419 (defmeth simplex-proto
:isnew
(f start
&optional size
)
420 (send self
:simplex start size
)
424 ;;; Slot Accessors and Mutators
427 (defmeth simplex-proto
:simplex
(&optional new size
)
430 (if (and (consp new
) (sequencep (car new
)))
431 (if (/= (length new
) (+ 1 (length (car new
))))
432 (error "bad simplex data")
434 (let* ((n (length new
))
435 (size (if size size
(repeat 1 n
)))
436 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
437 (diag (* 2 size
(- (random (repeat 2 n
)) .5)))
438 (pts (cons (repeat 0 n
)
439 (mapcar #'(lambda (x) (coerce x
'list
))
440 (column-list (diagonal diag
))))))
441 (mapcar #'(lambda (x) (reduce #'+ (list (* size x
) new
))) pts
)))))
442 (setf (slot-value 'simplex
)
443 (mapcar #'(lambda (x) (send self
:make-point x
)) simplex
))
444 (send self
:sort-simplex
)))
445 (slot-value 'simplex
))
447 (defmeth simplex-proto
:f
(&optional f
)
449 (setf (slot-value 'f
) f
)
451 (mapcar #'(lambda (x) (send self
:point-location x
))
452 (send self
:simplex
))))
453 (send self
:simplex simplex
)))
456 (defmeth simplex-proto
:sort-simplex
()
458 (setf (slot-value 'simplex
)
459 (sort (slot-value 'simplex
)
460 #'(lambda (x y
) (send self
:is-worse x y
))))))
463 ;;; Other Methods Using List Representation of SImplex
466 (defmeth simplex-proto
:best-point
() (car (last (send self
:simplex
))))
467 (defmeth simplex-proto
:worst-point
() (first (send self
:simplex
)))
468 (defmeth simplex-proto
:second-worst-point
() (second (send self
:simplex
)))
469 (defmeth simplex-proto
:replace-point
(new old
)
470 (let* ((simplex (send self
:simplex
))
471 (n (position old simplex
)))
473 (setf (nth n simplex
) new
)
474 (send self
:sort-simplex
))))
475 (defmeth simplex-proto
:mean-opposite-face
(x)
476 (let ((face (mapcar #'(lambda (x) (send self
:point-location x
))
477 (remove x
(send self
:simplex
)))))
478 (/ (reduce #'+ face
) (length face
))))
481 ;;; Iteration Step Methods
484 (defmeth simplex-proto
:extrapolate-from-worst
(fac)
485 (let* ((worst (send self
:worst-point
))
486 (wloc (send self
:point-location worst
))
487 (delta (- (send self
:mean-opposite-face worst
) wloc
))
488 (new (send self
:make-point
(+ wloc
(* (- 1 fac
) delta
)))))
489 (if (send self
:is-worse worst new
) (send self
:replace-point new worst
))
492 (defmeth simplex-proto
:shrink-to-best
(fac)
493 (let* ((best (send self
:best-point
))
494 (bloc (send self
:point-location best
)))
495 (dolist (x (copy-list (send self
:simplex
)))
496 (if (not (eq x best
))
497 (send self
:replace-point
498 (send self
:make-point
501 (- (send self
:point-location x
) bloc
))))
504 (defmeth simplex-proto
:relative-range
()
505 (let ((best (send self
:point-value
(send self
:best-point
)))
506 (worst (send self
:point-value
(send self
:worst-point
))))
507 (* 2 (/ (abs (- best worst
)) (+ 1 (abs best
) (abs worst
))))))
513 ;;;; Maximization and Numerical Derivatives
517 (defun data2double (n data ptr
)
519 (let* ((seq (compound-data-seq data
))
520 (elem (make-next-element seq
)))
521 (if (/= (length seq
) n
) (error "bad data size"))
524 (la-put-double ptr i
(get-next-element elem i
)))))
526 (defun maximize-callback (n px pfval pgrad phess pderivs
)
527 (la-vector-to-data px n
+mode-re
+ *maximize-callback-arg
*)
528 (let* ((val (funcall *maximize-callback-function
* *maximize-callback-arg
*))
529 (derivs (if (consp val
) (- (length val
) 1) 0)))
530 (la-put-integer pderivs
0 derivs
)
531 (la-put-double pfval
0 (if (consp val
) (first val
) val
))
532 (if (<= 1 derivs
) (data2double n
(second val
) pgrad
))
533 (if (<= 2 derivs
) (data2double (* n n
) (third val
) phess
))))
535 (defun numgrad (f x
&optional scale
(h -
1.0))
536 "Args: (f x &optional scale derivstep)
537 Computes the numerical gradient of F at X."
541 (check-sequence scale
)
544 (let* ((n (length x
))
545 (result (make-list n
)))
546 (if (and scale
(/= n
(length scale
)))
547 (error "scale not the same length as x"))
548 (let ((*maximize-callback-function
* f
)
549 (*maximize-callback-arg
* (make-list n
)))
550 (let ((px (la-data-to-vector x
+mode-re
+))
551 (pgrad (la-vector n
+mode-re
+))
552 (pscale (la-data-to-vector
553 (if scale scale
(make-list n
:initial-element
1.0))
557 (numgrad-front n px pgrad h pscale
)
558 (la-vector-to-data pgrad n
+mode-re
+ result
))
560 (la-free-vector pgrad
)
561 (la-free-vector pscale
))))
564 (defun numhess (f x
&optional scale
(h -
1.0) all
)
565 "Args: (f x &optional scale derivstep)
566 Computes the numerical Hessian matrix of F at X."
570 (check-sequence scale
)
573 (let* ((n (length x
))
575 (list nil
(make-list n
) (make-array (list n n
)))
576 (make-array (list n n
)))))
577 (if (and scale
(/= n
(length scale
)))
578 (error "scale not the same length as x"))
579 (let ((*maximize-callback-function
* f
)
580 (*maximize-callback-arg
* (make-list n
)))
581 (let ((hess-data (compound-data-seq (if all
(third result
) result
)))
582 (px (la-data-to-vector x
+mode-re
+))
583 (pf (la-vector 1 +mode-re
+))
584 (pgrad (la-vector n
+mode-re
+))
585 (phess (la-vector (* n n
) +mode-re
+))
586 (pscale (la-data-to-vector
587 (if scale scale
(make-list n
:initial-element
1.0))
591 (numhess-front n px pf pgrad phess h pscale
)
593 (setf (first result
) (la-get-double pf
0))
594 (la-vector-to-data pgrad n
+mode-re
+ (second result
)))
595 (la-vector-to-data phess
(* n n
) +mode-re
+ hess-data
))
598 (la-free-vector pgrad
)
599 (la-free-vector phess
)
600 (la-free-vector pscale
))))