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")
39 ;;;; minfo basics (internal??)
42 (defun init-minfo-ipar-values (n ipars
&key
54 "Initialize ipars (iteration parameters) by destructive modification."
55 (setf (aref ipars
0) n
)
56 (setf (aref ipars
1) m
)
57 (setf (aref ipars
2) k
)
58 (setf (aref ipars
3) itnlimit
)
59 (setf (aref ipars
4) backtrack
)
60 (setf (aref ipars
5) verbose
)
61 (setf (aref ipars
6) vals_suppl
)
62 (setf (aref ipars
7) exptilt
)
63 (setf (aref ipars
8) count
)
64 (setf (aref ipars
9) termcode
))
66 (defun init-minfo-dpar-values (h dpars
&key
75 "Initialize dpars (derivative parameters) by destructive modification."
76 (setf (aref dpars
0) typf
)
77 (setf (aref dpars
1) h
)
78 (setf (aref dpars
2) gradtol
)
79 (setf (aref dpars
3) steptol
)
80 (setf (aref dpars
4) maxstep
)
81 (setf (aref dpars
5) dflt
)
82 (setf (aref dpars
6) tilt
)
83 (setf (aref dpars
7) newtilt
)
84 (setf (aref dpars
8) hessadd
))
86 (defun init-minfo-internals (n h internals
)
87 (let ((ipars (aref internals
8))
88 (dpars (aref internals
9)))
89 (init-minfo-ipar-values n ipars
)
90 (init-minfo-dpar-values h dpars
)))
92 (defun new-minfo-internals (f x
&key scale
((:derivstep h
) -
1.0))
98 (check-sequence scale
)
100 (if (/= n
(length scale
)) (error "scale and x not the same length")))
101 (let ((internals (make-array 12)))
102 (setf (aref internals
0) f
)
103 (setf (aref internals
3) (if (consp x
) (copy-list x
) (coerce x
'list
)))
104 (setf (aref internals
4)
105 (if scale
(copy-seq scale
) (make-array n
:initial-element
1.0)))
106 (setf (aref internals
5) (make-list (+ 1 n
(* n n
))))
107 (setf (aref internals
8) (make-array 10))
108 (setf (aref internals
9) (make-array 9))
109 (init-minfo-internals n h internals
)
112 (defun minfo-maximize (internals &optional verbose
)
113 "This function does what?"
114 (let* ((f (aref internals
0))
115 (x (aref internals
3))
116 (fvals (aref internals
5))
118 (v (if verbose
(if (integerp verbose
) verbose
1) -
1)))
119 (setf (aref internals
3) (copy-list x
))
120 (setf (aref internals
5) (copy-list fvals
))
121 (let ((*maximize-callback-function
* f
)
122 (*maximize-callback-arg
* (make-list n
)))
123 (let* ((x (aref internals
3))
124 (scale (aref internals
4))
125 (fvals (aref internals
5))
126 (ip (aref internals
8))
127 (dp (aref internals
9))
128 (px (la-data-to-vector x mode-re
))
129 (pscale (la-data-to-vector scale mode-re
))
130 (pfvals (la-vector (length fvals
) mode-re
))
131 (pip (la-data-to-vector ip mode-in
))
132 (pdp (la-data-to-vector dp mode-re
)))
135 (base-minfo-maximize px pfvals pscale pip pdp v
)) ;; access to C
136 (la-vector-to-data px n mode-re x
)
137 (la-vector-to-data pfvals
(+ 1 n
(* n n
)) mode-re fvals
)
138 (la-vector-to-data pip
(length ip
) mode-in ip
)
139 (la-vector-to-data pdp
(length dp
) mode-re dp
))
145 ;;;; Mode Info Prototype
148 (defproto minfo-proto
'(internals))
150 #+xlisp
(send minfo-proto
:add-method
:isnew
#'|minfo-isnew|
)
151 #+xlisp
(send minfo-proto
:add-method
:maximize
#'|minfo-maximize|
)
152 #+xlisp
(send minfo-proto
:add-method
:loglaplace
#'|minfo-loglap|
)
154 (defmeth minfo-proto
:isnew
(&rest args
)
155 (setf (slot-value 'internals
) (apply #'new-minfo-internals args
)))
157 (defmeth minfo-proto
:maximize
(&rest args
)
158 (apply #'minfo-maximize
(slot-value 'internals
) args
))
160 (defmeth minfo-proto
:x
() (aref (slot-value 'internals
) 3))
161 (defmeth minfo-proto
:scale
() (aref (slot-value 'internals
) 4))
162 (defmeth minfo-proto
:derivstep
() (aref (aref (slot-value 'internals
) 9) 1))
163 (defmeth minfo-proto
:tilt
() (aref (aref (slot-value 'internals
) 9) 6))
165 (defmeth minfo-proto
:f
(&optional
(val nil set
))
167 (send self
:set-no-vals-supplied
)
168 (setf (aref (slot-value 'internals
) 0) val
))
169 (aref (slot-value 'internals
) 0))
171 (defmeth minfo-proto
:set-no-vals-supplied
()
172 (setf (aref (aref (slot-value 'internals
) 8) 6) 0))
174 (defmeth minfo-proto
:exptilt
(&optional
(val nil set
))
176 (let ((old (send self
:exptilt
)))
177 (setf (aref (aref (slot-value 'internals
) 8) 7) (if val
1 0))
178 (if (and (not (or (and old val
) (and (not old
) (not val
))))
179 (/= (send self
:tilt
) 0.0))
180 (send self
:set-no-vals-supplied
))))
181 (= 1 (aref (aref (slot-value 'internals
) 8) 7)))
183 (defmeth minfo-proto
:newtilt
(&optional
(val nil set
))
185 (setf (aref (aref (slot-value 'internals
) 9) 7) (float val
))
186 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
187 (aref (aref (slot-value 'internals
) 9) 7))
189 (defmeth minfo-proto
:gfuns
(&optional
(val nil set
))
191 (if (or (not (consp val
))
192 (not (every #'functionp val
)))
193 (error "not all functions"))
194 (setf (aref (slot-value 'internals
) 1) val
)
195 (setf (aref (aref (slot-value 'internals
) 8) 1) (length val
))
196 (setf (aref (slot-value 'internals
) 10) (repeat 1.0 (length val
)))
197 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
198 (aref (slot-value 'internals
) 1))
200 (defmeth minfo-proto
:cfuns
(&optional
(val nil set
))
202 (if (or (not (consp val
))
203 (not (every #'functionp val
)))
204 (error "not all functions"))
205 (setf (aref (slot-value 'internals
) 2) val
)
206 (setf (aref (aref (slot-value 'internals
) 8) 2) (length val
))
207 (setf (aref (slot-value 'internals
) 7) (repeat 0.0 (length val
)))
208 (setf (aref (slot-value 'internals
) 11) (repeat 0.0 (length val
)))
209 (send self
:set-no-vals-supplied
))
210 (aref (slot-value 'internals
) 2))
212 (defmeth minfo-proto
:ctarget
(&optional
(val nil set
))
214 (if (/= (length val
) (length (send self
:ctarget
)))
215 (error "bad target length"))
216 (setf (aref (slot-value 'internals
) 7) val
))
217 (aref (slot-value 'internals
) 7))
219 (defmeth minfo-proto
:fvals
()
220 (let* ((fv (aref (slot-value 'internals
) 5))
221 (n (length (send self
:x
)))
223 (grad (select fv
(iseq 1 n
)))
224 (hess (matrix (list n n
) (select fv
(iseq (+ 1 n
) (+ n
(* n n
)))))))
225 (list val grad hess
)))
227 (defmeth minfo-proto
:copy
()
228 (let ((obj (make-object minfo-proto
))
229 (internals (copy-seq (slot-value 'internals
))))
230 (dotimes (i (length internals
))
231 (let ((x (aref internals i
)))
233 (setf (aref internals i
) (copy-seq x
)))))
234 (send obj
:add-slot
'internals internals
)
237 (defmeth minfo-proto
:derivscale
()
238 (let* ((step (^ machine-epsilon
(/ 1 6)))
239 (hess (numhess (send self
:f
) (send self
:x
) (send self
:scale
) step
))
240 (scale (pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
)))))))
241 (setf hess
(numhess (send self
:f
) (send self
:x
) scale step
))
242 (setf scale
(pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
))))))
243 (setf (aref (slot-value 'internals
) 4) scale
)
244 (setf (aref (aref (slot-value 'internals
) 9) 1) step
)))
246 (defmeth minfo-proto
:verbose
(&optional
(val nil set
))
248 (setf (aref (aref (slot-value 'internals
) 8) 5)
249 (cond ((integerp val
) val
)
252 (aref (aref (slot-value 'internals
) 8) 5))
254 (defmeth minfo-proto
:backtrack
(&optional
(val nil set
))
255 (if set
(setf (aref (aref (slot-value 'internals
) 8) 4) (if val
1 0)))
256 (aref (aref (slot-value 'internals
) 8) 4))
258 (defmeth minfo-proto
:maxiter
(&optional
(val nil set
))
259 (if set
(setf (aref (aref (slot-value 'internals
) 8) 3)
260 (if (integerp val
) val -
1)))
261 (aref (aref (slot-value 'internals
) 8) 3))
263 (defmeth minfo-proto
:tiltscale
(&optional
(val nil set
))
265 (if (/= (length val
) (length (send self
:gfuns
)))
266 (error "wrong size tilt scale sequence"))
267 (setf (aref (slot-value 'internals
) 10) val
))
268 (aref (slot-value 'internals
) 10))
272 ;;;; Newton's Method with Backtracking
276 (defun newtonmax (f start
&key
282 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
283 Maximizes F starting from START using Newton's method with backtracking.
284 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
285 list of location, unction value, gradient and hessian at maximum.
286 SCALE should be a list of the typical magnitudes of the parameters.
287 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
288 of iteration information. COUNT-LIMIT limits the number of iterations"
289 (let ((verbose (if verbose
(if (integerp verbose
) verbose
1) 0))
290 (minfo (send minfo-proto
:new f start
291 :scale scale
:derivstep derivstep
)))
292 (send minfo
:maxiter count-limit
)
293 (send minfo
:derivscale
)
294 (send minfo
:maximize verbose
)
296 (cons (send minfo
:x
) (- (send minfo
:fvals
)))
301 ;;;; Nelder-Mead Simplex Method
305 (defun nelmeadmax (f start
&key
307 (epsilon (sqrt machine-epsilon
))
314 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
315 (count-limit 500) (verbose t) alpha beta gamma delta)
316 Maximizes F using the Nelder-Mead simplex method. START can be a
317 starting simplex - a list of N+1 points, with N=dimension of problem,
318 or a single point. If start is a single point you should give the
319 size of the initial simplex as SIZE, a sequence of length N. Default is
320 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
321 control the behavior of simplex algorithm."
322 (let ((s (send simplex-proto
:new f start size
)))
323 (do ((best (send s
:best-point
) (send s
:best-point
))
324 (count 0 (+ count
1))
326 ((or (< (send s
:relative-range
) epsilon
) (>= count count-limit
))
327 (if (and verbose
(>= count count-limit
))
328 (format t
"Iteration limit exceeded.~%"))
329 (send s
:point-location
(send s
:best-point
)))
330 (setf next
(send s
:extrapolate-from-worst
(- alpha
)))
331 (if (send s
:is-worse best next
)
332 (setf next
(send s
:extrapolate-from-worst gamma
))
333 (when (send s
:is-worse next
(send s
:second-worst-point
))
334 (setf next
(send s
:extrapolate-from-worst beta
))
335 (if (send s
:is-worse next
(send s
:worst-point
))
336 (send s
:shrink-to-best delta
))))
338 (format t
"Value = ~10g~%"
339 (send s
:point-value
(send s
:best-point
)))))))
343 ;;; Simplex Prototype
346 (defproto simplex-proto
'(f simplex
))
352 (defmeth simplex-proto
:make-point
(x)
353 (let ((f (send self
:f
)))
355 (let ((val (funcall f x
)))
356 (cons (if (consp val
) (car val
) val
) x
))
359 (defmeth simplex-proto
:point-value
(x) (car x
))
361 (defmeth simplex-proto
:point-location
(x) (cdr x
))
363 (defmeth simplex-proto
:is-worse
(x y
)
364 (< (send self
:point-value x
) (send self
:point-value y
)))
367 ;;; Making New Simplices
370 (defmeth simplex-proto
:isnew
(f start
&optional size
)
371 (send self
:simplex start size
)
375 ;;; Slot Accessors and Mutators
378 (defmeth simplex-proto
:simplex
(&optional new size
)
381 (if (and (consp new
) (sequencep (car new
)))
382 (if (/= (length new
) (+ 1 (length (car new
))))
383 (error "bad simplex data")
385 (let* ((n (length new
))
386 (size (if size size
(repeat 1 n
)))
387 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
388 (diag (* 2 size
(- (random (repeat 2 n
)) .5)))
389 (pts (cons (repeat 0 n
)
390 (mapcar #'(lambda (x) (coerce x
'list
))
391 (column-list (diagonal diag
))))))
392 (mapcar #'(lambda (x) (reduce #'+ (list (* size x
) new
))) pts
)))))
393 (setf (slot-value 'simplex
)
394 (mapcar #'(lambda (x) (send self
:make-point x
)) simplex
))
395 (send self
:sort-simplex
)))
396 (slot-value 'simplex
))
398 (defmeth simplex-proto
:f
(&optional f
)
400 (setf (slot-value 'f
) f
)
402 (mapcar #'(lambda (x) (send self
:point-location x
))
403 (send self
:simplex
))))
404 (send self
:simplex simplex
)))
407 (defmeth simplex-proto
:sort-simplex
()
409 (setf (slot-value 'simplex
)
410 (sort (slot-value 'simplex
)
411 #'(lambda (x y
) (send self
:is-worse x y
))))))
414 ;;; Other Methods Using List Representation of SImplex
417 (defmeth simplex-proto
:best-point
() (car (last (send self
:simplex
))))
418 (defmeth simplex-proto
:worst-point
() (first (send self
:simplex
)))
419 (defmeth simplex-proto
:second-worst-point
() (second (send self
:simplex
)))
420 (defmeth simplex-proto
:replace-point
(new old
)
421 (let* ((simplex (send self
:simplex
))
422 (n (position old simplex
)))
424 (setf (nth n simplex
) new
)
425 (send self
:sort-simplex
))))
426 (defmeth simplex-proto
:mean-opposite-face
(x)
427 (let ((face (mapcar #'(lambda (x) (send self
:point-location x
))
428 (remove x
(send self
:simplex
)))))
429 (/ (reduce #'+ face
) (length face
))))
432 ;;; Iteration Step Methods
435 (defmeth simplex-proto
:extrapolate-from-worst
(fac)
436 (let* ((worst (send self
:worst-point
))
437 (wloc (send self
:point-location worst
))
438 (delta (- (send self
:mean-opposite-face worst
) wloc
))
439 (new (send self
:make-point
(+ wloc
(* (- 1 fac
) delta
)))))
440 (if (send self
:is-worse worst new
) (send self
:replace-point new worst
))
443 (defmeth simplex-proto
:shrink-to-best
(fac)
444 (let* ((best (send self
:best-point
))
445 (bloc (send self
:point-location best
)))
446 (dolist (x (copy-list (send self
:simplex
)))
447 (if (not (eq x best
))
448 (send self
:replace-point
449 (send self
:make-point
452 (- (send self
:point-location x
) bloc
))))
455 (defmeth simplex-proto
:relative-range
()
456 (let ((best (send self
:point-value
(send self
:best-point
)))
457 (worst (send self
:point-value
(send self
:worst-point
))))
458 (* 2 (/ (abs (- best worst
)) (+ 1 (abs best
) (abs worst
))))))
464 ;;;; Maximization and Numerical Derivatives
468 (defun data2double (n data ptr
)
470 (let* ((seq (compound-data-seq data
))
471 (elem (make-next-element seq
)))
472 (if (/= (length seq
) n
) (error "bad data size"))
475 (la-put-double ptr i
(get-next-element elem i
)))))
477 (defun maximize-callback (n px pfval pgrad phess pderivs
)
478 (la-vector-to-data px n mode-re
*maximize-callback-arg
*)
479 (let* ((val (funcall *maximize-callback-function
* *maximize-callback-arg
*))
480 (derivs (if (consp val
) (- (length val
) 1) 0)))
481 (la-put-integer pderivs
0 derivs
)
482 (la-put-double pfval
0 (if (consp val
) (first val
) val
))
483 (if (<= 1 derivs
) (data2double n
(second val
) pgrad
))
484 (if (<= 2 derivs
) (data2double (* n n
) (third val
) phess
))))
486 (defun numgrad (f x
&optional scale
(h -
1.0))
487 "Args: (f x &optional scale derivstep)
488 Computes the numerical gradient of F at X."
492 (check-sequence scale
)
495 (let* ((n (length x
))
496 (result (make-list n
)))
497 (if (and scale
(/= n
(length scale
)))
498 (error "scale not the same length as x"))
499 (let ((*maximize-callback-function
* f
)
500 (*maximize-callback-arg
* (make-list n
)))
501 (let ((px (la-data-to-vector x mode-re
))
502 (pgrad (la-vector n mode-re
))
503 (pscale (la-data-to-vector
504 (if scale scale
(make-list n
:initial-element
1.0))
508 (numgrad-front n px pgrad h pscale
)
509 (la-vector-to-data pgrad n mode-re result
))
511 (la-free-vector pgrad
)
512 (la-free-vector pscale
))))
515 (defun numhess (f x
&optional scale
(h -
1.0) all
)
516 "Args: (f x &optional scale derivstep)
517 Computes the numerical Hessian matrix of F at X."
521 (check-sequence scale
)
524 (let* ((n (length x
))
526 (list nil
(make-list n
) (make-array (list n n
)))
527 (make-array (list n n
)))))
528 (if (and scale
(/= n
(length scale
)))
529 (error "scale not the same length as x"))
530 (let ((*maximize-callback-function
* f
)
531 (*maximize-callback-arg
* (make-list n
)))
532 (let ((hess-data (compound-data-seq (if all
(third result
) result
)))
533 (px (la-data-to-vector x mode-re
))
534 (pf (la-vector 1 mode-re
))
535 (pgrad (la-vector n mode-re
))
536 (phess (la-vector (* n n
) mode-re
))
537 (pscale (la-data-to-vector
538 (if scale scale
(make-list n
:initial-element
1.0))
542 (numhess-front n px pf pgrad phess h pscale
)
544 (setf (first result
) (la-get-double pf
0))
545 (la-vector-to-data pgrad n mode-re
(second result
)))
546 (la-vector-to-data phess
(* n n
) mode-re hess-data
))
549 (la-free-vector pgrad
)
550 (la-free-vector phess
)
551 (la-free-vector pscale
))))