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.
6 ;;; what this should do:
7 ;;; #1 - use CFFI (and possibly Verazanno) to import C/C++.
8 ;;; #2 - what to do for Fortran? Possibly: C <-> bridge, or CLapack?
9 ;;; problem: would be better to have access to Fortran. For
10 ;;; example, think of Doug Bates comment on reverse-calls (as
11 ;;; distinct from callbacks). It would be difficult if we don't
12 ;;; -- however, has anyone run Lapack or similar through F2CL?
13 ;;; Answer: yes, Matlisp does this.
15 ;;; #3 - Use a lisp-based matrix system drop-in? (matlisp, femlisp, clem, ...?)
19 ;;;; linalg -- Lisp-Stat interface to basic linear algebra routines.
21 ;;;; Copyright (c) 1991, by Luke Tierney. Permission is granted for
22 ;;;; unrestricted use.
28 (defpackage :lisp-stat-linalg
32 (:export chol-decomp lu-decomp lu-solve determinant inverse sv-decomp
33 qr-decomp rcondest make-rotation spline kernel-dens kernel-smooth
34 fft make-sweep-matrix sweep-operator ax
+y numgrad numhess
37 (in-package #:lisp-stat-linalg
)
39 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41 ;;;; Lisp to C number conversion and checking
43 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
46 ;;;; Lisp to/from C sequence and matrix conversion and checking
50 "FIXME:AJR this is not used anywhere?"
53 (defun check-fixnum (a)
54 (if (/= 0 (la-data-mode a
)) (error "not an integer sequence - ~s" a
)))
56 (defun check-real (data)
57 (let ((data (compound-data-seq data
)))
60 (let ((n (length data
)))
64 (check-one-real (aref data i
)))))
65 ((consp data
) (dolist (x data
) (check-one-real x
)))
66 (t (error "bad sequence - ~s" data
)))))
68 (defun vec-assign (a i x
) (setf (aref a i
) x
))
70 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
71 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
73 ;;;; Lisp Interfaces to Linear Algebra Routines
75 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
76 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
78 ;;; FIXME: use dpbt[f2|rf], dpbstf, dpot[f2|rf]; dpptrf, zpbstf, zpbt[f2|rf]
79 ;;; remember: factorization = decomposition, depending on training.
81 (defun chol-decomp (a &optional
(maxoffl 0.0))
83 Modified Cholesky decomposition. A should be a square, symmetric matrix.
84 Computes lower triangular matrix L such that L L^T = A + D where D is a
85 diagonal matrix. If A is strictly positive definite D will be zero.
86 Otherwise, D is as small as possible to make A + D numerically strictly
87 positive definite. Returns a list (L (max D))."
88 (check-square-matrix a
)
90 (let* ((n (array-dimension a
0))
91 (result (make-array (list n n
)))
92 (dpars (list maxoffl
0.0)))
94 (let ((mat (la-data-to-matrix a mode-re
))
95 (dp (la-data-to-vector dpars mode-re
)))
98 (chol-decomp-front mat n dp
)
99 (la-matrix-to-data mat n n mode-re result
)
100 (la-vector-to-data dp
2 mode-re dpars
))
101 (la-free-matrix mat n
)
102 (la-free-vector dp
)))
103 (list result
(second dpars
))))
108 ;;; i.e. result use by:
109 ;;; (setf (values (lu-out1 lu-out2 lu-out3)) (matlisp:lu my-matrix))
110 ;;; for solution, ...
112 ;;; (matlisp:gesv a b &opt ipivot)
116 A is a square matrix of numbers (real or complex). Computes the LU
117 decomposition of A and returns a list of the form (LU IV D FLAG), where
118 LU is a matrix with the L part in the lower triangle, the U part in the
119 upper triangle (the diagonal entries of L are taken to be 1), IV is a vector
120 describing the row permutation used, D is 1 if the number of permutations
121 is odd, -1 if even, and FLAG is T if A is numerically singular, NIL otherwise.
123 (check-square-matrix a
)
124 (let* ((n (array-dimension a
0))
125 (mode (max mode-re
(la-data-mode a
)))
126 (result (list (make-array (list n n
)) (make-array n
) nil nil
)))
127 (let ((mat (la-data-to-matrix a mode
))
128 (iv (la-vector n mode-in
))
129 (d (la-vector 1 mode-re
))
133 (setf singular
(lu-decomp-front mat n iv mode d
))
134 (la-matrix-to-data mat n n mode
(first result
))
135 (la-vector-to-data iv n mode-in
(second result
))
136 (setf (third result
) (la-get-double d
0))
137 (setf (fourth result
) (if (= singular
0.0) nil t
)))
138 (la-free-matrix mat n
)
143 (defun lu-solve (lu lb
)
145 LU is the result of (LU-DECOMP A) for a square matrix A, B is a sequence.
146 Returns the solution to the equation Ax = B. Signals an error if A is
148 (let ((la (first lu
))
150 (check-square-matrix la
)
151 (check-sequence lidx
)
154 (let* ((n (num-rows la
))
155 (result (make-sequence (if (consp lb
) 'list
'vector
) n
))
156 (a-mode (la-data-mode la
))
157 (b-mode (la-data-mode lb
)))
158 (if (/= n
(length lidx
)) (error "index sequence is wrong length"))
159 (if (/= n
(length lb
)) (error "right hand side is wrong length"))
160 (let* ((mode (max mode-re a-mode b-mode
))
161 (a (la-data-to-matrix la mode
))
162 (indx (la-data-to-vector lidx mode-in
))
163 (b (la-data-to-vector lb mode
))
167 (setf singular
(lu-solve-front a n indx b mode
))
168 (la-vector-to-data b n mode result
))
170 (la-free-vector indx
)
172 (if (/= 0.0 singular
) (error "matrix is (numerically) singular"))
175 (defun determinant (a)
177 Returns the determinant of the square matrix M."
178 (let* ((lu (lu-decomp a
))
184 (flet ((fabs (x) (float (abs x
) 0.d0
)))
185 (dotimes (i n
(* d1
(exp d2
)))
187 (let* ((x (aref la i i
))
189 (if (= 0.0 magn
) (return 0.d0
))
190 (setf d1
(* d1
(/ x magn
)))
191 (setf d2
(+ d2
(log magn
))))))))
195 Returns the inverse of the the square matrix M; signals an error if M is ill
196 conditioned or singular"
197 (check-square-matrix a
)
198 (let ((n (num-rows a
))
199 (mode (max mode-re
(la-data-mode a
))))
201 (let ((result (make-array (list n n
) :initial-element
0)))
204 (setf (aref result i i
) 1))
205 (let ((mat (la-data-to-matrix a mode
))
206 (inv (la-data-to-matrix result mode
))
207 (iv (la-vector n mode-in
))
208 (v (la-vector n mode
))
212 (setf singular
(lu-inverse-front mat n iv v mode inv
))
213 (la-matrix-to-data inv n n mode result
))
214 (la-free-matrix mat n
)
215 (la-free-matrix inv n
)
218 (if (/= singular
0) (error "matrix is (numerically) singular"))
222 ;;;; SV Decomposition
227 A is a matrix of real numbers with at least as many rows as columns.
228 Computes the singular value decomposition of A and returns a list of the form
229 (U W V FLAG) where U and V are matrices whose columns are the left and right
230 singular vectors of A and W is the sequence of singular values of A. FLAG is T
231 if the algorithm converged, NIL otherwise."
233 (let* ((m (num-rows a
))
235 (mode (max mode-re
(la-data-mode a
)))
236 (result (list (make-array (list m n
))
238 (make-array (list n n
))
240 (if (< m n
) (error "number of rows less than number of columns"))
241 (if (= mode mode-cx
) (error "complex SVD not available yet"))
242 (let ((mat (la-data-to-matrix a mode
))
243 (w (la-vector n mode-re
))
244 (v (la-matrix n n mode-re
))
248 (setf converged
(sv-decomp-front mat m n w v
))
249 (la-matrix-to-data mat m n mode
(first result
))
250 (la-vector-to-data w n mode
(second result
))
251 (la-matrix-to-data v n n mode
(third result
))
252 (setf (fourth result
) (if (/= 0.0 converged
) t nil
)))
253 (la-free-matrix mat m
)
255 (la-free-matrix v n
))
260 ;;;; QR Decomposition
263 (defun qr-decomp (a &optional pivot
)
264 "Args: (a &optional pivot)
265 A is a matrix of real numbers with at least as many rows as columns. Computes
266 the QR factorization of A and returns the result in a list of the form (Q R).
267 If PIVOT is true the columns of X are first permuted to place insure the
268 absolute values of the diagonal elements of R are nonincreasing. In this case
269 the result includes a third element, a list of the indices of the columns in
270 the order in which they were used."
272 (let* ((m (num-rows a
))
274 (mode (max mode-re
(la-data-mode a
)))
277 (list (make-array (list m n
))
278 (make-array (list n n
))
280 (list (make-array (list m n
)) (make-array (list n n
))))))
281 (if (< m n
) (error "number of rows less than number of columns"))
282 (if (= mode mode-cx
) (error "complex QR decomposition not available yet"))
283 (let ((mat (la-data-to-matrix a mode
))
284 (v (la-matrix n n mode-re
))
285 (jpvt (la-vector n mode-in
)))
288 (qr-decomp-front mat m n v jpvt p
)
289 (la-matrix-to-data mat m n mode
(first result
))
290 (la-matrix-to-data v n n mode
(second result
))
291 (if pivot
(la-vector-to-data jpvt n mode-in
(third result
))))
292 (la-free-matrix mat m
)
294 (la-free-vector jpvt
))
298 ;;;; Estimate of Condition Number for Lower Triangular Matrix
303 Returns an estimate of the reciprocal of the L1 condition number of an upper
304 triangular matrix a."
305 (check-square-matrix a
)
306 (let ((mode (max mode-re
(la-data-mode a
)))
309 (error "complex condition estimate not available yet"))
310 (let ((mat (la-data-to-matrix a mode
))
313 (setf est
(rcondest-front mat n
))
314 (la-free-matrix mat n
))
318 ;;;; Make Rotation Matrix
321 (defun make-rotation (x y
&optional alpha
)
322 "Args: (x y &optional alpha)
323 Returns a rotation matrix for rotating from X to Y, or from X toward Y
324 by angle ALPHA, in radians. X and Y are sequences of the same length."
327 (if alpha
(check-one-real alpha
))
328 (let* ((n (length x
))
329 (mode (max mode-re
(la-data-mode x
) (la-data-mode y
)))
330 (use-angle (if alpha
1 0))
331 (angle (if alpha
(float alpha
0.0) 0.0))
332 (result (make-array (list n n
))))
333 (if (/= n
(length y
)) (error "sequences not the same length"))
334 (if (= mode mode-cx
) (error "complex data not supported yet"))
335 (let ((px (la-data-to-vector x mode-re
))
336 (py (la-data-to-vector y mode-re
))
337 (rot (la-matrix n n mode-re
)))
340 (make-rotation-front n rot px py use-angle angle
)
341 (la-matrix-to-data rot n n mode-re result
))
344 (la-free-matrix rot n
))
348 ;;;; Eigenvalues and Vectors
353 Returns list of list of eigenvalues and list of eigenvectors of square,
354 symmetric matrix A. Third element of result is NIL if algorithm converges.
355 If the algorithm does not converge, the third element is an integer I.
356 In this case the eigenvalues 0, ..., I are not reliable."
357 (check-square-matrix a
)
358 (let ((mode (max mode-re
(la-data-mode a
)))
360 (if (= mode mode-cx
) (error "matrix must be real and symmetric"))
361 (let ((evals (make-array n
))
362 (evecs (make-list (* n n
)))
363 (pa (la-data-to-vector (compound-data-seq a
) mode-re
))
364 (w (la-vector n mode-re
))
365 (z (la-vector (* n n
) mode-re
))
366 (fv1 (la-vector n mode-re
))
370 (setf ierr
(eigen-front pa n w z fv1
))
371 (la-vector-to-data w n mode-re evals
)
372 (la-vector-to-data z
(* n n
) mode-re evecs
))
376 (la-free-vector fv1
))
377 (list (nreverse evals
)
378 (nreverse (mapcar #'(lambda (x) (coerce x
'vector
))
379 (split-list evecs n
)))
380 (if (/= 0 ierr
) (- n ierr
))))))
383 ;;;; Spline Interpolation
386 (defun make-smoother-args (x y xvals
)
392 (unless (integerp xvals
)
393 (check-sequence xvals
)
395 (let* ((n (length x
))
396 (ns (if (integerp xvals
) xvals
(length xvals
)))
397 (result (list (make-list ns
) (make-list ns
))))
398 (if (and y
(/= n
(length y
))) (error "sequences not the same length"))
399 (list x y n
(if (integerp xvals
) 0 1) ns xvals result
)))
401 (defun get-smoother-result (args) (seventh args
))
403 (defmacro with-smoother-data
((x y xvals is-reg
) &rest body
)
410 (unless (integerp ,xvals
)
411 (check-sequence ,xvals
)
413 (let* ((supplied (not (integerp ,xvals
)))
415 (ns (if supplied
(length ,xvals
) ,xvals
))
416 (result (list (make-list ns
) (make-list ns
))))
417 (if (and ,is-reg
(/= n
(length ,y
)))
418 (error "sequences not the same length"))
419 (if (and (not supplied
) (< ns
2))
420 (error "too few points for interpolation"))
421 (let* ((px (la-data-to-vector ,x mode-re
))
422 (py (if ,is-reg
(la-data-to-vector ,y mode-re
)))
424 (la-data-to-vector ,xvals mode-re
)
425 (la-vector ns mode-re
)))
426 (pys (la-vector ns mode-re
)))
427 (unless supplied
(la-range-to-rseq n px ns pxs
))
430 (la-vector-to-data pxs ns mode-re
(first result
))
431 (la-vector-to-data pys ns mode-re
(second result
)))
433 (if ,is-reg
(la-free-vector py
))
435 (la-free-vector pys
))
438 (defun spline (x y
&key
(xvals 30))
439 "Args: (x y &key xvals)
440 Returns list of x and y values of natural cubic spline interpolation of (X,Y).
441 X must be strictly increasing. XVALS can be an integer, the number of equally
442 spaced points to use in the range of X, or it can be a sequence of points at
443 which to interpolate."
444 (with-smoother-data (x y xvals t
)
445 (let ((work (la-vector (* 2 n
) mode-re
))
448 (setf error
(spline-front n px py ns pxs pys work
))
449 (la-free-vector work
))
450 (if (/= error
0) (error "bad data for splines")))))
453 ;;;; Kernel Density Estimators and Smoothers
456 (defun kernel-type-code (type)
457 (cond ((eq type
'u
) 0)
462 (defun kernel-dens (x &key
(type 'b
) (width -
1.0) (xvals 30))
463 "Args: (x &key xvals width type)
464 Returns list of x and y values of kernel density estimate of X. XVALS can be an
465 integer, the number of equally spaced points to use in the range of X, or it
466 can be a sequence of points at which to interpolate. WIDTH specifies the
467 window width. TYPE specifies the lernel and should be one of the symbols G, T,
468 U or B for gaussian, triangular, uniform or bisquare. The default is B."
469 (check-one-real width
)
470 (with-smoother-data (x nil xvals nil
) ;; warning about deleting unreachable code is TRUE -- 2nd arg=nil!
471 (let ((code (kernel-type-code type
))
473 (setf error
(kernel-dens-front px n width pxs pys ns code
))
474 (if (/= 0 error
) (error "bad kernel density data")))))
476 (defun kernel-smooth (x y
&key
(type 'b
) (width -
1.0) (xvals 30))
477 "Args: (x y &key xvals width type)
478 Returns list of x and y values of kernel smooth of (X,Y). XVALS can be an
479 integer, the number of equally spaced points to use in the range of X, or it
480 can be a sequence of points at which to interpolate. WIDTH specifies the
481 window width. TYPE specifies the lernel and should be one of the symbols G, T,
482 U or B for Gaussian, triangular, uniform or bisquare. The default is B."
483 (check-one-real width
)
484 (with-smoother-data (x y xvals t
)
485 (let ((code (kernel-type-code type
))
487 ;;(kernel-smooth-front px py n width pxs pys ns code)
488 (kernel-smooth-Cport px py n width pxs pys ns code
)
489 (if (/= 0 error
) (error "bad kernel density data")))))
493 (defun kernel-smooth-Cport (px py n width
;;wts wds ;; see above for mismatch?
495 "Port of kernel_smooth (Lib/kernel.c) to Lisp.
496 FIXME:kernel-smooth-Cport"
498 ((and (< n
2) (<= width
0)) 1.0)
499 (t (let* ((xmin (min px
))
501 (width (/ (- xmax xmin
) (+ 1.0 (log n
)))))
502 (dotimes (i (- ns
1))
506 (dotimes (j (- n
1)) )
507 ;;;possible nasty errors...
510 ((lwidth (if wds
(* width
(aref wds j
)) width
))
511 (lwt (* (kernel-Cport (aref xs i
) (aref px j
) lwidth ktype
) ;; px?
512 (if wts
(aref wts j
) 1.0))))
513 (setf wsum
(+ wsum lwt
))
514 (setf ysum
(if py
(+ ysum
(* lwt
(aref py j
)))))) ;; py? y?
524 (defun kernel-Cport (x y w ktype
)
525 "Port of kernel() (Lib/kernel.c) to Lisp.
526 x,y,w are doubles, type is an integer"
530 (cond ((eq ktype
"B")
535 (/ (/ (* 15.0 (* (- 1.0 (* 4 z z
)) ;; k/w
536 (- 1.0 (* 4 z z
)))) ;; k/w
541 (let* ((w (* w
0.25))
543 (k (/ (exp (* -
0.5 z z
))
549 (k (if (< (abs z
) 0.5)
554 (cond ((and (> z -
1.0)
565 ;;;; Lowess Smoother Interface
568 (defun |base-lowess|
(s1 s2 f nsteps delta
)
574 (check-one-fixnum nsteps
)
575 (check-one-real delta
)
576 (let* ((n (length s1
))
577 (result (make-list n
)))
578 (if (/= n
(length s2
)) (error "sequences not the same length"))
579 (let ((x (la-data-to-vector s1 mode-re
))
580 (y (la-data-to-vector s2 mode-re
))
581 (ys (la-vector n mode-re
))
582 (rw (la-vector n mode-re
))
583 (res (la-vector n mode-re
))
587 (setf error
(base-lowess-front x y n f nsteps delta ys rw res
))
588 (la-vector-to-data ys n mode-re result
))
593 (la-free-vector res
))
594 (if (/= error
0) (error "bad data for lowess"))
598 static LVAL add_contour_point
(i, j
, k
, l
, x
, y
, z
, v
, result
)
608 if
((z[i][j] <= v && v < z[k][l]) || (z[k][l] <= v && v < z[i][j])) {
611 p = (v - z[i][j]) / (z[k][l] - z[i][j]);
613 rplaca(pt, cvflonum((FLOTYPE) (q * x[i] + p * x[k])));
614 rplaca
(cdr(pt), cvflonum
((FLOTYPE) (q * y
[j] + p * y[l])));
615 result = cons(pt, result);
621 LVAL xssurface_contour()
623 LVAL s1, s2, mat, result;
629 s1 = xsgetsequence();
630 s2 = xsgetsequence();
632 v = makedouble(xlgetarg());
635 n = seqlen(s1); m = seqlen(s2);
636 if (n != numrows(mat) || m != numcols(mat)) xlfail("dimensions do not match");
637 if (data_mode(s1) == CX || data_mode(s2) == CX || data_mode(mat) == CX)
638 xlfail("data must be real");
640 x = (RVector) data_to_vector(s1, RE);
641 y = (RVector) data_to_vector(s2, RE);
642 z = (RMatrix) data_to_matrix(mat, RE);
646 for (i = 0; i < n - 1; i++) {
647 for (j = 0; j < m - 1; j++) {
648 result = add_contour_point(i, j, i, j+1, x, y, z, v, result);
649 result = add_contour_point(i, j+1, i+1, j+1, x, y, z, v, result);
650 result = add_contour_point(i+1, j+1, i+1, j, x, y, z, v, result);
651 result = add_contour_point(i+1, j, i, j, x, y, z, v, result);
668 ;;; ??replace with matlisp:fft and matlisp:ifft (the latter for inverse mapping)
670 (defun fft (x &optional inverse)
671 "Args: (x &optional inverse)
672 Returns unnormalized Fourier transform of X, or inverse transform if INVERSE
675 (let* ((n (length x))
676 (mode (la-data-mode x))
677 (isign (if inverse -1 1))
678 (result (if (consp x) (make-list n) (make-array n))))
679 (let ((px (la-data-to-vector x mode-cx))
680 (work (la-vector (+ (* 4 n) 15) mode-re)))
683 (fft-front n px work isign)
684 (la-vector-to-data px n mode-cx result))
686 (la-free-vector work))
690 ;;; SWEEP Operator: FIXME: use matlisp
693 (defun make-sweep-front (x y w n p mode has_w x_mean result)
694 (declare (fixnum n p mode has_w))
709 (has-w (if (/= 0 has_w) t nil))
711 (declare (long-float val dxi dyi dv dw sum_w dxik dxjk dyj
712 dx_meani dx_meanj dy_mean))
713 ;; (declare-double val dxi dyi dv dw sum_w dxik dxjk dyj
714 ;; dx_meani dx_meanj dy_mean)
716 (if (> mode RE) (error "not supported for complex data yet"))
718 (setf x_data (compound-data-seq x))
719 (setf result_data (compound-data-seq result))
721 ;; find the mean of y
726 (setf dyi (makedouble (aref y i)))
728 (setf dw (makedouble (aref w i)))
730 (setf dyi (* dyi dw)))
732 (if (not has-w) (setf sum_w (float n 0.0)))
733 (if (<= sum_w 0.0) (error "non positive sum of weights"))
734 (setf dy_mean (/ val sum_w))
736 ;; find the column means
742 (setf dxi (makedouble (aref x_data (+ (* p i) j))))
744 (setf dw (makedouble (aref w i)))
745 (setf dxi (* dxi dw)))
747 (setf (aref x_mean j) (/ val sum_w)))
749 ;; put 1/sum_w in topleft, means on left, minus means on top
750 (setf (aref result_data 0) (/ 1.0 sum_w))
753 (setf dxi (makedouble (aref x_mean i)))
754 (setf (aref result_data (+ i 1)) (- dxi))
755 (setf (aref result_data (* (+ i 1) (+ p 2))) dxi))
756 (setf (aref result_data (+ p 1)) (- dy_mean))
757 (setf (aref result_data (* (+ p 1) (+ p 2))) dy_mean)
759 ;; put sums of adjusted cross products in body
767 (setf dxik (makedouble (aref x_data (+ (* p k) i))))
768 (setf dxjk (makedouble (aref x_data (+ (* p k) j))))
769 (setf dx_meani (makedouble (aref x_mean i)))
770 (setf dx_meanj (makedouble (aref x_mean j)))
771 (setf dv (* (- dxik dx_meani) (- dxjk dx_meanj)))
773 (setf dw (makedouble (aref w k)))
776 (setf (aref result_data (+ (* (+ i 1) (+ p 2)) (+ j 1))) val)
777 (setf (aref result_data (+ (* (+ j 1) (+ p 2)) (+ i 1))) val))
781 (setf dxik (makedouble (aref x_data (+ (* p j) i))))
782 (setf dyj (makedouble (aref y j)))
783 (setf dx_meani (makedouble (aref x_mean i)))
784 (setf dv (* (- dxik dx_meani) (- dyj dy_mean)))
786 (setf dw (makedouble (aref w j)))
789 (setf (aref result_data (+ (* (+ i 1) (+ p 2)) (+ p 1))) val)
790 (setf (aref result_data (+ (* (+ p 1) (+ p 2)) (+ i 1))) val))
794 (setf dyj (makedouble (aref y j)))
795 (setf dv (* (- dyj dy_mean) (- dyj dy_mean)))
797 (setf dw (makedouble (aref w j)))
800 (setf (aref result_data (+ (* (+ p 1) (+ p 2)) (+ p 1))) val)))
802 ;;; FIXME: use matlisp
803 (defun sweep-in-place-front (a rows cols mode k tol)
804 "Sweep algorithm for linear regression."
805 (declare (long-float tol))
806 (declare (fixnum rows cols mode k))
814 (declare (long-float pivot aij aik akj akk))
816 (if (> mode RE) (error "not supported for complex data yet"))
817 (if (or (< k 0) (>= k rows) (>= k cols)) (error "index out of range"))
819 (setf tol (max tol machine-epsilon))
820 (setf data (compound-data-seq a))
822 (setf pivot (makedouble (aref data (+ (* cols k) k))))
825 ((or (> pivot tol) (< pivot (- tol)))
830 (when (and (/= i k) (/= j k))
831 (setf aij (makedouble (aref data (+ (* cols i) j))))
832 (setf aik (makedouble (aref data (+ (* cols i) k))))
833 (setf akj (makedouble (aref data (+ (* cols k) j))))
834 (setf aij (- aij (/ (* aik akj) pivot)))
835 (setf (aref data (+ (* cols i) j)) aij))))
839 (setf aik (makedouble (aref data (+ (* cols i) k))))
841 (setf aik (/ aik pivot))
842 (setf (aref data (+ (* cols i) k)) aik)))
846 (setf akj (makedouble (aref data (+ (* cols k) j))))
848 (setf akj (- (/ akj pivot)))
849 (setf (aref data (+ (* cols k) j)) akj)))
851 (setf akk (/ 1.0 pivot))
852 (setf (aref data (+ (* cols k) k)) akk)
856 ;; FIXME: use matlisp
857 (defun make-sweep-matrix (x y &optional w)
858 "Args: (x y &optional weights)
859 X is matrix, Y and WEIGHTS are sequences. Returns the sweep matrix of the
860 (weighted) regression of Y on X"
863 (if w (check-sequence w))
864 (let ((n (num-rows x))
866 (if (/= n (length y)) (error "dimensions do not match"))
867 (if (and w (/= n (length w))) (error "dimensions do not match"))
868 (let ((mode (max (la-data-mode x)
870 (if w (la-data-mode w) 0)))
871 (result (make-array (list (+ p 2) (+ p 2))))
872 (x-mean (make-array p))
873 (y (coerce y 'vector))
874 (w (if w (coerce w 'vector)))
876 (make-sweep-front x y w n p mode has-w x-mean result)
879 (defun sweep-in-place (a k tol)
883 (let ((rows (num-rows a))
885 (mode (la-data-mode a)))
886 (let ((swept (sweep-in-place-front a rows cols mode k tol)))
887 (if (/= 0 swept) t nil))))
889 (defun sweep-operator (a columns &optional tolerances)
890 "Args: (a indices &optional tolerances)
891 A is a matrix, INDICES a sequence of the column indices to be swept. Returns
892 a list of the swept result and the list of the columns actually swept. (See
893 MULTREG documentation.) If supplied, TOLERANCES should be a list of real
894 numbers the same length as INDICES. An index will only be swept if its pivot
895 element is larger than the corresponding element of TOLERANCES."
897 (check-sequence columns)
898 (if tolerances (check-sequence tolerances))
900 (check-fixnum columns)
901 (if tolerances (check-real tolerances))
903 (result (copy-array a))
905 (columns (coerce columns 'list) (cdr columns))
906 (tolerances (if (consp tolerances) (coerce tolerances 'list))
907 (if (consp tolerances) (cdr tolerances))))
908 ((null columns) (list result swept-columns))
909 (let ((col (first columns))
910 (tol (if (consp tolerances) (first tolerances) tol)))
911 (if (sweep-in-place result col tol)
912 (setf swept-columns (cons col swept-columns))))))
921 (defun ax+y (a x y &optional lower)
922 "Args (a x y &optional lower)
923 Returns (+ (matmult A X) Y). If LOWER is not nil, A is taken to be lower
925 This could probably be made more efficient."
926 (check-square-matrix a)
932 (let* ((n (num-rows a))
933 (result (make-list n))
934 (a (compound-data-seq a)))
936 (if (or (/= n (length x)) (/= n (length y)))
937 (error "dimensions do not match"))
938 (do* ((tx (make-next-element x) (make-next-element x))
939 (ty (make-next-element y))
940 (tr (make-next-element result))
942 (start 0 (+ start n))
943 (end (if lower (+ i 1) n) (if lower (+ i 1) n)))
945 (declare (fixnum i start end))
946 (let ((val (get-next-element ty i)))
949 (setf val (+ val (* (get-next-element tx j)
950 (aref a (+ start j))))))
951 (set-next-element tr i val)))))
954 ;;;; Maximization and Numerical Derivatives
957 (defvar *maximize-callback-function* nil)
958 (defvar *maximize-callback-arg* nil)
960 (defun data2double (n data ptr)
962 (let* ((seq (compound-data-seq data))
963 (elem (make-next-element seq)))
964 (if (/= (length seq) n) (error "bad data size"))
967 (la-put-double ptr i (get-next-element elem i)))))
969 (defun maximize-callback (n px pfval pgrad phess pderivs)
970 (la-vector-to-data px n mode-re *maximize-callback-arg*)
971 (let* ((val (funcall *maximize-callback-function* *maximize-callback-arg*))
972 (derivs (if (consp val) (- (length val) 1) 0)))
973 (la-put-integer pderivs 0 derivs)
974 (la-put-double pfval 0 (if (consp val) (first val) val))
975 (if (<= 1 derivs) (data2double n (second val) pgrad))
976 (if (<= 2 derivs) (data2double (* n n) (third val) phess))))
978 (defun numgrad (f x &optional scale (h -1.0))
979 "Args: (f x &optional scale derivstep)
980 Computes the numerical gradient of F at X."
984 (check-sequence scale)
987 (let* ((n (length x))
988 (result (make-list n)))
989 (if (and scale (/= n (length scale)))
990 (error "scale not the same length as x"))
991 (let ((*maximize-callback-function* f)
992 (*maximize-callback-arg* (make-list n)))
993 (let ((px (la-data-to-vector x mode-re))
994 (pgrad (la-vector n mode-re))
995 (pscale (la-data-to-vector
996 (if scale scale (make-list n :initial-element 1.0))
1000 (numgrad-front n px pgrad h pscale)
1001 (la-vector-to-data pgrad n mode-re result))
1003 (la-free-vector pgrad)
1004 (la-free-vector pscale))))
1007 (defun numhess (f x &optional scale (h -1.0) all)
1008 "Args: (f x &optional scale derivstep)
1009 Computes the numerical Hessian matrix of F at X."
1013 (check-sequence scale)
1016 (let* ((n (length x))
1018 (list nil (make-list n) (make-array (list n n)))
1019 (make-array (list n n)))))
1020 (if (and scale (/= n (length scale)))
1021 (error "scale not the same length as x"))
1022 (let ((*maximize-callback-function* f)
1023 (*maximize-callback-arg* (make-list n)))
1024 (let ((hess-data (compound-data-seq (if all (third result) result)))
1025 (px (la-data-to-vector x mode-re))
1026 (pf (la-vector 1 mode-re))
1027 (pgrad (la-vector n mode-re))
1028 (phess (la-vector (* n n) mode-re))
1029 (pscale (la-data-to-vector
1030 (if scale scale (make-list n :initial-element 1.0))
1034 (numhess-front n px pf pgrad phess h pscale)
1036 (setf (first result) (la-get-double pf 0))
1037 (la-vector-to-data pgrad n mode-re (second result)))
1038 (la-vector-to-data phess (* n n) mode-re hess-data))
1041 (la-free-vector pgrad)
1042 (la-free-vector phess)
1043 (la-free-vector pscale))))