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
198 (defproto minfo-proto
'(internals))
200 #+xlisp
(send minfo-proto
:add-method
:isnew
#'|minfo-isnew|
)
201 #+xlisp
(send minfo-proto
:add-method
:maximize
#'|minfo-maximize|
)
202 #+xlisp
(send minfo-proto
:add-method
:loglaplace
#'|minfo-loglap|
)
204 (defmeth minfo-proto
:isnew
(&rest args
)
205 (setf (slot-value 'internals
) (apply #'new-minfo-internals args
)))
207 (defmeth minfo-proto
:maximize
(&rest args
)
208 (apply #'minfo-maximize
(slot-value 'internals
) args
))
210 (defmeth minfo-proto
:x
() (aref (slot-value 'internals
) 3))
211 (defmeth minfo-proto
:scale
() (aref (slot-value 'internals
) 4))
212 (defmeth minfo-proto
:derivstep
() (aref (aref (slot-value 'internals
) 9) 1))
213 (defmeth minfo-proto
:tilt
() (aref (aref (slot-value 'internals
) 9) 6))
215 (defmeth minfo-proto
:f
(&optional
(val nil set
))
217 (send self
:set-no-vals-supplied
)
218 (setf (aref (slot-value 'internals
) 0) val
))
219 (aref (slot-value 'internals
) 0))
221 (defmeth minfo-proto
:set-no-vals-supplied
()
222 (setf (aref (aref (slot-value 'internals
) 8) 6) 0))
224 (defmeth minfo-proto
:exptilt
(&optional
(val nil set
))
226 (let ((old (send self
:exptilt
)))
227 (setf (aref (aref (slot-value 'internals
) 8) 7) (if val
1 0))
228 (if (and (not (or (and old val
) (and (not old
) (not val
))))
229 (/= (send self
:tilt
) 0.0))
230 (send self
:set-no-vals-supplied
))))
231 (= 1 (aref (aref (slot-value 'internals
) 8) 7)))
233 (defmeth minfo-proto
:newtilt
(&optional
(val nil set
))
235 (setf (aref (aref (slot-value 'internals
) 9) 7) (float val
))
236 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
237 (aref (aref (slot-value 'internals
) 9) 7))
239 (defmeth minfo-proto
:gfuns
(&optional
(val nil set
))
241 (if (or (not (consp val
))
242 (not (every #'functionp val
)))
243 (error "not all functions"))
244 (setf (aref (slot-value 'internals
) 1) val
)
245 (setf (aref (aref (slot-value 'internals
) 8) 1) (length val
))
246 (setf (aref (slot-value 'internals
) 10) (repeat 1.0 (length val
)))
247 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
248 (aref (slot-value 'internals
) 1))
250 (defmeth minfo-proto
:cfuns
(&optional
(val nil set
))
252 (if (or (not (consp val
))
253 (not (every #'functionp val
)))
254 (error "not all functions"))
255 (setf (aref (slot-value 'internals
) 2) val
)
256 (setf (aref (aref (slot-value 'internals
) 8) 2) (length val
))
257 (setf (aref (slot-value 'internals
) 7) (repeat 0.0 (length val
)))
258 (setf (aref (slot-value 'internals
) 11) (repeat 0.0 (length val
)))
259 (send self
:set-no-vals-supplied
))
260 (aref (slot-value 'internals
) 2))
262 (defmeth minfo-proto
:ctarget
(&optional
(val nil set
))
264 (if (/= (length val
) (length (send self
:ctarget
)))
265 (error "bad target length"))
266 (setf (aref (slot-value 'internals
) 7) val
))
267 (aref (slot-value 'internals
) 7))
269 (defmeth minfo-proto
:fvals
()
270 (let* ((fv (aref (slot-value 'internals
) 5))
271 (n (length (send self
:x
)))
273 (grad (select fv
(iseq 1 n
)))
274 (hess (matrix (list n n
) (select fv
(iseq (+ 1 n
) (+ n
(* n n
)))))))
275 (list val grad hess
)))
277 (defmeth minfo-proto
:copy
()
278 (let ((obj (make-object minfo-proto
))
279 (internals (copy-seq (slot-value 'internals
))))
280 (dotimes (i (length internals
))
281 (let ((x (aref internals i
)))
283 (setf (aref internals i
) (copy-seq x
)))))
284 (send obj
:add-slot
'internals internals
)
287 (defmeth minfo-proto
:derivscale
()
288 (let* ((step (^ machine-epsilon
(/ 1 6)))
289 (hess (numhess (send self
:f
) (send self
:x
) (send self
:scale
) step
))
290 (scale (pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
)))))))
291 (setf hess
(numhess (send self
:f
) (send self
:x
) scale step
))
292 (setf scale
(pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
))))))
293 (setf (aref (slot-value 'internals
) 4) scale
)
294 (setf (aref (aref (slot-value 'internals
) 9) 1) step
)))
296 (defmeth minfo-proto
:verbose
(&optional
(val nil set
))
298 (setf (aref (aref (slot-value 'internals
) 8) 5)
299 (cond ((integerp val
) val
)
302 (aref (aref (slot-value 'internals
) 8) 5))
304 (defmeth minfo-proto
:backtrack
(&optional
(val nil set
))
305 (if set
(setf (aref (aref (slot-value 'internals
) 8) 4) (if val
1 0)))
306 (aref (aref (slot-value 'internals
) 8) 4))
308 (defmeth minfo-proto
:maxiter
(&optional
(val nil set
))
309 (if set
(setf (aref (aref (slot-value 'internals
) 8) 3)
310 (if (integerp val
) val -
1)))
311 (aref (aref (slot-value 'internals
) 8) 3))
313 (defmeth minfo-proto
:tiltscale
(&optional
(val nil set
))
315 (if (/= (length val
) (length (send self
:gfuns
)))
316 (error "wrong size tilt scale sequence"))
317 (setf (aref (slot-value 'internals
) 10) val
))
318 (aref (slot-value 'internals
) 10))
322 ;;;; Newton's Method with Backtracking
326 (defun newtonmax (f start
&key
332 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
333 Maximizes F starting from START using Newton's method with backtracking.
334 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
335 list of location, unction value, gradient and hessian at maximum.
336 SCALE should be a list of the typical magnitudes of the parameters.
337 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
338 of iteration information. COUNT-LIMIT limits the number of iterations"
339 (let ((verbose (if verbose
(if (integerp verbose
) verbose
1) 0))
340 (minfo (send minfo-proto
:new f start
341 :scale scale
:derivstep derivstep
)))
342 (send minfo
:maxiter count-limit
)
343 (send minfo
:derivscale
)
344 (send minfo
:maximize verbose
)
346 (cons (send minfo
:x
) (- (send minfo
:fvals
)))
350 ;;; Nelder-Mead Simplex Method
353 ;;; Simplex Prototype
355 (defvar simplex-proto
)
356 (defproto simplex-proto
'(f simplex
))
358 (defun nelmeadmax (f start
&key
360 (epsilon (sqrt machine-epsilon
))
367 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
368 (count-limit 500) (verbose t) alpha beta gamma delta)
369 Maximizes F using the Nelder-Mead simplex method. START can be a
370 starting simplex - a list of N+1 points, with N=dimension of problem,
371 or a single point. If start is a single point you should give the
372 size of the initial simplex as SIZE, a sequence of length N. Default is
373 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
374 control the behavior of simplex algorithm."
375 (let ((s (send simplex-proto
:new f start size
)))
376 (do ((best (send s
:best-point
) (send s
:best-point
))
377 (count 0 (+ count
1))
379 ((or (< (send s
:relative-range
) epsilon
) (>= count count-limit
))
380 (if (and verbose
(>= count count-limit
))
381 (format t
"Iteration limit exceeded.~%"))
382 (send s
:point-location
(send s
:best-point
)))
383 (setf next
(send s
:extrapolate-from-worst
(- alpha
)))
384 (if (send s
:is-worse best next
)
385 (setf next
(send s
:extrapolate-from-worst gamma
))
386 (when (send s
:is-worse next
(send s
:second-worst-point
))
387 (setf next
(send s
:extrapolate-from-worst beta
))
388 (if (send s
:is-worse next
(send s
:worst-point
))
389 (send s
:shrink-to-best delta
))))
391 (format t
"Value = ~10g~%"
392 (send s
:point-value
(send s
:best-point
)))))))
400 (defmeth simplex-proto
:make-point
(x)
401 (let ((f (send self
:f
)))
403 (let ((val (funcall f x
)))
404 (cons (if (consp val
) (car val
) val
) x
))
407 (defmeth simplex-proto
:point-value
(x) (car x
))
409 (defmeth simplex-proto
:point-location
(x) (cdr x
))
411 (defmeth simplex-proto
:is-worse
(x y
)
412 (< (send self
:point-value x
) (send self
:point-value y
)))
415 ;;; Making New Simplices
418 (defmeth simplex-proto
:isnew
(f start
&optional size
)
419 (send self
:simplex start size
)
423 ;;; Slot Accessors and Mutators
426 (defmeth simplex-proto
:simplex
(&optional new size
)
429 (if (and (consp new
) (sequencep (car new
)))
430 (if (/= (length new
) (+ 1 (length (car new
))))
431 (error "bad simplex data")
433 (let* ((n (length new
))
434 (size (if size size
(repeat 1 n
)))
435 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
436 (diag (* 2 size
(- (random (repeat 2 n
)) .5)))
437 (pts (cons (repeat 0 n
)
438 (mapcar #'(lambda (x) (coerce x
'list
))
439 (column-list (diagonal diag
))))))
440 (mapcar #'(lambda (x) (reduce #'+ (list (* size x
) new
))) pts
)))))
441 (setf (slot-value 'simplex
)
442 (mapcar #'(lambda (x) (send self
:make-point x
)) simplex
))
443 (send self
:sort-simplex
)))
444 (slot-value 'simplex
))
446 (defmeth simplex-proto
:f
(&optional f
)
448 (setf (slot-value 'f
) f
)
450 (mapcar #'(lambda (x) (send self
:point-location x
))
451 (send self
:simplex
))))
452 (send self
:simplex simplex
)))
455 (defmeth simplex-proto
:sort-simplex
()
457 (setf (slot-value 'simplex
)
458 (sort (slot-value 'simplex
)
459 #'(lambda (x y
) (send self
:is-worse x y
))))))
462 ;;; Other Methods Using List Representation of SImplex
465 (defmeth simplex-proto
:best-point
() (car (last (send self
:simplex
))))
466 (defmeth simplex-proto
:worst-point
() (first (send self
:simplex
)))
467 (defmeth simplex-proto
:second-worst-point
() (second (send self
:simplex
)))
468 (defmeth simplex-proto
:replace-point
(new old
)
469 (let* ((simplex (send self
:simplex
))
470 (n (position old simplex
)))
472 (setf (nth n simplex
) new
)
473 (send self
:sort-simplex
))))
474 (defmeth simplex-proto
:mean-opposite-face
(x)
475 (let ((face (mapcar #'(lambda (x) (send self
:point-location x
))
476 (remove x
(send self
:simplex
)))))
477 (/ (reduce #'+ face
) (length face
))))
480 ;;; Iteration Step Methods
483 (defmeth simplex-proto
:extrapolate-from-worst
(fac)
484 (let* ((worst (send self
:worst-point
))
485 (wloc (send self
:point-location worst
))
486 (delta (- (send self
:mean-opposite-face worst
) wloc
))
487 (new (send self
:make-point
(+ wloc
(* (- 1 fac
) delta
)))))
488 (if (send self
:is-worse worst new
) (send self
:replace-point new worst
))
491 (defmeth simplex-proto
:shrink-to-best
(fac)
492 (let* ((best (send self
:best-point
))
493 (bloc (send self
:point-location best
)))
494 (dolist (x (copy-list (send self
:simplex
)))
495 (if (not (eq x best
))
496 (send self
:replace-point
497 (send self
:make-point
500 (- (send self
:point-location x
) bloc
))))
503 (defmeth simplex-proto
:relative-range
()
504 (let ((best (send self
:point-value
(send self
:best-point
)))
505 (worst (send self
:point-value
(send self
:worst-point
))))
506 (* 2 (/ (abs (- best worst
)) (+ 1 (abs best
) (abs worst
))))))
512 ;;;; Maximization and Numerical Derivatives
516 (defun data2double (n data ptr
)
518 (let* ((seq (compound-data-seq data
))
519 (elem (make-next-element seq
)))
520 (if (/= (length seq
) n
) (error "bad data size"))
523 (la-put-double ptr i
(get-next-element elem i
)))))
525 (defun maximize-callback (n px pfval pgrad phess pderivs
)
526 (la-vector-to-data px n
+mode-re
+ *maximize-callback-arg
*)
527 (let* ((val (funcall *maximize-callback-function
* *maximize-callback-arg
*))
528 (derivs (if (consp val
) (- (length val
) 1) 0)))
529 (la-put-integer pderivs
0 derivs
)
530 (la-put-double pfval
0 (if (consp val
) (first val
) val
))
531 (if (<= 1 derivs
) (data2double n
(second val
) pgrad
))
532 (if (<= 2 derivs
) (data2double (* n n
) (third val
) phess
))))
534 (defun numgrad (f x
&optional scale
(h -
1.0))
535 "Args: (f x &optional scale derivstep)
536 Computes the numerical gradient of F at X."
540 (check-sequence scale
)
543 (let* ((n (length x
))
544 (result (make-list n
)))
545 (if (and scale
(/= n
(length scale
)))
546 (error "scale not the same length as x"))
547 (let ((*maximize-callback-function
* f
)
548 (*maximize-callback-arg
* (make-list n
)))
549 (let ((px (la-data-to-vector x
+mode-re
+))
550 (pgrad (la-vector n
+mode-re
+))
551 (pscale (la-data-to-vector
552 (if scale scale
(make-list n
:initial-element
1.0))
556 (numgrad-front n px pgrad h pscale
)
557 (la-vector-to-data pgrad n
+mode-re
+ result
))
559 (la-free-vector pgrad
)
560 (la-free-vector pscale
))))
563 (defun numhess (f x
&optional scale
(h -
1.0) all
)
564 "Args: (f x &optional scale derivstep)
565 Computes the numerical Hessian matrix of F at X."
569 (check-sequence scale
)
572 (let* ((n (length x
))
574 (list nil
(make-list n
) (make-array (list n n
)))
575 (make-array (list n n
)))))
576 (if (and scale
(/= n
(length scale
)))
577 (error "scale not the same length as x"))
578 (let ((*maximize-callback-function
* f
)
579 (*maximize-callback-arg
* (make-list n
)))
580 (let ((hess-data (compound-data-seq (if all
(third result
) result
)))
581 (px (la-data-to-vector x
+mode-re
+))
582 (pf (la-vector 1 +mode-re
+))
583 (pgrad (la-vector n
+mode-re
+))
584 (phess (la-vector (* n n
) +mode-re
+))
585 (pscale (la-data-to-vector
586 (if scale scale
(make-list n
:initial-element
1.0))
590 (numhess-front n px pf pgrad phess h pscale
)
592 (setf (first result
) (la-get-double pf
0))
593 (la-vector-to-data pgrad n
+mode-re
+ (second result
)))
594 (la-vector-to-data phess
(* n n
) +mode-re
+ hess-data
))
597 (la-free-vector pgrad
)
598 (la-free-vector phess
)
599 (la-free-vector pscale
))))