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.
7 ;; matrix is in statistics, but should that be a predecessor?
9 ;;; FIXME:AJR: There is a need to figure out the proper symbols to
10 ;;; export. more importantly should there be any specialty package
11 ;;; that are exported for maximization?
13 (in-package :lisp-stat-optimize
)
16 (defctype size-t
:unsigned-long
)
18 (defctype size-t
:unsigned-int
)
20 (defvar *maximize-callback-function
* nil
21 "Used in generic optimization to determine function name -- symbol or string?")
23 (defvar *maximize-callback-arg
* nil
24 "args to function to maximize")
28 ;;; CFFI support using library for optimization work.
31 ;; There is a problem with this particular approach, in terms of
32 ;; circular dependencies. We can not have this out-of-object call
33 ;; into optimize, at least not from here.
34 (cffi:defcallback ccl-maximize-callback
:void
((n :int
)
40 (lisp-stat-optimize::maximize-callback n px pfval pgrad phess pderivs
))
42 (cffi:defcfun
("register_maximize_callback" register-maximize-callback
)
44 (register-maximize-callback (cffi:callback ccl-maximize-callback
))
46 (cffi:defcfun
("ccl_numgrad_front" ccl-numgrad-front
)
47 :void
(x size-t
) (y :pointer
) (z :pointer
) (u :double
) (v :pointer
))
48 (defun numgrad-front (x y z u v
)
49 (ccl-numgrad-front x y z
(float u
1d0
) v
))
51 (cffi:defcfun
("ccl_numhess_front" ccl-numhess-front
)
52 :void
(x size-t
) (y :pointer
) (z :pointer
) (u :pointer
) (v :pointer
) (w :double
) (a :pointer
))
53 (defun numhess-front (x y z u v w a
)
54 (ccl-numhess-front x y z u v
(float w
1d0
) a
))
56 (cffi:defcfun
("ccl_minfo_maximize" ccl-minfo-maximize
)
57 :void
(x :pointer
) (y :pointer
) (z :pointer
) (u :pointer
) (v :pointer
) (w :int
))
58 (defun base-minfo-maximize (x y z u v w
)
59 (ccl-minfo-maximize x y z u v w
))
64 ;;;; minfo basics (internal??)
67 (defun init-minfo-ipar-values (n ipars
&key
79 "Initialize ipars (iteration parameters) by destructive modification."
80 (setf (aref ipars
0) n
)
81 (setf (aref ipars
1) m
)
82 (setf (aref ipars
2) k
)
83 (setf (aref ipars
3) itnlimit
)
84 (setf (aref ipars
4) backtrack
)
85 (setf (aref ipars
5) verbose
)
86 (setf (aref ipars
6) vals_suppl
)
87 (setf (aref ipars
7) exptilt
)
88 (setf (aref ipars
8) count
)
89 (setf (aref ipars
9) termcode
))
91 (defun init-minfo-dpar-values (h dpars
&key
100 "Initialize dpars (derivative parameters) by destructive modification."
101 (setf (aref dpars
0) typf
)
102 (setf (aref dpars
1) h
)
103 (setf (aref dpars
2) gradtol
)
104 (setf (aref dpars
3) steptol
)
105 (setf (aref dpars
4) maxstep
)
106 (setf (aref dpars
5) dflt
)
107 (setf (aref dpars
6) tilt
)
108 (setf (aref dpars
7) newtilt
)
109 (setf (aref dpars
8) hessadd
))
111 (defun init-minfo-internals (n h internals
)
112 (let ((ipars (aref internals
8))
113 (dpars (aref internals
9)))
114 (init-minfo-ipar-values n ipars
)
115 (init-minfo-dpar-values h dpars
)))
117 (defun new-minfo-internals (f x
&key scale
((:derivstep h
) -
1.0))
119 (check-real x
) ;; becomes:
120 ;; (assert (reduce #'and (map #'(lambda (x) (or (typep x 'real) (typep x 'double)) x))) "x not real seq")
122 (let ((n (length x
)))
124 (check-sequence scale
)
126 (if (/= n
(length scale
)) (error "scale and x not the same length")))
127 (let ((internals (make-array 12)))
128 (setf (aref internals
0) f
)
129 (setf (aref internals
3) (if (consp x
) (copy-list x
) (coerce x
'list
)))
130 (setf (aref internals
4)
131 (if scale
(copy-seq scale
) (make-array n
:initial-element
1.0)))
132 (setf (aref internals
5) (make-list (+ 1 n
(* n n
))))
133 (setf (aref internals
8) (make-array 10))
134 (setf (aref internals
9) (make-array 9))
135 (init-minfo-internals n h internals
)
138 (defun minfo-maximize (internals &optional verbose
)
139 "This function does what?"
140 (let* ((f (aref internals
0))
141 (x (aref internals
3))
142 (fvals (aref internals
5))
144 (v (if verbose
(if (integerp verbose
) verbose
1) -
1)))
145 (setf (aref internals
3) (copy-list x
))
146 (setf (aref internals
5) (copy-list fvals
))
147 (let ((*maximize-callback-function
* f
)
148 (*maximize-callback-arg
* (make-list n
)))
149 (let* ((x (aref internals
3))
150 (scale (aref internals
4))
151 (fvals (aref internals
5))
152 (ip (aref internals
8))
153 (dp (aref internals
9))
154 (px (la-data-to-vector x
+mode-re
+))
155 (pscale (la-data-to-vector scale
+mode-re
+))
156 (pfvals (la-vector (length fvals
) +mode-re
+))
157 (pip (la-data-to-vector ip
+mode-in
+))
158 (pdp (la-data-to-vector dp
+mode-re
+)))
161 (base-minfo-maximize px pfvals pscale pip pdp v
)) ;; access to C
162 (la-vector-to-data px n
+mode-re
+ x
)
163 (la-vector-to-data pfvals
(+ 1 n
(* n n
)) +mode-re
+ fvals
)
164 (la-vector-to-data pip
(length ip
) +mode-in
+ ip
)
165 (la-vector-to-data pdp
(length dp
) +mode-re
+ dp
))
171 ;;;; Mode Info Prototype
175 (defproto minfo-proto
'(internals))
177 #+xlisp
(send minfo-proto
:add-method
:isnew
#'|minfo-isnew|
)
178 #+xlisp
(send minfo-proto
:add-method
:maximize
#'|minfo-maximize|
)
179 #+xlisp
(send minfo-proto
:add-method
:loglaplace
#'|minfo-loglap|
)
181 (defmeth minfo-proto
:isnew
(&rest args
)
182 (setf (proto-slot-value 'internals
) (apply #'new-minfo-internals args
)))
184 (defmeth minfo-proto
:maximize
(&rest args
)
185 (apply #'minfo-maximize
(proto-slot-value 'internals
) args
))
187 (defmeth minfo-proto
:x
() (aref (proto-slot-value 'internals
) 3))
188 (defmeth minfo-proto
:scale
() (aref (proto-slot-value 'internals
) 4))
189 (defmeth minfo-proto
:derivstep
() (aref (aref (proto-slot-value 'internals
) 9) 1))
190 (defmeth minfo-proto
:tilt
() (aref (aref (proto-slot-value 'internals
) 9) 6))
192 (defmeth minfo-proto
:f
(&optional
(val nil set
))
194 (send self
:set-no-vals-supplied
)
195 (setf (aref (proto-slot-value 'internals
) 0) val
))
196 (aref (proto-slot-value 'internals
) 0))
198 (defmeth minfo-proto
:set-no-vals-supplied
()
199 (setf (aref (aref (proto-slot-value 'internals
) 8) 6) 0))
201 (defmeth minfo-proto
:exptilt
(&optional
(val nil set
))
203 (let ((old (send self
:exptilt
)))
204 (setf (aref (aref (proto-slot-value 'internals
) 8) 7) (if val
1 0))
205 (if (and (not (or (and old val
) (and (not old
) (not val
))))
206 (/= (send self
:tilt
) 0.0))
207 (send self
:set-no-vals-supplied
))))
208 (= 1 (aref (aref (proto-slot-value 'internals
) 8) 7)))
210 (defmeth minfo-proto
:newtilt
(&optional
(val nil set
))
212 (setf (aref (aref (proto-slot-value 'internals
) 9) 7) (float val
))
213 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
214 (aref (aref (proto-slot-value 'internals
) 9) 7))
216 (defmeth minfo-proto
:gfuns
(&optional
(val nil set
))
218 (if (or (not (consp val
))
219 (not (every #'functionp val
)))
220 (error "not all functions"))
221 (setf (aref (proto-slot-value 'internals
) 1) val
)
222 (setf (aref (aref (proto-slot-value 'internals
) 8) 1) (length val
))
223 (setf (aref (proto-slot-value 'internals
) 10) (repeat 1.0 (length val
)))
224 (if (/= (send self
:tilt
) 0.0) (send self
:set-no-vals-supplied
)))
225 (aref (proto-slot-value 'internals
) 1))
227 (defmeth minfo-proto
:cfuns
(&optional
(val nil set
))
229 (if (or (not (consp val
))
230 (not (every #'functionp val
)))
231 (error "not all functions"))
232 (setf (aref (proto-slot-value 'internals
) 2) val
)
233 (setf (aref (aref (proto-slot-value 'internals
) 8) 2) (length val
))
234 (setf (aref (proto-slot-value 'internals
) 7) (repeat 0.0 (length val
)))
235 (setf (aref (proto-slot-value 'internals
) 11) (repeat 0.0 (length val
)))
236 (send self
:set-no-vals-supplied
))
237 (aref (proto-slot-value 'internals
) 2))
239 (defmeth minfo-proto
:ctarget
(&optional
(val nil set
))
241 (if (/= (length val
) (length (send self
:ctarget
)))
242 (error "bad target length"))
243 (setf (aref (proto-slot-value 'internals
) 7) val
))
244 (aref (proto-slot-value 'internals
) 7))
246 (defmeth minfo-proto
:fvals
()
247 (let* ((fv (aref (proto-slot-value 'internals
) 5))
248 (n (length (send self
:x
)))
250 (grad (select fv
(iseq 1 n
)))
251 (hess (matrix (list n n
) (select fv
(iseq (+ 1 n
) (+ n
(* n n
)))))))
252 (list val grad hess
)))
254 (defmeth minfo-proto
:copy
()
257 Make a copy of an minfo instance."
258 (let ((obj (make-object minfo-proto
))
259 (internals (copy-seq (proto-slot-value 'internals
))))
260 (dotimes (i (length internals
))
261 (let ((x (aref internals i
)))
262 (if (typep x
'sequence
)
263 (setf (aref internals i
) (copy-seq x
)))))
264 (send obj
:add-slot
'internals internals
)
267 (defmeth minfo-proto
:derivscale
()
268 (let* ((step (^ machine-epsilon
(/ 1 6)))
269 (hess (numhess (send self
:f
) (send self
:x
) (send self
:scale
) step
))
270 (scale (pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
)))))))
271 (setf hess
(numhess (send self
:f
) (send self
:x
) scale step
))
272 (setf scale
(pmax (abs (send self
:x
)) (sqrt (abs (/ (diagonal hess
))))))
273 (setf (aref (proto-slot-value 'internals
) 4) scale
)
274 (setf (aref (aref (proto-slot-value 'internals
) 9) 1) step
)))
276 (defmeth minfo-proto
:verbose
(&optional
(val nil set
))
278 (setf (aref (aref (proto-slot-value 'internals
) 8) 5)
279 (cond ((integerp val
) val
)
282 (aref (aref (proto-slot-value 'internals
) 8) 5))
284 (defmeth minfo-proto
:backtrack
(&optional
(val nil set
))
285 (if set
(setf (aref (aref (proto-slot-value 'internals
) 8) 4) (if val
1 0)))
286 (aref (aref (proto-slot-value 'internals
) 8) 4))
288 (defmeth minfo-proto
:maxiter
(&optional
(val nil set
))
289 (if set
(setf (aref (aref (proto-slot-value 'internals
) 8) 3)
290 (if (integerp val
) val -
1)))
291 (aref (aref (proto-slot-value 'internals
) 8) 3))
293 (defmeth minfo-proto
:tiltscale
(&optional
(val nil set
))
295 (if (/= (length val
) (length (send self
:gfuns
)))
296 (error "wrong size tilt scale sequence"))
297 (setf (aref (proto-slot-value 'internals
) 10) val
))
298 (aref (proto-slot-value 'internals
) 10))
302 ;;;; Newton's Method with Backtracking
306 (defun newtonmax (f start
&key
312 "Args:(f start &key scale derivstep (verbose 1) return-derivs)
313 Maximizes F starting from START using Newton's method with backtracking.
314 If RETURN-DERIVS is NIL returns location of maximum; otherwise returns
315 list of location, unction value, gradient and hessian at maximum.
316 SCALE should be a list of the typical magnitudes of the parameters.
317 DERIVSTEP is used in numerical derivatives and VERBOSE controls printing
318 of iteration information. COUNT-LIMIT limits the number of iterations"
319 (let ((verbose (if verbose
(if (integerp verbose
) verbose
1) 0))
320 (minfo (send minfo-proto
:new f start
321 :scale scale
:derivstep derivstep
)))
322 (send minfo
:maxiter count-limit
)
323 (send minfo
:derivscale
)
324 (send minfo
:maximize verbose
)
326 (cons (send minfo
:x
) (- (send minfo
:fvals
)))
330 ;;; Nelder-Mead Simplex Method
333 ;;; Simplex Prototype
335 (defvar simplex-proto
)
336 (defproto simplex-proto
'(f simplex
))
338 (defun nelmeadmax (f start
&key
340 (epsilon (sqrt machine-epsilon
))
347 "Args: (f start &key (size 1) (epsilon (sqrt machine-epsilon))
348 (count-limit 500) (verbose t) alpha beta gamma delta)
349 Maximizes F using the Nelder-Mead simplex method. START can be a
350 starting simplex - a list of N+1 points, with N=dimension of problem,
351 or a single point. If start is a single point you should give the
352 size of the initial simplex as SIZE, a sequence of length N. Default is
353 all 1's. EPSILON is the convergence tolerance. ALPHA-DELTA can be used to
354 control the behavior of simplex algorithm."
355 (let ((s (send simplex-proto
:new f start size
)))
356 (do ((best (send s
:best-point
) (send s
:best-point
))
357 (count 0 (+ count
1))
359 ((or (< (send s
:relative-range
) epsilon
) (>= count count-limit
))
360 (if (and verbose
(>= count count-limit
))
361 (format t
"Iteration limit exceeded.~%"))
362 (send s
:point-location
(send s
:best-point
)))
363 (setf next
(send s
:extrapolate-from-worst
(- alpha
)))
364 (if (send s
:is-worse best next
)
365 (setf next
(send s
:extrapolate-from-worst gamma
))
366 (when (send s
:is-worse next
(send s
:second-worst-point
))
367 (setf next
(send s
:extrapolate-from-worst beta
))
368 (if (send s
:is-worse next
(send s
:worst-point
))
369 (send s
:shrink-to-best delta
))))
371 (format t
"Value = ~10g~%"
372 (send s
:point-value
(send s
:best-point
)))))))
380 (defmeth simplex-proto
:make-point
(x)
381 (let ((f (send self
:f
)))
383 (let ((val (funcall f x
)))
384 (cons (if (consp val
) (car val
) val
) x
))
387 (defmeth simplex-proto
:point-value
(x) (car x
))
389 (defmeth simplex-proto
:point-location
(x) (cdr x
))
391 (defmeth simplex-proto
:is-worse
(x y
)
392 (< (send self
:point-value x
) (send self
:point-value y
)))
395 ;;; Making New Simplices
398 (defmeth simplex-proto
:isnew
(f start
&optional size
)
399 (send self
:simplex start size
)
403 ;;; Slot Accessors and Mutators
406 (defmeth simplex-proto
:simplex
(&optional new size
)
409 (if (and (consp new
) (typep (car new
) 'sequence
))
410 (if (/= (length new
) (+ 1 (length (car new
))))
411 (error "bad simplex data")
413 (let* ((n (length new
))
414 (size (if size size
(repeat 1 n
)))
415 ; (pts (- (* 2 (uniform-rand (repeat n (+ n 1)))) 1)))
416 (diag (* 2 size
(- (random (repeat 2 n
)) .5)))
417 (pts (cons (repeat 0 n
)
418 (mapcar #'(lambda (x) (coerce x
'list
))
419 (column-list (diagonal diag
))))))
420 (mapcar #'(lambda (x) (reduce #'+ (list (* size x
) new
))) pts
)))))
421 (setf (proto-slot-value 'simplex
)
422 (mapcar #'(lambda (x) (send self
:make-point x
)) simplex
))
423 (send self
:sort-simplex
)))
424 (proto-slot-value 'simplex
))
426 (defmeth simplex-proto
:f
(&optional f
)
428 (setf (proto-slot-value 'f
) f
)
430 (mapcar #'(lambda (x) (send self
:point-location x
))
431 (send self
:simplex
))))
432 (send self
:simplex simplex
)))
433 (proto-slot-value 'f
))
435 (defmeth simplex-proto
:sort-simplex
()
437 (setf (proto-slot-value 'simplex
)
438 (sort (proto-slot-value 'simplex
)
439 #'(lambda (x y
) (send self
:is-worse x y
))))))
442 ;;; Other Methods Using List Representation of SImplex
445 (defmeth simplex-proto
:best-point
() (car (last (send self
:simplex
))))
446 (defmeth simplex-proto
:worst-point
() (first (send self
:simplex
)))
447 (defmeth simplex-proto
:second-worst-point
() (second (send self
:simplex
)))
448 (defmeth simplex-proto
:replace-point
(new old
)
449 (let* ((simplex (send self
:simplex
))
450 (n (position old simplex
)))
452 (setf (nth n simplex
) new
)
453 (send self
:sort-simplex
))))
454 (defmeth simplex-proto
:mean-opposite-face
(x)
455 (let ((face (mapcar #'(lambda (x) (send self
:point-location x
))
456 (remove x
(send self
:simplex
)))))
457 (/ (reduce #'+ face
) (length face
))))
460 ;;; Iteration Step Methods
463 (defmeth simplex-proto
:extrapolate-from-worst
(fac)
464 (let* ((worst (send self
:worst-point
))
465 (wloc (send self
:point-location worst
))
466 (delta (- (send self
:mean-opposite-face worst
) wloc
))
467 (new (send self
:make-point
(+ wloc
(* (- 1 fac
) delta
)))))
468 (if (send self
:is-worse worst new
) (send self
:replace-point new worst
))
471 (defmeth simplex-proto
:shrink-to-best
(fac)
472 (let* ((best (send self
:best-point
))
473 (bloc (send self
:point-location best
)))
474 (dolist (x (copy-list (send self
:simplex
)))
475 (if (not (eq x best
))
476 (send self
:replace-point
477 (send self
:make-point
480 (- (send self
:point-location x
) bloc
))))
483 (defmeth simplex-proto
:relative-range
()
484 (let ((best (send self
:point-value
(send self
:best-point
)))
485 (worst (send self
:point-value
(send self
:worst-point
))))
486 (* 2 (/ (abs (- best worst
)) (+ 1 (abs best
) (abs worst
))))))
492 ;;;; Maximization and Numerical Derivatives
496 (defun data2double (n data ptr
)
498 (let* ((seq (compound-data-seq data
))
499 (elem (make-next-element seq
)))
500 (if (/= (length seq
) n
) (error "bad data size"))
503 (la-put-double ptr i
(get-next-element elem i
)))))
505 (defun maximize-callback (n px pfval pgrad phess pderivs
)
506 (la-vector-to-data px n
+mode-re
+ *maximize-callback-arg
*)
507 (let* ((val (funcall *maximize-callback-function
* *maximize-callback-arg
*))
508 (derivs (if (consp val
) (- (length val
) 1) 0)))
509 (la-put-integer pderivs
0 derivs
)
510 (la-put-double pfval
0 (if (consp val
) (first val
) val
))
511 (if (<= 1 derivs
) (data2double n
(second val
) pgrad
))
512 (if (<= 2 derivs
) (data2double (* n n
) (third val
) phess
))))
514 (defun numgrad (f x
&optional scale
(h -
1.0))
515 "Args: (f x &optional scale derivstep)
516 Computes the numerical gradient of F at X."
520 (check-sequence scale
)
523 (let* ((n (length x
))
524 (result (make-list n
)))
525 (if (and scale
(/= n
(length scale
)))
526 (error "scale not the same length as x"))
527 (let ((*maximize-callback-function
* f
)
528 (*maximize-callback-arg
* (make-list n
)))
529 (let ((px (la-data-to-vector x
+mode-re
+))
530 (pgrad (la-vector n
+mode-re
+))
531 (pscale (la-data-to-vector
532 (if scale scale
(make-list n
:initial-element
1.0))
536 (numgrad-front n px pgrad h pscale
)
537 (la-vector-to-data pgrad n
+mode-re
+ result
))
539 (la-free-vector pgrad
)
540 (la-free-vector pscale
))))
543 (defun numhess (f x
&optional scale
(h -
1.0) all
)
544 "Args: (f x &optional scale derivstep)
545 Computes the numerical Hessian matrix of F at X."
549 (check-sequence scale
)
552 (let* ((n (length x
))
554 (list nil
(make-list n
) (make-array (list n n
)))
555 (make-array (list n n
)))))
556 (if (and scale
(/= n
(length scale
)))
557 (error "scale not the same length as x"))
558 (let ((*maximize-callback-function
* f
)
559 (*maximize-callback-arg
* (make-list n
)))
560 (let ((hess-data (compound-data-seq (if all
(third result
) result
)))
561 (px (la-data-to-vector x
+mode-re
+))
562 (pf (la-vector 1 +mode-re
+))
563 (pgrad (la-vector n
+mode-re
+))
564 (phess (la-vector (* n n
) +mode-re
+))
565 (pscale (la-data-to-vector
566 (if scale scale
(make-list n
:initial-element
1.0))
570 (numhess-front n px pf pgrad phess h pscale
)
572 (setf (first result
) (la-get-double pf
0))
573 (la-vector-to-data pgrad n
+mode-re
+ (second result
)))
574 (la-vector-to-data phess
(* n n
) +mode-re
+ hess-data
))
577 (la-free-vector pgrad
)
578 (la-free-vector phess
)
579 (la-free-vector pscale
))))