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
10 :lisp-stat-object-system
15 (:shadowing-import-from
:lisp-stat-object-system
16 slot-value call-method call-next-method
)
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")
40 ;;; CFFI support using library for optimization work.
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
)
52 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs
))
54 (cffi:defcfun
("register_maximize_callback" register-maximize-callback
)
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
))
76 ;;;; minfo basics (internal??)
79 (defun init-minfo-ipar-values (n ipars
&key
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
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))
133 (let ((n (length x
)))
135 (check-sequence 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
)
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))
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
)))
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
))
182 ;;;; Mode Info Prototype
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|
)
191 (defmeth minfo-proto
:isnew
(&rest args
)
192 (setf (slot-value 'internals
) (apply #'new-minfo-internals args
)))
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
))
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
))
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
))
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
))
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
))
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
))
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
)))
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
)))
270 (setf (aref internals i
) (copy-seq x
)))))
271 (send obj
:add-slot
'internals internals
)
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
))
285 (setf (aref (aref (slot-value 'internals
) 8) 5)
286 (cond ((integerp val
) val
)
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
))
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))
309 ;;;; Newton's Method with Backtracking
313 (defun newtonmax (f start
&key
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
)
333 (cons (send minfo
:x
) (- (send minfo
:fvals
)))
338 ;;;; Nelder-Mead Simplex Method
342 (defun nelmeadmax (f start
&key
344 (epsilon (sqrt machine-epsilon
))
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))
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
))))
375 (format t
"Value = ~10g~%"
376 (send s
:point-value
(send s
:best-point
)))))))
380 ;;; Simplex Prototype
383 (defproto simplex-proto
'(f simplex
))
389 (defmeth simplex-proto
:make-point
(x)
390 (let ((f (send self
:f
)))
392 (let ((val (funcall f x
)))
393 (cons (if (consp val
) (car val
) val
) 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
)
412 ;;; Slot Accessors and Mutators
415 (defmeth simplex-proto
:simplex
(&optional new size
)
418 (if (and (consp new
) (sequencep (car new
)))
419 (if (/= (length new
) (+ 1 (length (car new
))))
420 (error "bad simplex data")
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
)
437 (setf (slot-value 'f
) f
)
439 (mapcar #'(lambda (x) (send self
:point-location x
))
440 (send self
:simplex
))))
441 (send self
:simplex simplex
)))
444 (defmeth simplex-proto
:sort-simplex
()
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
)))
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
))
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
489 (- (send self
:point-location x
) bloc
))))
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
))))))
501 ;;;; Maximization and Numerical Derivatives
505 (defun data2double (n data ptr
)
507 (let* ((seq (compound-data-seq data
))
508 (elem (make-next-element seq
)))
509 (if (/= (length seq
) n
) (error "bad data size"))
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."
529 (check-sequence scale
)
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))
545 (numgrad-front n px pgrad h pscale
)
546 (la-vector-to-data pgrad n mode-re result
))
548 (la-free-vector pgrad
)
549 (la-free-vector pscale
))))
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."
558 (check-sequence scale
)
561 (let* ((n (length x
))
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))
579 (numhess-front n px pf pgrad phess h pscale
)
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
))
586 (la-free-vector pgrad
)
587 (la-free-vector phess
)
588 (la-free-vector pscale
))))