updating object structure, adding fixes
[tsl.git] / bayes.lsp
blob3dd129d13ab0b795dd464e45d26e47c3439484ca
1 ;;; -*- mode: lisp -*-
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.
5 ;;; File moved from XLISP-STAT to CommonLispStat by Luke, note the following:
7 ;;;; XLISP-STAT 2.1 Copyright (c) 1990, by Luke Tierney
8 ;;;; Additions to Xlisp 2.1, Copyright (c) 1989 by David Michael Betz
9 ;;;; You may give out copies of this software; for conditions see the file
10 ;;;; COPYING included with this distribution.
12 (in-package #:lisp-stat)
14 (export '(bayes-model bayes-model-proto bayes-internals))
16 ;;;;
17 ;;;; Objects Representing Functions
18 ;;;;
20 ;; Generic C2 Functions
22 (defproto c2-function-proto '(f h num-derivs))
24 (defmeth c2-function-proto :isnew (f &optional (h .001) (num-derivs 0))
25 (setf (slot-value 'f) f)
26 (setf (slot-value 'h) (if (numberp h) (list h h) h))
27 (setf (slot-value 'num-derivs) num-derivs))
29 (defmeth c2-function-proto :f (&optional f)
30 (if f (setf (slot-value 'f) f))
31 (slot-value 'f))
33 (defmeth c2-function-proto :grad-h () (first (slot-value 'h)))
34 (defmeth c2-function-proto :hess-h () (second (slot-value 'h)))
35 (defmeth c2-function-proto :num-derivs () (slot-value 'num-derivs))
37 (defmeth c2-function-proto :value (x)
38 (let ((f (send self :f)))
39 (if (objectp f)
40 (send f :value x)
41 (let ((v (funcall f x)))
42 (if (consp v) (first v) v)))))
44 (defmeth c2-function-proto :gradient (x &optional (h (send self :grad-h)))
45 (let ((f (send self :f)))
46 (if (objectp f) (send f :gradient x h) (numgrad f x nil h))))
48 (defmeth c2-function-proto :hessian (x &optional (h (send self :hess-h)))
49 (let ((f (send self :f)))
50 (if (objectp f) (send f :hessian x h) (numhess f x nil h))))
52 (defmeth c2-function-proto :vals (x &optional (h (send self :hess-h)))
53 (let ((f (send self :f)))
54 (if (objectp f)
55 (send f :vals x h)
56 (let ((v (funcall f x)))
57 (if (consp v)
58 (if (= (length v) 3)
60 (list (first v) (second v) (send self :hessian x h)))
61 (list v (send self :gradient x h) (send self :hessian x h)))))))
63 (defmeth c2-function-proto :vals (x &optional (h (send self :hess-h)))
64 (let ((f (send self :f)))
65 (if (objectp f) (send f :vals x h) (numhess f x nil h t))))
68 ;; Scaled C2 Functions
70 (defproto scaled-c2-function-proto '(scaling) () c2-function-proto)
72 ;;**** allow function objects?
73 (defmeth scaled-c2-function-proto :isnew (f &optional
74 theta
75 sigma
76 (center 0)
77 (scale 1)
78 (h 0.001))
79 (let* ((value (funcall f theta))
80 (num-derivs (if (consp value) (- (length value) 1) -1))
81 (sigma-t (if (< 0 num-derivs) (transpose sigma))))
82 (labels ((scale (v)
83 (if v
84 (case num-derivs
85 (-1 (/ (- v center) scale))
86 (0 (/ (- (first v) center) scale))
87 (1 (list (/ (- (first v) center) scale)
88 (matmult sigma-t (/ (second v) scale))))
89 (2 (list (/ (- (first v) center) scale)
90 (matmult sigma-t (/ (second v) scale))
91 (matmult sigma-t (/ (third v) scale) sigma))))))
92 (sf (x) (scale (funcall f (ax+y sigma x theta t)))))
93 (call-next-method #'sf h num-derivs))))
95 ;; Tilted C2 Functions
96 ;; **** allow nil values?
97 (defproto tilt-function-proto '(tilt exptilt) () c2-function-proto)
99 (defmeth tilt-function-proto :isnew (&optional f (tilt .1) (h .001))
100 (call-next-method f h)
101 (setf (slot-value 'exptilt) t)
102 (setf (slot-value 'tilt) tilt))
104 (defmeth tilt-function-proto :tilt (&optional tilt)
105 (if tilt (setf (slot-value 'tilt) tilt))
106 (slot-value 'tilt))
108 (defmeth tilt-function-proto :exptilt (&optional (new nil set))
109 (if set (setf (slot-value 'exptilt) new))
110 (slot-value 'exptilt))
112 (defmeth tilt-function-proto :value (x)
113 (let ((f (send self :f))
114 (tilt (send self :tilt))
115 (exptilt (send self :exptilt)))
116 (flet ((value (f)
117 (let ((v (send f :value x)))
118 (if exptilt v (log v)))))
119 (* tilt (if (consp f) (apply #'+ (mapcar #'value f)) (value f))))))
121 (defmeth tilt-function-proto :gradient (x &optional (h (send self :grad-h)))
122 (let ((f (send self :f))
123 (tilt (send self :tilt))
124 (exptilt (send self :exptilt)))
125 (flet ((gradient (f)
126 (if exptilt
127 (send f :gradient x h)
128 (let ((v (send f :value x))
129 (grad (send f :gradient x h)))
130 (/ grad v)))))
131 (* tilt
132 (if (consp f) (apply #'+ (mapcar #'gradient f)) (gradient f))))))
134 (defmeth tilt-function-proto :hessian (x &optional (h (send self :hess-h)))
135 (let ((f (send self :f))
136 (tilt (send self :tilt))
137 (exptilt (send self :exptilt)))
138 (flet ((hessian (f)
139 (let* ((vals (send f :vals x h))
140 (v (first vals))
141 (grad (if exptilt (second vals) (/ (second vals) v)))
142 (hess (if exptilt (third vals) (/ (third vals) v))))
143 (if exptilt hess (- hess (outer-product grad grad))))))
144 (* tilt (if (consp f) (apply #'+ (mapcar #'hessian f)) (hessian f))))))
146 (defmeth tilt-function-proto :vals (x &optional (h (send self :hess-h)))
147 (let ((f (send self :f))
148 (tilt (send self :tilt))
149 (exptilt (send self :exptilt)))
150 (flet ((vals (f)
151 (let ((vals (send f :vals x h)))
152 (if exptilt
153 vals
154 (let* ((v (first vals))
155 (grad (/ (second vals) v))
156 (hess (- (/ (third vals) v)
157 (outer-product grad grad))))
158 (list (log v) grad hess))))))
159 (let ((v (if (consp f) (mapcar #'vals f) (vals f))))
160 (* tilt (if (consp f) (apply #'+ v) v))))))
162 ;; scaled log posterior prototype
164 (defproto scaled-logpost-proto
165 '(tilt-object init-pars) () scaled-c2-function-proto)
167 (defmeth scaled-logpost-proto :isnew (f &optional
168 theta sigma
169 (center 0) (scale 1) (h .001))
170 (let* ((n (length theta))
171 (m (repeat 0 n))
172 (m-grad (repeat 0 n))
173 (m-hess (- (identity-matrix n)))
174 (pars (list m m-grad m-hess)))
175 (call-next-method f theta sigma center scale h)
176 (setf (slot-value 'init-pars) pars)
177 (setf (slot-value 'tilt-object) (send tilt-function-proto :new))))
179 (defmeth scaled-logpost-proto :log-laplace (g &optional
180 (count-limit 2) det-only (h .1))
181 (let* ((x (send self :tilt-newton g count-limit))
182 (vals (send self :vals x h))
183 (gvals (if g (send g :vals x h)))
184 (hess (if g (+ (third vals) (third gvals)) (third vals)))
185 (det (- (sum (log (diagonal (first (chol-decomp (- hess)))))))))
186 (if det-only
187 det
188 (if g (+ (first vals) (first gvals) det) (+ (first vals) det)))))
190 (defmeth scaled-logpost-proto :tilt-newton (tilt &optional (count-limit 2))
191 (let* ((pars (slot-value 'init-pars))
192 (mode (first pars))
193 (mode-grad (second pars))
194 (mode-hess (third pars)))
195 (flet ((gradhess (x initial)
196 (let ((gh (if (and initial mode-grad mode-hess)
197 (list mode-grad mode-hess)
198 (rest (send self :vals x)))))
199 (if tilt (+ gh (rest (send tilt :vals x))) gh)))
200 (newton-step (x gh) (- x (solve (second gh) (first gh)))))
201 (do* ((count 1 (+ count 1))
202 (gradhess (gradhess mode t) (gradhess x nil))
203 (x (newton-step mode gradhess) (newton-step x gradhess)))
204 ((>= count count-limit) x)))))
206 (defmeth scaled-logpost-proto :tilt-laplace (g tilt &optional
207 (exptilt t) maxiter det-only h)
208 (let ((tilt-object (slot-value 'tilt-object)))
209 (send tilt-object :exptilt exptilt)
210 (send tilt-object :f g)
211 (send tilt-object :tilt tilt)
212 (send self :log-laplace tilt-object maxiter det-only h)))
214 (defmeth scaled-logpost-proto :tilt-mode (g tilt &key (exptilt t) (maxiter 2))
215 (let ((tilt-object (slot-value 'tilt-object)))
216 (send tilt-object :exptilt exptilt)
217 (send tilt-object :f g)
218 (send tilt-object :tilt tilt)
219 (send self :tilt-newton tilt-object maxiter)))
221 ;;;;
222 ;;;; Bayes Model Prototype
223 ;;;;
225 (defproto bayes-model-proto '(bayes-internals))
227 ;; initialization methods and constructor function
229 (defmeth bayes-model-proto :isnew (logpost mode &key
230 scale
231 (derivstep .001)
232 (verbose t)
233 (maximize t)
234 domain)
235 (send self :set-bayes-internals
236 logpost mode scale derivstep nil nil t domain)
237 (if maximize (send self :maximize verbose)))
239 (defun bayes-model (logpost mode &rest args &key (quick t) (print t))
240 "Args: (logpost mode &key scale derivstep (verbose t)
241 (quick t) (print t)))
242 LOGPOST computes the logposterior density. It should return the
243 function, or a list of the function value and gradient, or a list of
244 the function value, gradient and Hessian. MODE is an initial guess for
245 the mode. SCALE and DERIVSTEP are used for numerical derivatives and
246 scaling. VERBOSE controls printing of iteration information during
247 optimization, PRINT controls printing of summary information. If QUICK
248 is T the summary is based on first order approximations."
249 (let ((m (apply #'send bayes-model-proto :new logpost mode args)))
250 (if print (send m :display :quick quick))
253 ;; display method
255 (defmeth bayes-model-proto :display (&key (quick t))
256 (let* ((moments (send self (if quick :1stmoments :moments)))
257 (means (first moments))
258 (stdevs (second moments))
259 (p-names (send self :parameter-names)))
260 (if quick
261 (format t "~2%First Order Approximations to Posterior Moments:~2%")
262 (format t "~2%Approximate Posterior Moments:~2%"))
263 (mapcar #'(lambda (name mu sd)
264 (format t "~22a ~10g (~a)~%" name mu sd))
265 p-names
266 means
267 stdevs)
268 (format t "~%")))
270 (defmeth bayes-model-proto :parameter-names ()
271 (let ((n (length (send self :mode))))
272 (mapcar #'(lambda (x) (format nil "Parameter ~d" x)) (iseq 0 (- n 1)))))
274 ;; implementation-dependent access methods
276 (defmeth bayes-model-proto :set-bayes-internals (lp m s h mval ch max dom)
277 (setf (slot-value 'bayes-internals)
278 (vector lp m s h mval ch max dom)))
280 (defmeth bayes-model-proto :logpost (&optional new)
281 (let ((internals (slot-value 'bayes-internals)))
282 (when new
283 (setf (select internals 0) new)
284 (send self :needs-maximizing t))
285 (select internals 0)))
287 (defmeth bayes-model-proto :domain (&optional new)
288 (let ((internals (slot-value 'bayes-internals)))
289 (if new (setf (select internals 7) new))
290 (select internals 7)))
292 (defmeth bayes-model-proto :mode-values (&optional mode mval ch)
293 (let ((internals (slot-value 'bayes-internals)))
294 (when mode
295 (setf (select internals 1) mode)
296 (setf (select internals 4) mval)
297 (setf (select internals 5) ch))
298 (list (select internals 1)
299 (select internals 4)
300 (select internals 5))))
302 (defmeth bayes-model-proto :parameter-scale (&optional new)
303 (let ((internals (slot-value 'bayes-internals)))
304 (if new (setf (select internals 2) new))
305 (select internals 2)))
307 (defmeth bayes-model-proto :parameter-dimension ()
308 (length (select (slot-value 'bayes-internals) 1)))
310 (defmeth bayes-model-proto :derivstep ()
311 (select (slot-value 'bayes-internals) 3))
313 (defmeth bayes-model-proto :needs-maximizing (&optional (new nil set))
314 (let ((internals (slot-value 'bayes-internals)))
315 (if set (setf (select internals 6) new))
316 (select internals 6)))
318 ;; Transformation-Related Methods
319 ;; (These should be the only ones needing to be changed to handle
320 ;; an internal parameter transformation; perhaps also :logpost)
322 ;; **** fix to be more careful about use of functionp
323 (defun function-list (g &optional n)
324 (cond
325 ((or (functionp g) (objectp g)) (list g))
326 ((integerp g)
327 (if (null n)
328 (list #'(lambda (x) (elt x g)))
329 (let ((grad (make-array n :initial-element 0))
330 (hess (make-array (list n n) :initial-element 0)))
331 (setf (aref grad g) 1)
332 (list #'(lambda (x) (list (elt x g) grad hess))))))
333 (t (mapcar #'(lambda (x) (car (function-list x n))) g))))
335 (defmeth bayes-model-proto :mode ()
336 (if (send self :needs-maximizing) (send self :maximize))
337 (first (send self :mode-values)))
339 (defmeth bayes-model-proto :new-mode-guess (new)
340 (send self :needs-maximizing t)
341 (send self :mode-values new))
343 (defmeth bayes-model-proto :transformed-logpost ()
344 (if (send self :needs-maximizing) (send self :maximize))
345 (let* ((m-values (send self :mode-values))
346 (mode (first m-values))
347 (mval (second m-values))
348 (ch (third m-values))
349 (h (send self :derivstep))
350 (f (send self :logpost)))
351 (send scaled-logpost-proto :new f mode ch mval 1 h)))
353 ;;**** need transformed domain here
355 (defmeth bayes-model-proto :transformed-functions (&optional g (c 0) (s 1))
356 (if (send self :needs-maximizing) (send self :maximize))
357 (let* ((m-values (send self :mode-values))
358 (mode (first m-values))
359 (mval (second m-values))
360 (ch (third m-values))
361 (h (send self :derivstep))
362 (n (length mode))
363 (g (function-list (if g g (iseq n)) n))
364 (c (if (numberp c) (repeat c (length g)) c))
365 (s (if (numberp s) (repeat s (length g)) s)))
366 (mapcar #'(lambda (g c s)
367 (send scaled-c2-function-proto :new g mode ch c s h))
368 g c s)))
370 ;; computing methods
372 (defmeth bayes-model-proto :maximize (&optional (verbose 0))
373 (let* ((lp (send self :logpost))
374 (x (first (send self :mode-values)))
375 (scale (send self :parameter-scale))
376 (h (send self :derivstep))
377 (minfo (newtonmax lp x
378 :scale scale
379 :derivstep h
380 :verbose verbose
381 :return-derivs t))
382 (mode (first minfo))
383 (mval (second minfo))
384 (ch (first (chol-decomp (inverse (- (fourth minfo)))))))
385 (send self :mode-values mode mval ch)
386 (send self :needs-maximizing nil)
387 (send self :check-derivatives verbose)))
389 (defmeth bayes-model-proto :check-derivatives (&optional
390 (verbose 0)
391 (epsilon .00001))
392 (let* ((verbose (if (numberp verbose) (< 0 verbose) verbose))
393 (n (send self :parameter-dimension))
394 (tlp (send self :transformed-logpost))
395 (hess (send tlp :hessian (repeat 0 n)))
396 (needs-max (send self :needs-maximizing)))
397 (when (> (max (abs (+ hess (identity-matrix n)))) epsilon)
398 (if verbose (format t "Adjusting derivatives...~%"))
399 (let* ((ch (first (chol-decomp (- (inverse hess)))))
400 (mvals (send self :mode-values))
401 (m (matmult (third mvals) ch)))
402 (send self :mode-values (first mvals) (second mvals) m)
403 (if (not needs-max) (send self :needs-maximizing nil))
404 (if verbose
405 (let* ((tlp (send self :transformed-logpost))
406 (hess (send tlp :hessian (repeat 0 n))))
407 (if (> (max (abs (+ hess (identity-matrix n)))) epsilon)
408 (format t
409 "Derivatives may not be well-behaved.~%"))))))))
411 ;; moments
413 (defmeth bayes-model-proto :1stmoments (&optional gfuns &key covar)
414 "Args: (&optional gfuns &key covar)
415 Computes first order approximations to posterior moments. GFUNS can be
416 a parameter index, list of indices, a function of the parameters or a
417 list of such functions. Returns a the list of first order approximate
418 means and standard deviations if COVAR is NIL. If COVAR is T the
419 covaraince is appended to the end of the result as well."
420 (if (send self :needs-maximizing) (send self :maximize))
421 (let* ((n (send self :parameter-dimension))
422 (x (repeat 0 n))
423 (g (send self :transformed-functions gfuns 0 1))
424 (grads (apply #'bind-columns
425 (mapcar #'(lambda (g) (send g :gradient x)) g)))
426 (mean (mapcar #'(lambda (g) (send g :value x)) g))
427 (cov (matmult (transpose grads) grads)))
428 (if covar
429 (list mean (sqrt (diagonal cov)) cov)
430 (list mean (sqrt (diagonal cov))))))
432 (defmeth bayes-model-proto :mgfmoments (&optional g &key covar
433 (mgfdel .1)
434 ((:derivstep h) .1)
435 (maxiter 2))
436 (let* ((moms1 (send self :1stmoments g :covar covar))
437 (mean1 (first moms1))
438 (stdev1 (second moms1))
439 (cov1 (if covar (third moms1)))
440 (l-object (send self :transformed-logpost))
441 (g-objects (send self :transformed-functions g mean1 stdev1))
442 (ldet0 (send l-object :log-laplace nil maxiter t h)))
443 (labels ((lapdet (g tilt)
444 (- (send l-object :tilt-laplace g tilt t maxiter t h) ldet0))
445 (moms2 (m s g)
446 (let ((ldet1 (lapdet g mgfdel))
447 (ldet2 (lapdet g (- mgfdel))))
448 (list (+ m (* s (/ (- ldet1 ldet2) (* 2 mgfdel))))
449 (* s (sqrt (+ 1 (/ (+ ldet1 ldet2) (^ mgfdel 2))))))))
450 (covar (g mean-sd)
451 (let* ((mu (first mean-sd))
452 (sd (second mean-sd))
453 (cov (diagonal (^ sd 2)))
454 (var1 (^ stdev1 2))
455 (var (^ sd 2))
456 (rvdiff (/ (- var var1) var))
457 (tilt mgfdel)
458 (2tilt2 (* 2 (^ tilt 2)))
459 (negtilt (- tilt)))
460 (dotimes (i (length g) cov)
461 (dotimes (j i)
462 (let* ((g (select g (list i j)))
463 (rvdi (select rvdiff i))
464 (rvdj (select rvdiff j))
465 (sdi (select sd i))
466 (sdj (select sd j))
467 (ldt1 (lapdet g tilt))
468 (ldt2 (lapdet g negtilt))
469 (del2 (/ (+ ldt1 ldt2) 2tilt2))
470 (d (- del2 (* 0.5 rvdi) (* 0.5 rvdj)))
471 (c (+ (aref cov1 i j) (* d sdi sdj))))
472 (setf (aref cov i j) c)
473 (setf (aref cov j i) c)))))))
474 (let ((mean-sd (transpose (mapcar #'moms2 mean1 stdev1 g-objects))))
475 (if covar
476 (append mean-sd (list (covar g-objects mean-sd)))
477 mean-sd)))))
479 (defmeth bayes-model-proto :fullmoments (&optional g &key covar
480 ((:derivstep h) .1)
481 (maxiter 2))
482 (let* ((moms1 (send self :1stmoments g))
483 (mean1 (first moms1))
484 (stdev1 (second moms1))
485 (l-object (send self :transformed-logpost))
486 (g-objects (send self :transformed-functions g 0 mean1))
487 (loglap0 (send l-object :log-laplace nil maxiter nil h)))
488 (labels ((loglap (g tilt)
489 (- (send l-object :tilt-laplace g tilt nil maxiter nil h)
490 loglap0))
491 (moms2 (g mu)
492 (let ((mu1 (exp (loglap g 1.0)))
493 (mu2 (exp (loglap g 2.0))))
494 (* mu (list mu1 (sqrt (- mu2 (^ mu1 2)))))))
495 (covar (g mean-sd)
496 (let* ((mu (/ (first mean-sd) mean1))
497 (sd (second mean-sd))
498 (cov (diagonal (^ sd 2))))
499 (dotimes (i (length g) cov)
500 (dotimes (j i)
501 (let* ((g (select g (list i j)))
502 (muij (exp (loglap g 1.0)))
503 (mui (select mu i))
504 (muj (select mu j))
505 (mu1i (select mean1 i))
506 (mu1j (select mean1 j))
507 (c (* (- muij (* mui muj)) mu1i mu1j)))
508 (setf (aref cov i j) c)
509 (setf (aref cov j i) c)))))))
510 (let ((mean-sd (transpose (mapcar #'moms2 g-objects mean1))))
511 (if covar
512 (append mean-sd (list (covar g-objects mean-sd)))
513 mean-sd)))))
515 (defmeth bayes-model-proto :2ndmoments (&rest args)
516 (apply #'send self :mgfmoments args))
518 (defmeth bayes-model-proto :moments (&rest args)
519 "Args: (&optional gfuns &key covar)
520 Computes second order approximations to posterior moments. GFUNS can be
521 a parameter index, list of indices, a function of the parameters or a
522 list of such functions. Returns a the list of second order approximate
523 means and standard deviations if COVAR is NIL. If COVAR is T the
524 covaraince is appended to the end of the result as well."
525 (apply #'send self :2ndmoments args))
527 ;; margins
529 (defproto laplace-margin-proto '(logpost g x val i j a grad gval lu h))
531 (defmeth laplace-margin-proto :isnew (logpost g n k h)
532 (setf (slot-value 'logpost) logpost)
533 (setf (slot-value 'g) g)
534 (setf (slot-value 'x) (repeat 0 (+ n k)))
535 (setf (slot-value 'i) (iseq n))
536 (setf (slot-value 'j) (+ n (iseq k)))
537 (setf (slot-value 'a)
538 (make-array (list (+ n k) (+ n k)) :initial-element 0))
539 (setf (slot-value 'h) h)
540 (send self :adjust-internals t))
542 (defmeth laplace-margin-proto :adjust-internals (&optional initial)
543 (let* ((logpost (slot-value 'logpost))
544 (g (slot-value 'g))
545 (i (slot-value 'i))
546 (j (slot-value 'j))
547 (x (slot-value 'x))
548 (a (slot-value 'a))
549 (h (slot-value 'h))
550 (y (select x i))
551 (lambda (select x j))
552 (n (length y))
553 (vals (if initial
554 (list 0 (repeat 0 n) (- (identity-matrix n)))
555 (send logpost :vals y h)))
556 (val (first vals))
557 (grad (second vals))
558 (hess (third vals))
559 (gvals (mapcar #'(lambda (x) (send x :vals y h)) g))
560 (gval (mapcar #'first gvals))
561 (ggrad (mapcar #'second gvals))
562 (ghess (mapcar #'third gvals))
563 (ggradmat (apply #' bind-columns ggrad)))
564 (setf (slot-value 'val) val)
565 (setf (slot-value 'grad) (apply #'+ grad (* lambda ggrad)))
566 (setf (slot-value 'gval) gval)
567 (setf (select a i i) (apply #'+ hess (* lambda ghess)))
568 (setf (select a i j) ggradmat)
569 (setf (select a j i) (transpose ggradmat))
570 (setf (slot-value 'lu) (lu-decomp a))))
572 ;; **** test for nonsingularity?
573 (defmeth laplace-margin-proto :move-to (target)
574 (let* ((x (slot-value 'x))
575 (grad (slot-value 'grad))
576 (gval (slot-value 'gval))
577 (lu (slot-value 'lu))
578 (next-x (- x (lu-solve lu (combine grad (- gval target))))))
579 (setf (slot-value 'x) next-x)
580 (send self :adjust-internals)))
582 (defmeth laplace-margin-proto :log-density (&optional profile)
583 (let ((val (slot-value 'val)))
584 (if profile
586 (let* ((lu (slot-value 'lu))
587 (nonsing (null (fourth lu))))
588 (if nonsing
589 (+ (* -0.5 (sum (log (abs (diagonal (first lu))))))
590 val))))))
592 ;; ***** fix step choice
593 ;; ***** Cut off at first nil?
594 (defmeth bayes-model-proto :log-margin1 (g x &key
595 ((:derivstep h) .05)
596 (spline t)
597 profile)
598 (let* ((moms1 (send self :1stmoments g))
599 (mean1 (select (first moms1) 0))
600 (stdev1 (select (second moms1) 0))
601 (n (send self :parameter-dimension))
602 (l-ob (send self :transformed-logpost))
603 (g-obs (send self :transformed-functions g mean1 stdev1))
604 (xs (/ (- x mean1) stdev1))
605 (xlow (coerce (sort-data (select xs (which (<= xs 0)))) 'list))
606 (xhigh (coerce (sort-data (select xs (which (> xs 0)))) 'list)))
607 (flet ((margin (x)
608 (let ((margin (send laplace-margin-proto :new l-ob g-obs n 1 h)))
609 (flet ((nextmargin (x)
610 (send margin :move-to x)
611 (send margin :log-density profile)))
612 (mapcar #'nextmargin x)))))
613 (let* ((ylow (reverse (margin (reverse xlow))))
614 (yhigh (margin xhigh))
615 (x (append xlow xhigh))
616 (y (append ylow yhigh))
617 (i (which (mapcar #'numberp y)))
618 (xi (select x i))
619 (yi (select y i))
620 (xy (if spline (spline xi yi) (list xi yi))))
621 (list (+ mean1 (* stdev1 (first xy)))
622 (- (second xy) (log stdev1) (* 0.5 (log (* 2 pi)))))))))
624 (defmeth bayes-model-proto :margin1 (g x &key
625 (derivstep .05)
626 (spline t)
627 profile)
628 "Args: (g x &key (:derivstep .05) (spline t) profile)
629 Computes Laplace approximation to marginal posterior density of G at
630 points X. G can be an index or a function of the parameter vector. X
631 is a sequence that should include the modal value of G. If SPLINE is
632 true the log density is splined. If PROFILE is true, a profile of the
633 posterior is returned."
634 (let* ((logmar (send self :log-margin1 g x
635 :derivstep derivstep
636 :spline spline
637 :profile profile)))
638 (list (first logmar) (exp (second logmar)))))
640 ;;**** allow domain test function
641 (defmeth bayes-model-proto :impsample (&optional g &key (n 100) (df 2))
642 (let* ((l-ob (send self :transformed-logpost))
643 (g-obs (send self :transformed-functions g))
644 (k (send self :parameter-dimension))
645 (v (chisq-rand n df))
646 (z (* (normal-rand (repeat k n)) (sqrt (/ df v))))
647 (c (- (log-gamma (/ (+ k df) 2))
648 (log-gamma (/ df 2))
649 (* (/ k 2) (log (/ df 2))))))
650 (flet ((w (z)
651 (let ((lp (send l-ob :value z))
652 (lt (* -0.5 (+ k df) (log (+ 1 (/ (sum (* z z)) df))))))
653 (if (realp lp) (exp (- lp lt c)) 0)))
654 (gvals (z) (mapcar #'(lambda (g) (send g :value z)) g-obs)))
655 (list (mapcar #'gvals z) (mapcar #'w z)))))
657 (defmeth bayes-model-proto :impmoments (&optional g &key (n 100) (df 2))
658 (let* ((impsample (send self :impsample g :n n :df df))
659 (means (/ (reduce #'+ (* (first impsample) (second impsample)))
660 (reduce #'+ (second impsample))))
661 (x (mapcar #'(lambda (z) (^ (- z means) 2)) (first impsample)))
662 (vars (/ (reduce #'+ (* x (second impsample)))
663 (reduce #'+ (second impsample)))))
664 (list means (sqrt vars))))