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
36 :lisp-stat-compound-data
37 :lisp-stat-linalg-data
39 (:shadowing-import-from
:lisp-stat-math
40 expt
+ -
* / ** mod rem abs
1+ 1- log exp sqrt sin cos tan
41 asin acos atan sinh cosh tanh asinh acosh atanh float random
42 truncate floor ceiling round minusp zerop plusp evenp oddp
43 < <= = /= >= > complex conjugate realpart imagpart phase
44 min max logand logior logxor lognot ffloor fceiling
45 ftruncate fround signum cis
)
46 (:export chol-decomp lu-decomp lu-solve determinant inverse sv-decomp
47 qr-decomp rcondest make-rotation spline kernel-dens kernel-smooth
48 fft make-sweep-matrix sweep-operator ax
+y eigen
))
50 (in-package #:lisp-stat-linalg
)
54 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
56 ;;; Lisp Interfaces to Linear Algebra Routines
58 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
61 ;;; Cholesky Decomposition
64 (cffi:defcfun
("ccl_chol_decomp_front" ccl-chol-decomp-front
)
65 :int
(x :pointer
) (y :int
) (z :pointer
))
66 (defun chol-decomp-front (x y z
)
67 (ccl-chol-decomp-front x y z
))
73 (cffi:defcfun
("ccl_lu_decomp_front" ccl-lu-decomp-front
)
74 :int
(x :pointer
) (y :int
) (z :pointer
) (u :int
) (v :pointer
))
75 (defun lu-decomp-front (x y z u v
)
76 (ccl-lu-decomp-front x y z u v
))
78 (cffi:defcfun
("ccl_lu_solve_front" ccl-lu-solve-front
)
79 :int
(x :pointer
) (y :int
) (z :pointer
) (u :pointer
) (v :int
))
80 (defun lu-solve-front (x y z u v
)
81 (ccl-lu-solve-front x y z u v
))
83 (cffi:defcfun
("ccl_lu_inverse_front" ccl-lu-inverse-front
)
84 :int
(x :pointer
) (y :int
) (z :pointer
) (u :pointer
) (v :int
) (w :pointer
))
85 (defun lu-inverse-front (x y z u v w
)
86 (ccl-lu-inverse-front x y z u v w
))
92 (cffi:defcfun
("ccl_sv_decomp_front" ccl-sv-decomp-front
)
93 :int
(x :pointer
) (y :int
) (z :int
) (u :pointer
) (v :pointer
))
94 (defun sv-decomp-front (x y z u v
)
95 (ccl-sv-decomp-front x y z u v
))
101 (cffi:defcfun
("ccl_qr_decomp_front" ccl-qr-decomp-front
)
102 :int
(x :pointer
) (y :int
) (z :int
) (u :pointer
) (v :pointer
) (w :int
))
103 (defun qr-decomp-front (x y z u v w
)
104 (ccl-qr-decomp-front x y z u v w
))
107 ;;;; Estimate of Condition Number for Lower Triangular Matrix
110 (cffi:defcfun
("ccl_rcondest_front" ccl-rcondest-front
)
111 :double
(x :pointer
) (y :int
))
112 (defun rcondest-front (x y
)
113 (ccl-rcondest-front x y
))
116 ;;;; Make Rotation Matrix
119 (cffi:defcfun
("ccl_make_rotation_front" ccl-make-rotation-front
)
120 :int
(x :int
) (y :pointer
) (z :pointer
) (u :pointer
) (v :int
) (w :double
))
121 (defun make-rotation-front (x y z u v w
)
122 (ccl-make-rotation-front x y z u v
(float w
1d0
)))
125 ;;;; Eigenvalues and Eigenvectors
128 (cffi:defcfun
("ccl_eigen_front" ccl-eigen-front
)
129 :int
(x :pointer
) (y :int
) (z :pointer
) (u :pointer
) (v :pointer
))
130 (defun eigen-front (x y z u v
)
131 (ccl-eigen-front x y z u v
))
134 ;;;; Spline Interpolation
137 (cffi:defcfun
("ccl_range_to_rseq" ccl-range-to-rseq
)
138 :int
(x :int
) (y :pointer
) (z :int
) (u :pointer
))
139 (defun la-range-to-rseq (x y z u
)
140 (ccl-range-to-rseq x y z u
))
142 (cffi:defcfun
("ccl_spline_front" ccl-spline-front
)
143 :int
(x :int
) (y :pointer
) (z :pointer
) (u :int
) (v :pointer
) (w :pointer
) (a :pointer
))
144 (defun spline-front (x y z u v w a
)
145 (ccl-spline-front x y z u v w a
))
148 ;;;; Kernel Density Estimators and Smoothers
151 (cffi:defcfun
("ccl_kernel_dens_front" ccl-kernel-dens-front
)
152 :int
(x :pointer
) (y :int
) (z :double
) (u :pointer
) (v :pointer
) (w :int
) (a :int
))
153 (defun kernel-dens-front (x y z u v w a
)
154 (ccl-kernel-dens-front x y
(float z
1d0
) u v w a
))
156 (cffi:defcfun
("ccl_kernel_smooth_front" ccl-kernel-smooth-front
)
157 :int
(x :pointer
) (y :pointer
) (z :int
) (u :double
) (v :pointer
) (w :pointer
) (a :int
) (b :int
))
158 (defun kernel-smooth-front (x y z u v w a b
)
159 (ccl-kernel-smooth-front x y z
(float u
1d0
) v w a b
))
162 ;;;; Lowess Smoother Interface
165 (cffi:defcfun
("ccl_base_lowess_front" ccl-base-lowess-front
)
166 :int
(x :pointer
) (y :pointer
) (z :int
) (u :double
) (v :int
) (w :double
) (a :pointer
) (b :pointer
) (c :pointer
))
167 (defun base-lowess-front (x y z u v w a b c
)
168 (ccl-base-lowess-front x y z
(float u
1d0
) v
(float w
1d0
) a b c
))
174 (cffi:defcfun
("ccl_fft_front" ccl-fft-front
)
175 :int
(x :int
) (y :pointer
) (z :pointer
) (u :int
))
176 (defun fft-front (x y z u
)
177 (ccl-fft-front x y z u
))
182 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
184 ;;;; Lisp to C number conversion and checking
186 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
189 ;;;; Lisp to/from C sequence and matrix conversion and checking
193 "FIXME:AJR this is not used anywhere?"
196 (defun check-fixnum (a)
197 (if (/= 0 (la-data-mode a
)) (error "not an integer sequence - ~s" a
)))
199 (defun check-real (data)
200 (let ((data (compound-data-seq data
)))
203 (let ((n (length data
)))
207 (check-one-real (aref data i
)))))
208 ((consp data
) (dolist (x data
) (check-one-real x
)))
209 (t (error "bad sequence - ~s" data
)))))
211 (defun vec-assign (a i x
) (setf (aref a i
) x
))
213 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
214 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
216 ;;;; Lisp Interfaces to Linear Algebra Routines
218 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
219 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
221 ;;; FIXME: use dpbt[f2|rf], dpbstf, dpot[f2|rf]; dpptrf, zpbstf, zpbt[f2|rf]
222 ;;; remember: factorization = decomposition, depending on training.
224 (defun chol-decomp (a &optional
(maxoffl 0.0))
226 Modified Cholesky decomposition. A should be a square, symmetric matrix.
227 Computes lower triangular matrix L such that L L^T = A + D where D is a
228 diagonal matrix. If A is strictly positive definite D will be zero.
229 Otherwise, D is as small as possible to make A + D numerically strictly
230 positive definite. Returns a list (L (max D))."
231 (check-square-matrix a
)
233 (let* ((n (array-dimension a
0))
234 (result (make-array (list n n
)))
235 (dpars (list maxoffl
0.0)))
237 (let ((mat (la-data-to-matrix a
+mode-re
+))
238 (dp (la-data-to-vector dpars
+mode-re
+)))
241 (chol-decomp-front mat n dp
)
242 (la-matrix-to-data mat n n
+mode-re
+ result
)
243 (la-vector-to-data dp
2 +mode-re
+ dpars
))
244 (la-free-matrix mat n
)
245 (la-free-vector dp
)))
246 (list result
(second dpars
))))
251 ;;; i.e. result use by:
252 ;;; (setf (values (lu-out1 lu-out2 lu-out3)) (matlisp:lu my-matrix))
253 ;;; for solution, ...
255 ;;; (matlisp:gesv a b &opt ipivot)
259 A is a square matrix of numbers (real or complex). Computes the LU
260 decomposition of A and returns a list of the form (LU IV D FLAG), where
261 LU is a matrix with the L part in the lower triangle, the U part in the
262 upper triangle (the diagonal entries of L are taken to be 1), IV is a vector
263 describing the row permutation used, D is 1 if the number of permutations
264 is odd, -1 if even, and FLAG is T if A is numerically singular, NIL otherwise.
266 (check-square-matrix a
)
267 (let* ((n (array-dimension a
0))
268 (mode (max +mode-re
+ (la-data-mode a
)))
269 (result (list (make-array (list n n
)) (make-array n
) nil nil
)))
270 (let ((mat (la-data-to-matrix a mode
))
271 (iv (la-vector n
+mode-in
+))
272 (d (la-vector 1 +mode-re
+))
276 (setf singular
(lu-decomp-front mat n iv mode d
))
277 (la-matrix-to-data mat n n mode
(first result
))
278 (la-vector-to-data iv n
+mode-in
+ (second result
))
279 (setf (third result
) (la-get-double d
0))
280 (setf (fourth result
) (if (= singular
0.0) nil t
)))
281 (la-free-matrix mat n
)
286 (defun lu-solve (lu lb
)
288 LU is the result of (LU-DECOMP A) for a square matrix A, B is a sequence.
289 Returns the solution to the equation Ax = B. Signals an error if A is
291 (let ((la (first lu
))
293 (check-square-matrix la
)
294 (check-sequence lidx
)
297 (let* ((n (num-rows la
))
298 (result (make-sequence (if (consp lb
) 'list
'vector
) n
))
299 (a-mode (la-data-mode la
))
300 (b-mode (la-data-mode lb
)))
301 (if (/= n
(length lidx
)) (error "index sequence is wrong length"))
302 (if (/= n
(length lb
)) (error "right hand side is wrong length"))
303 (let* ((mode (max +mode-re
+ a-mode b-mode
))
304 (a (la-data-to-matrix la mode
))
305 (indx (la-data-to-vector lidx
+mode-in
+))
306 (b (la-data-to-vector lb mode
))
310 (setf singular
(lu-solve-front a n indx b mode
))
311 (la-vector-to-data b n mode result
))
313 (la-free-vector indx
)
315 (if (/= 0.0 singular
) (error "matrix is (numerically) singular"))
318 (defun determinant (a)
320 Returns the determinant of the square matrix M."
321 (let* ((lu (lu-decomp a
))
327 (flet ((fabs (x) (float (abs x
) 0.d0
)))
328 (dotimes (i n
(* d1
(exp d2
)))
330 (let* ((x (aref la i i
))
332 (if (= 0.0 magn
) (return 0.d0
))
333 (setf d1
(* d1
(/ x magn
)))
334 (setf d2
(+ d2
(log magn
))))))))
338 Returns the inverse of the the square matrix M; signals an error if M is ill
339 conditioned or singular"
340 (check-square-matrix a
)
341 (let ((n (num-rows a
))
342 (mode (max +mode-re
+ (la-data-mode a
))))
344 (let ((result (make-array (list n n
) :initial-element
0)))
347 (setf (aref result i i
) 1))
348 (let ((mat (la-data-to-matrix a mode
))
349 (inv (la-data-to-matrix result mode
))
350 (iv (la-vector n
+mode-in
+))
351 (v (la-vector n mode
))
355 (setf singular
(lu-inverse-front mat n iv v mode inv
))
356 (la-matrix-to-data inv n n mode result
))
357 (la-free-matrix mat n
)
358 (la-free-matrix inv n
)
361 (if (/= singular
0) (error "matrix is (numerically) singular"))
365 ;;;; SV Decomposition
370 A is a matrix of real numbers with at least as many rows as columns.
371 Computes the singular value decomposition of A and returns a list of the form
372 (U W V FLAG) where U and V are matrices whose columns are the left and right
373 singular vectors of A and W is the sequence of singular values of A. FLAG is T
374 if the algorithm converged, NIL otherwise."
376 (let* ((m (num-rows a
))
378 (mode (max +mode-re
+ (la-data-mode a
)))
379 (result (list (make-array (list m n
))
381 (make-array (list n n
))
383 (if (< m n
) (error "number of rows less than number of columns"))
384 (if (= mode
+mode-cx
+) (error "complex SVD not available yet"))
385 (let ((mat (la-data-to-matrix a mode
))
386 (w (la-vector n
+mode-re
+))
387 (v (la-matrix n n
+mode-re
+))
391 (setf converged
(sv-decomp-front mat m n w v
))
392 (la-matrix-to-data mat m n mode
(first result
))
393 (la-vector-to-data w n mode
(second result
))
394 (la-matrix-to-data v n n mode
(third result
))
395 (setf (fourth result
) (if (/= 0.0 converged
) t nil
)))
396 (la-free-matrix mat m
)
398 (la-free-matrix v n
))
403 ;;;; QR Decomposition
406 (defun qr-decomp (a &optional pivot
)
407 "Args: (a &optional pivot)
408 A is a matrix of real numbers with at least as many rows as columns. Computes
409 the QR factorization of A and returns the result in a list of the form (Q R).
410 If PIVOT is true the columns of X are first permuted to place insure the
411 absolute values of the diagonal elements of R are nonincreasing. In this case
412 the result includes a third element, a list of the indices of the columns in
413 the order in which they were used."
415 (let* ((m (num-rows a
))
417 (mode (max +mode-re
+ (la-data-mode a
)))
420 (list (make-array (list m n
))
421 (make-array (list n n
))
423 (list (make-array (list m n
)) (make-array (list n n
))))))
424 (if (< m n
) (error "number of rows less than number of columns"))
425 (if (= mode
+mode-cx
+) (error "complex QR decomposition not available yet"))
426 (let ((mat (la-data-to-matrix a mode
))
427 (v (la-matrix n n
+mode-re
+))
428 (jpvt (la-vector n
+mode-in
+)))
431 (qr-decomp-front mat m n v jpvt p
)
432 (la-matrix-to-data mat m n mode
(first result
))
433 (la-matrix-to-data v n n mode
(second result
))
434 (if pivot
(la-vector-to-data jpvt n
+mode-in
+ (third result
))))
435 (la-free-matrix mat m
)
437 (la-free-vector jpvt
))
441 ;;;; Estimate of Condition Number for Lower Triangular Matrix
446 Returns an estimate of the reciprocal of the L1 condition number of an upper
447 triangular matrix a."
448 (check-square-matrix a
)
449 (let ((mode (max +mode-re
+ (la-data-mode a
)))
451 (if (= mode
+mode-cx
+)
452 (error "complex condition estimate not available yet"))
453 (let ((mat (la-data-to-matrix a mode
))
456 (setf est
(rcondest-front mat n
))
457 (la-free-matrix mat n
))
461 ;;;; Make Rotation Matrix
464 (defun make-rotation (x y
&optional alpha
)
465 "Args: (x y &optional alpha)
466 Returns a rotation matrix for rotating from X to Y, or from X toward Y
467 by angle ALPHA, in radians. X and Y are sequences of the same length."
470 (if alpha
(check-one-real alpha
))
471 (let* ((n (length x
))
472 (mode (max +mode-re
+ (la-data-mode x
) (la-data-mode y
)))
473 (use-angle (if alpha
1 0))
474 (angle (if alpha
(float alpha
0.0) 0.0))
475 (result (make-array (list n n
))))
476 (if (/= n
(length y
)) (error "sequences not the same length"))
477 (if (= mode
+mode-cx
+) (error "complex data not supported yet"))
478 (let ((px (la-data-to-vector x
+mode-re
+))
479 (py (la-data-to-vector y
+mode-re
+))
480 (rot (la-matrix n n
+mode-re
+)))
483 (make-rotation-front n rot px py use-angle angle
)
484 (la-matrix-to-data rot n n
+mode-re
+ result
))
487 (la-free-matrix rot n
))
491 ;;;; Eigenvalues and Vectors
496 Returns list of list of eigenvalues and list of eigenvectors of square,
497 symmetric matrix A. Third element of result is NIL if algorithm converges.
498 If the algorithm does not converge, the third element is an integer I.
499 In this case the eigenvalues 0, ..., I are not reliable."
500 (check-square-matrix a
)
501 (let ((mode (max +mode-re
+ (la-data-mode a
)))
503 (if (= mode
+mode-cx
+) (error "matrix must be real and symmetric"))
504 (let ((evals (make-array n
))
505 (evecs (make-list (* n n
)))
506 (pa (la-data-to-vector (compound-data-seq a
) +mode-re
+))
507 (w (la-vector n
+mode-re
+))
508 (z (la-vector (* n n
) +mode-re
+))
509 (fv1 (la-vector n
+mode-re
+))
513 (setf ierr
(eigen-front pa n w z fv1
))
514 (la-vector-to-data w n
+mode-re
+ evals
)
515 (la-vector-to-data z
(* n n
) +mode-re
+ evecs
))
519 (la-free-vector fv1
))
520 (list (nreverse evals
)
521 (nreverse (mapcar #'(lambda (x) (coerce x
'vector
))
522 (split-list evecs n
)))
523 (if (/= 0 ierr
) (- n ierr
))))))
526 ;;;; Spline Interpolation
529 (defun make-smoother-args (x y xvals
)
535 (unless (integerp xvals
)
536 (check-sequence xvals
)
538 (let* ((n (length x
))
539 (ns (if (integerp xvals
) xvals
(length xvals
)))
540 (result (list (make-list ns
) (make-list ns
))))
541 (if (and y
(/= n
(length y
))) (error "sequences not the same length"))
542 (list x y n
(if (integerp xvals
) 0 1) ns xvals result
)))
544 (defun get-smoother-result (args) (seventh args
))
546 (defmacro with-smoother-data
((x y xvals is-reg
) &rest body
)
553 (unless (integerp ,xvals
)
554 (check-sequence ,xvals
)
556 (let* ((supplied (not (integerp ,xvals
)))
558 (ns (if supplied
(length ,xvals
) ,xvals
))
559 (result (list (make-list ns
) (make-list ns
))))
560 (if (and ,is-reg
(/= n
(length ,y
)))
561 (error "sequences not the same length"))
562 (if (and (not supplied
) (< ns
2))
563 (error "too few points for interpolation"))
564 (let* ((px (la-data-to-vector ,x
+mode-re
+))
565 (py (if ,is-reg
(la-data-to-vector ,y
+mode-re
+)))
567 (la-data-to-vector ,xvals
+mode-re
+)
568 (la-vector ns
+mode-re
+)))
569 (pys (la-vector ns
+mode-re
+)))
570 (unless supplied
(la-range-to-rseq n px ns pxs
))
573 (la-vector-to-data pxs ns
+mode-re
+ (first result
))
574 (la-vector-to-data pys ns
+mode-re
+ (second result
)))
576 (if ,is-reg
(la-free-vector py
))
578 (la-free-vector pys
))
581 (defun spline (x y
&key
(xvals 30))
582 "Args: (x y &key xvals)
583 Returns list of x and y values of natural cubic spline interpolation of (X,Y).
584 X must be strictly increasing. XVALS can be an integer, the number of equally
585 spaced points to use in the range of X, or it can be a sequence of points at
586 which to interpolate."
587 (with-smoother-data (x y xvals t
)
588 (let ((work (la-vector (* 2 n
) +mode-re
+))
591 (setf error
(spline-front n px py ns pxs pys work
))
592 (la-free-vector work
))
593 (if (/= error
0) (error "bad data for splines")))))
596 ;;;; Kernel Density Estimators and Smoothers
599 (defun kernel-type-code (type)
600 (cond ((eq type
'u
) 0)
605 (defun kernel-dens (x &key
(type 'b
) (width -
1.0) (xvals 30))
606 "Args: (x &key xvals width type)
607 Returns list of x and y values of kernel density estimate of X. XVALS can be an
608 integer, the number of equally spaced points to use in the range of X, or it
609 can be a sequence of points at which to interpolate. WIDTH specifies the
610 window width. TYPE specifies the lernel and should be one of the symbols G, T,
611 U or B for gaussian, triangular, uniform or bisquare. The default is B."
612 (check-one-real width
)
613 (with-smoother-data (x nil xvals nil
) ;; warning about deleting unreachable code is TRUE -- 2nd arg=nil!
614 (let ((code (kernel-type-code type
))
616 (setf error
(kernel-dens-front px n width pxs pys ns code
))
617 (if (/= 0 error
) (error "bad kernel density data")))))
619 (defun kernel-smooth (x y
&key
(type 'b
) (width -
1.0) (xvals 30))
620 "Args: (x y &key xvals width type)
621 Returns list of x and y values of kernel smooth of (X,Y). XVALS can be an
622 integer, the number of equally spaced points to use in the range of X, or it
623 can be a sequence of points at which to interpolate. WIDTH specifies the
624 window width. TYPE specifies the lernel and should be one of the symbols G, T,
625 U or B for Gaussian, triangular, uniform or bisquare. The default is B."
626 (check-one-real width
)
627 (with-smoother-data (x y xvals t
)
628 (let ((code (kernel-type-code type
))
630 (kernel-smooth-front px py n width pxs pys ns code
)
631 ;; if we get the Lisp version ported from C, uncomment below and
632 ;; comment above. (thanks to Carlos Ungil for the initial CFFI
634 ;;(kernel-smooth-Cport px py n width pxs pys ns code)
635 (if (/= 0 error
) (error "bad kernel density data")))))
639 (defun kernel-smooth-Cport (px py n width
;;wts wds ;; see above for mismatch?
641 "Port of kernel_smooth (Lib/kernel.c) to Lisp.
642 FIXME:kernel-smooth-Cport : This is broken.
643 Until this is fixed, we are using Luke's C code and CFFI as glue."
645 ((and (< n
2) (<= width
0)) 1.0)
646 (t (let* ((xmin (min px
))
648 (width (/ (- xmax xmin
) (+ 1.0 (log n
)))))
649 (dotimes (i (- ns
1))
653 (dotimes (j (- n
1)) )
654 ;;;possible nasty errors...
657 ((lwidth (if wds
(* width
(aref wds j
)) width
))
658 (lwt (* (kernel-Cport (aref xs i
) (aref px j
) lwidth ktype
) ;; px?
659 (if wts
(aref wts j
) 1.0))))
660 (setf wsum
(+ wsum lwt
))
661 (setf ysum
(if py
(+ ysum
(* lwt
(aref py j
)))))) ;; py? y?
671 (defun kernel-Cport (x y w ktype
)
672 "Port of kernel() (Lib/kernel.c) to Lisp.
673 x,y,w are doubles, type is an integer"
677 (cond ((eq ktype
"B")
682 (/ (/ (* 15.0 (* (- 1.0 (* 4 z z
)) ;; k/w
683 (- 1.0 (* 4 z z
)))) ;; k/w
688 (let* ((w (* w
0.25))
690 (k (/ (exp (* -
0.5 z z
))
696 (k (if (< (abs z
) 0.5)
701 (cond ((and (> z -
1.0)
712 ;;;; Lowess Smoother Interface
715 (defun |base-lowess|
(s1 s2 f nsteps delta
)
721 (check-one-fixnum nsteps
)
722 (check-one-real delta
)
723 (let* ((n (length s1
))
724 (result (make-list n
)))
725 (if (/= n
(length s2
)) (error "sequences not the same length"))
726 (let ((x (la-data-to-vector s1
+mode-re
+))
727 (y (la-data-to-vector s2
+mode-re
+))
728 (ys (la-vector n
+mode-re
+))
729 (rw (la-vector n
+mode-re
+))
730 (res (la-vector n
+mode-re
+))
734 (setf error
(base-lowess-front x y n f nsteps delta ys rw res
))
735 (la-vector-to-data ys n
+mode-re
+ result
))
740 (la-free-vector res
))
741 (if (/= error
0) (error "bad data for lowess"))
745 static LVAL add_contour_point
(i, j
, k
, l
, x
, y
, z
, v
, result
)
755 if
((z[i][j] <= v && v < z[k][l]) || (z[k][l] <= v && v < z[i][j])) {
758 p = (v - z[i][j]) / (z[k][l] - z[i][j]);
760 rplaca(pt, cvflonum((FLOTYPE) (q * x[i] + p * x[k])));
761 rplaca
(cdr(pt), cvflonum
((FLOTYPE) (q * y
[j] + p * y[l])));
762 result = cons(pt, result);
768 LVAL xssurface_contour()
770 LVAL s1, s2, mat, result;
776 s1 = xsgetsequence();
777 s2 = xsgetsequence();
779 v = makedouble(xlgetarg());
782 n = seqlen(s1); m = seqlen(s2);
783 if (n != numrows(mat) || m != numcols(mat)) xlfail("dimensions do not match");
784 if (data_mode(s1) == CX || data_mode(s2) == CX || data_mode(mat) == CX)
785 xlfail("data must be real");
787 x = (RVector) data_to_vector(s1, RE);
788 y = (RVector) data_to_vector(s2, RE);
789 z = (RMatrix) data_to_matrix(mat, RE);
793 for (i = 0; i < n - 1; i++) {
794 for (j = 0; j < m - 1; j++) {
795 result = add_contour_point(i, j, i, j+1, x, y, z, v, result);
796 result = add_contour_point(i, j+1, i+1, j+1, x, y, z, v, result);
797 result = add_contour_point(i+1, j+1, i+1, j, x, y, z, v, result);
798 result = add_contour_point(i+1, j, i, j, x, y, z, v, result);
815 ;;; ??replace with matlisp:fft and matlisp:ifft (the latter for inverse mapping)
817 (defun fft (x &optional inverse)
818 "Args: (x &optional inverse)
819 Returns unnormalized Fourier transform of X, or inverse transform if INVERSE
822 (let* ((n (length x))
823 (mode (la-data-mode x))
824 (isign (if inverse -1 1))
825 (result (if (consp x) (make-list n) (make-array n))))
826 (let ((px (la-data-to-vector x +mode-cx+))
827 (work (la-vector (+ (* 4 n) 15) +mode-re+)))
830 (fft-front n px work isign)
831 (la-vector-to-data px n +mode-cx+ result))
833 (la-free-vector work))
837 ;;; SWEEP Operator: FIXME: use matlisp
840 (defun make-sweep-front (x y w n p mode has_w x_mean result)
841 (declare (fixnum n p mode has_w))
856 (has-w (if (/= 0 has_w) t nil))
858 (declare (long-float val dxi dyi dv dw sum_w dxik dxjk dyj
859 dx_meani dx_meanj dy_mean))
860 ;; (declare-double val dxi dyi dv dw sum_w dxik dxjk dyj
861 ;; dx_meani dx_meanj dy_mean)
863 (if (> mode RE) (error "not supported for complex data yet"))
865 (setf x_data (compound-data-seq x))
866 (setf result_data (compound-data-seq result))
868 ;; find the mean of y
873 (setf dyi (makedouble (aref y i)))
875 (setf dw (makedouble (aref w i)))
877 (setf dyi (* dyi dw)))
879 (if (not has-w) (setf sum_w (float n 0.0)))
880 (if (<= sum_w 0.0) (error "non positive sum of weights"))
881 (setf dy_mean (/ val sum_w))
883 ;; find the column means
889 (setf dxi (makedouble (aref x_data (+ (* p i) j))))
891 (setf dw (makedouble (aref w i)))
892 (setf dxi (* dxi dw)))
894 (setf (aref x_mean j) (/ val sum_w)))
896 ;; put 1/sum_w in topleft, means on left, minus means on top
897 (setf (aref result_data 0) (/ 1.0 sum_w))
900 (setf dxi (makedouble (aref x_mean i)))
901 (setf (aref result_data (+ i 1)) (- dxi))
902 (setf (aref result_data (* (+ i 1) (+ p 2))) dxi))
903 (setf (aref result_data (+ p 1)) (- dy_mean))
904 (setf (aref result_data (* (+ p 1) (+ p 2))) dy_mean)
906 ;; put sums of adjusted cross products in body
914 (setf dxik (makedouble (aref x_data (+ (* p k) i))))
915 (setf dxjk (makedouble (aref x_data (+ (* p k) j))))
916 (setf dx_meani (makedouble (aref x_mean i)))
917 (setf dx_meanj (makedouble (aref x_mean j)))
918 (setf dv (* (- dxik dx_meani) (- dxjk dx_meanj)))
920 (setf dw (makedouble (aref w k)))
923 (setf (aref result_data (+ (* (+ i 1) (+ p 2)) (+ j 1))) val)
924 (setf (aref result_data (+ (* (+ j 1) (+ p 2)) (+ i 1))) val))
928 (setf dxik (makedouble (aref x_data (+ (* p j) i))))
929 (setf dyj (makedouble (aref y j)))
930 (setf dx_meani (makedouble (aref x_mean i)))
931 (setf dv (* (- dxik dx_meani) (- dyj dy_mean)))
933 (setf dw (makedouble (aref w j)))
936 (setf (aref result_data (+ (* (+ i 1) (+ p 2)) (+ p 1))) val)
937 (setf (aref result_data (+ (* (+ p 1) (+ p 2)) (+ i 1))) val))
941 (setf dyj (makedouble (aref y j)))
942 (setf dv (* (- dyj dy_mean) (- dyj dy_mean)))
944 (setf dw (makedouble (aref w j)))
947 (setf (aref result_data (+ (* (+ p 1) (+ p 2)) (+ p 1))) val)))
949 ;;; FIXME: use matlisp
950 (defun sweep-in-place-front (a rows cols mode k tol)
951 "Sweep algorithm for linear regression."
952 (declare (long-float tol))
953 (declare (fixnum rows cols mode k))
961 (declare (long-float pivot aij aik akj akk))
963 (if (> mode RE) (error "not supported for complex data yet"))
964 (if (or (< k 0) (>= k rows) (>= k cols)) (error "index out of range"))
966 (setf tol (max tol machine-epsilon))
967 (setf data (compound-data-seq a))
969 (setf pivot (makedouble (aref data (+ (* cols k) k))))
972 ((or (> pivot tol) (< pivot (- tol)))
977 (when (and (/= i k) (/= j k))
978 (setf aij (makedouble (aref data (+ (* cols i) j))))
979 (setf aik (makedouble (aref data (+ (* cols i) k))))
980 (setf akj (makedouble (aref data (+ (* cols k) j))))
981 (setf aij (- aij (/ (* aik akj) pivot)))
982 (setf (aref data (+ (* cols i) j)) aij))))
986 (setf aik (makedouble (aref data (+ (* cols i) k))))
988 (setf aik (/ aik pivot))
989 (setf (aref data (+ (* cols i) k)) aik)))
993 (setf akj (makedouble (aref data (+ (* cols k) j))))
995 (setf akj (- (/ akj pivot)))
996 (setf (aref data (+ (* cols k) j)) akj)))
998 (setf akk (/ 1.0 pivot))
999 (setf (aref data (+ (* cols k) k)) akk)
1003 ;; FIXME: use matlisp
1004 (defun make-sweep-matrix (x y &optional w)
1005 "Args: (x y &optional weights)
1006 X is matrix, Y and WEIGHTS are sequences. Returns the sweep matrix of the
1007 (weighted) regression of Y on X"
1010 (if w (check-sequence w))
1011 (let ((n (num-rows x))
1013 (if (/= n (length y)) (error "dimensions do not match"))
1014 (if (and w (/= n (length w))) (error "dimensions do not match"))
1015 (let ((mode (max (la-data-mode x)
1017 (if w (la-data-mode w) 0)))
1018 (result (make-array (list (+ p 2) (+ p 2))))
1019 (x-mean (make-array p))
1020 (y (coerce y 'vector))
1021 (w (if w (coerce w 'vector)))
1023 (make-sweep-front x y w n p mode has-w x-mean result)
1026 (defun sweep-in-place (a k tol)
1028 (check-one-fixnum k)
1029 (check-one-real tol)
1030 (let ((rows (num-rows a))
1032 (mode (la-data-mode a)))
1033 (let ((swept (sweep-in-place-front a rows cols mode k tol)))
1034 (if (/= 0 swept) t nil))))
1036 (defun sweep-operator (a columns &optional tolerances)
1037 "Args: (a indices &optional tolerances)
1038 A is a matrix, INDICES a sequence of the column indices to be swept. Returns
1039 a list of the swept result and the list of the columns actually swept. (See
1040 MULTREG documentation.) If supplied, TOLERANCES should be a list of real
1041 numbers the same length as INDICES. An index will only be swept if its pivot
1042 element is larger than the corresponding element of TOLERANCES."
1044 (check-sequence columns)
1045 (if tolerances (check-sequence tolerances))
1047 (check-fixnum columns)
1048 (if tolerances (check-real tolerances))
1050 (result (copy-array a))
1052 (columns (coerce columns 'list) (cdr columns))
1053 (tolerances (if (consp tolerances) (coerce tolerances 'list))
1054 (if (consp tolerances) (cdr tolerances))))
1055 ((null columns) (list result swept-columns))
1056 (let ((col (first columns))
1057 (tol (if (consp tolerances) (first tolerances) tol)))
1058 (if (sweep-in-place result col tol)
1059 (setf swept-columns (cons col swept-columns))))))
1068 (defun ax+y (a x y &optional lower)
1069 "Args (a x y &optional lower)
1070 Returns (+ (matmult A X) Y). If LOWER is not nil, A is taken to be lower
1072 This could probably be made more efficient."
1073 (check-square-matrix a)
1079 (let* ((n (num-rows a))
1080 (result (make-list n))
1081 (a (compound-data-seq a)))
1082 (declare (fixnum n))
1083 (if (or (/= n (length x)) (/= n (length y)))
1084 (error "dimensions do not match"))
1085 (do* ((tx (make-next-element x) (make-next-element x))
1086 (ty (make-next-element y))
1087 (tr (make-next-element result))
1089 (start 0 (+ start n))
1090 (end (if lower (+ i 1) n) (if lower (+ i 1) n)))
1092 (declare (fixnum i start end))
1093 (let ((val (get-next-element ty i)))
1095 (declare (fixnum j))
1096 (setf val (+ val (* (get-next-element tx j)
1097 (aref a (+ start j))))))
1098 (set-next-element tr i val)))))