docs improved to start fast.
[CommonLispStat.git] / nonlin.lsp
blobde75fdde697a6b35c11a74e1a81c12e8fc4f0802
1 ;;; -*- mode: lisp -*-
2 ;;;
3 ;;; Copyright (c) 2005--2007, by A.J. Rossini <blindglobe@gmail.com>
4 ;;; See COPYRIGHT file for any additional restrictions (BSD license).
5 ;;; Since 1991, ANSI was finally finished. Modified to match ANSI
6 ;;; Common Lisp.
8 ;;;; XLISP-STAT 2.1 Copyright (c) 1990, by Luke Tierney
9 ;;;; Additions to Xlisp 2.1, Copyright (c) 1989 by David Michael Betz
10 ;;;; You may give out copies of this software; for conditions see the file
11 ;;;; COPYING included with this distribution.
13 (defpackage :lisp-stat-regression-nonlin
14 (:use :common-lisp
15 :lisp-stat-object-system
16 :lisp-stat-math
17 :lisp-stat-basics
18 :lisp-stat-compound-data
19 :lisp-stat-matrix
20 :lisp-stat-linalg
21 :lisp-stat-regression-linear)
22 (:shadowing-import-from :lisp-stat-object-system
23 slot-value call-method call-next-method)
24 (:shadowing-import-from :lisp-stat-math
25 expt + - * / ** mod rem abs 1+ 1- log exp sqrt sin cos tan
26 asin acos atan sinh cosh tanh asinh acosh atanh float random
27 truncate floor ceiling round minusp zerop plusp evenp oddp
28 < <= = /= >= > complex conjugate realpart imagpart phase
29 min max logand logior logxor lognot ffloor fceiling
30 ftruncate fround signum cis)
32 (:export nreg-model nreg-model-proto mean-function theta-hat epsilon
33 count-limit verbose))
35 (in-package :lisp-stat-regression-nonlin)
37 ;;;
38 ;;; Nonlinear Regression Model Prototype
39 ;;;
41 (defproto nreg-model-proto
42 '(mean-function theta-hat epsilon count-limit verbose)
43 '()
44 regression-model-proto)
46 (defun nreg-model (mean-function y theta
47 &key
48 (epsilon .0001)
49 (print t)
50 (count-limit 20)
51 parameter-names
52 response-name
53 case-labels
54 weights
55 included
56 (verbose print))
57 "Args: (mean-function y theta &key (epsilon .0001) (count-limit 20)
58 (print t) parameter-names response-name case-labels
59 weights included (vetbose print))
60 Fits nonlinear regression model with MEAN-FUNCTION and response Y using initial
61 parameter guess THETA. Returns model object."
62 (let ((m (send nreg-model-proto :new)))
63 (send m :mean-function mean-function)
64 (send m :y y)
65 (send m :new-initial-guess theta)
66 (send m :epsilon epsilon)
67 (send m :count-limit count-limit)
68 (send m :parameter-names parameter-names)
69 (send m :response-name response-name)
70 (send m :case-labels case-labels)
71 (send m :weights weights)
72 (send m :included included)
73 (send m :verbose verbose)
74 (if print (send m :display))
75 m))
77 (defmeth nreg-model-proto :save ()
78 "Message args: ()
79 Returns an expression that will reconstruct the regression model."
80 `(nreg-model ',(send self :mean-function)
81 ',(send self :y)
82 ',(send self :coef-estimates)
83 :epsilon ',(send self :epsilon)
84 :count-limit ',(send self :count-limit)
85 :predictor-names ',(send self :predictor-names)
86 :response-name ',(send self :response-name)
87 :case-labels ',(send self :case-labels)
88 :weights ',(send self :weights)
89 :included ',(send self :included)
90 :verbose ',(send self :verbose)))
92 ;;;
93 ;;; Computing Method
94 ;;;
96 (defmeth nreg-model-proto :compute ()
97 "Message args: ()
98 Recomputes the estimates. For internal use by other messages"
99 (let* ((y (send self :y))
100 (weights (send self :weights))
101 (inc (if-else (send self :included) 1 0))
102 (w (if weights (* inc weights) inc)))
103 (setf (slot-value 'theta-hat)
104 (nlreg (send self :mean-function)
106 (slot-value 'theta-hat)
107 (send self :epsilon)
108 (send self :count-limit)
110 (send self :verbose)))
111 (setf (slot-value 'x)
112 (funcall (make-jacobian (slot-value 'mean-function)
113 (length (slot-value 'theta-hat)))
114 (slot-value 'theta-hat)))
115 (setf (slot-value 'intercept) nil)
116 (call-next-method)
117 (let ((r (send self :residuals)))
118 (setf (slot-value 'residual-sum-of-squares)
119 (sum (* inc r r))))))
122 ;;; Slot Accessors and Mutators
125 (defmeth nreg-model-proto :new-initial-guess (guess)
126 "Message args: (guess)
127 Sets a new initial uess for parmeters."
128 (setf (slot-value 'theta-hat) guess)
129 (send self :needs-computing t))
131 (defmeth nreg-model-proto :theta-hat ()
132 "Message args: ()
133 Returns current parameter estimate."
134 (if (send self :needs-computing) (send self :compute))
135 (coerce (slot-value 'theta-hat) 'list))
137 (defmeth nreg-model-proto :mean-function (&optional f)
138 "Message args: (&optional f)
139 With no argument returns the mean function as supplied to m. With an
140 argument F sets the mean function of m to F and recomputes the
141 estimates."
142 (when (and f (functionp f))
143 (setf (slot-value 'mean-function) f)
144 (send self :needs-computing t))
145 (slot-value 'mean-function))
147 (defmeth nreg-model-proto :epsilon (&optional eps)
148 "Message args: (&optional eps)
149 With no argument returns the tolerance as supplied to m. With an argument
150 EPS sets the tolerance of m to EPS and recomputes the estimates."
151 (when (and eps (numberp eps))
152 (setf (slot-value 'epsilon) eps)
153 (send self :needs-computing t))
154 (slot-value 'epsilon))
156 (defmeth nreg-model-proto :count-limit (&optional count)
157 "Message args: (&optional new-count)
158 With no argument returns the iteration count limit as supplied to m. With
159 an argument COUNT sets the limit to COUNT and recomputes the
160 estimates."
161 (when (and count (numberp count))
162 (setf (slot-value 'count-limit) count)
163 (send self :needs-computing t))
164 (slot-value 'count-limit))
166 (defmeth nreg-model-proto :parameter-names (&optional (names nil set))
167 "Method args: (&optional names)
168 Sets or returns parameter names."
169 (if set (setf (slot-value 'predictor-names) names))
170 (let ((p-names (slot-value 'predictor-names))
171 (p (length (slot-value 'theta-hat))))
172 (if (not (and p-names (= p (length p-names))))
173 (setf (slot-value 'predictor-names)
174 (mapcar #'(lambda (a) (format nil "Parameter ~a" a))
175 (iseq 0 (- p 1))))))
176 (slot-value 'predictor-names))
178 (defmeth nreg-model-proto :verbose (&optional (val nil set))
179 "Method args: (&optional val)
180 Sets or retrieves verbose setting. If T iteration info is printed during
181 optimization."
182 (if set (setf (slot-value 'verbose) val))
183 (slot-value 'verbose))
186 ;;; Overrides for Linear Regression Methods
189 (defmeth nreg-model-proto :x ()
190 "Message args: ()
191 Returns the Jacobian matrix at theta-hat."
192 (call-next-method))
194 (defmeth nreg-model-proto :intercept (&rest args)
195 "Message args: ()
196 Always returns nil. (For compatibility with linear regression.)"
197 nil)
199 (defmeth nreg-model-proto :fit-values ()
200 "Message args: ()
201 Returns the fitted values for the model."
202 (coerce (funcall (send self :mean-function) (send self :theta-hat))
203 'list))
205 (defmeth nreg-model-proto :coef-estimates (&optional guess)
206 "Message args: (&optional guess)
207 With no argument returns the current parameter estimate. With an
208 argument GUESS takes it as a new initial guess and recomputes
209 the estimates."
210 (if guess (send self :new-initial-guess guess))
211 (send self :theta-hat))
213 (defmeth nreg-model-proto :predictor-names () (send self :parameter-names))
215 ;;;;
216 ;;;;
217 ;;;; Linear Regression Coefficients
218 ;;;;
219 ;;;;
221 (defun regression-coefficients (x y &key (intercept T) weights)
222 "Args: (x y &key (intercept T) weights)
223 Returns the coefficients of the regression of the sequence Y on the columns of
224 the matrix X."
225 (let* ((m (if weights
226 (make-sweep-matrix x y weights)
227 (make-sweep-matrix x y)))
228 (n (array-dimension x 1)))
229 (coerce (compound-data-seq
230 (if intercept
231 (select (car (sweep-operator m (iseq 1 n)))
232 (1+ n)
233 (iseq 0 n))
234 (select (car (sweep-operator m (iseq 0 n)))
235 (1+ n)
236 (iseq 1 n))))
237 'vector)))
239 ;;;;
240 ;;;;
241 ;;;; Nonlinear Regression Functions
242 ;;;;
243 ;;;;
244 (defun nlreg1 (f j y initial-beta epsilon count-limit weights verbose)
245 "Args: (mean-function jacobian y initial-beta
246 epsilon count-limit weights verbose)
247 MEAN-FUNCTION returns the mean response vector for a given parameter vector.
248 JACOBIAN returns the jacobian of MEAN-FUNCTION at a given parameter vector.
249 Y is the observed response vector. Returns the estimated parameter vector
250 obtained by a Gauss-Newton algorithm with backtracking that continues until
251 the COUNT-LIMIT is reached or no component of the parameter vector changes
252 by more than EPSILON."
253 (labels ((rss (beta) ; residual sum of squares
254 (let ((res (- y (funcall f beta))))
255 (sum (if weights (* res res weights) (* res res)))))
256 (next-beta (beta delta rss) ; next beta by backtracking
257 (do* ((lambda 1 (/ lambda 2))
258 (new-rss (rss (+ beta delta))
259 (rss (+ beta (* lambda delta)))))
260 ((or (< new-rss rss) (< lambda .0001))
261 (if (>= lambda .0001)
262 (+ beta (* lambda delta))
263 beta)))))
264 (do* ((delbeta (regression-coefficients
265 (funcall j initial-beta)
266 (- y (funcall f initial-beta))
267 :intercept nil
268 :weights weights)
269 (regression-coefficients
270 (funcall j beta)
271 (- y (funcall f beta))
272 :intercept nil
273 :weights weights))
274 (beta initial-beta (next-beta beta delbeta rss))
275 (rss (rss beta) (rss beta))
276 (count 0 (1+ count)))
277 ((or (> count count-limit) (> epsilon (max (abs delbeta))))
278 (if (and verbose (> count count-limit))
279 (format t "Iteration limit exceeded.~%"))
280 beta)
281 (if verbose (format t "Residual sum of squares: ~10g~%" rss)))))
283 (defun make-jacobian (f n)
284 "Args: (f n)
285 F is a function of an N-vector. Returns a function that approximates the
286 jacobian function iof F by a symmetric difference."
287 (let* ((h .0001)
288 (del (* h (values-list (column-list (identity-matrix n))))))
289 #'(lambda (b)
290 (let ((b+ (mapcar #'(lambda (x) (+ b x)) del))
291 (b- (mapcar #'(lambda (x) (- b x)) del)))
292 ;; FIXME:AJR BAD IDIOM FOLLOWS
293 (apply #'bind-columns (/ (- (mapcar f b+) (mapcar f b-)) (* 2 h)))))))
295 (defun nlreg (f y guess &optional
296 (epsilon .0001) (count-limit 20) weights verbose)
297 "Args: (mean-function y guess &optional
298 (epsilon .0001) (count-limit 20) weights verbose)
299 MEAN-FUNCTION returns the mean response vector for a given parameter vector.
300 Y is the observed response vector. Returns the estimated parameter vector
301 obtained by a Gauss-Newton algorithm that continues until the ITERATION-LIMIT
302 is reached or no component of the parameter vector changes by more than
303 EPSILON. The jacobian of MEAN-FUNCTION is approximated by a symmetric difference."
304 (nlreg1 f (make-jacobian f (length guess)) y guess
305 epsilon count-limit weights verbose))