3 ;;; Time-stamp: <2009-03-21 09:32:59 tony>
4 ;;; Creation: <2008-09-08 08:06:30 tony>
6 ;;; Author: AJ Rossini <blindglobe@gmail.com>
7 ;;; Copyright: (c) 2007-2008, AJ Rossini <blindglobe@gmail.com>. BSD.
8 ;;; Purpose: Stuff that needs to be made working sits inside the progns...
10 ;;; What is this talk of 'release'? Klingons do not make software
11 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
12 ;;; designers and quality assurance people in its wake.
14 ;;; This file contains the current challenges to solve, including a
15 ;;; description of the setup and the work to solve....
20 ;;(asdf:oos 'asdf:compile-op 'lispstat)
21 ;;(asdf:oos 'asdf:load-op 'lispstat)
23 (in-package :lisp-stat-unittests
)
25 ;; tests = 89, failures = 7, errors = 37
27 (describe (run-tests :suite
'lisp-stat-ut
))
28 (run-tests :suite
'lisp-stat-ut
)
31 ;; FIXME: Example: currently not relevant, yet
34 :test-case
'lisp-stat-unittests
::create-proto
35 :suite
'lisp-stat-unittests
::lisp-stat-ut-proto
))
38 (describe 'lisp-stat-ut
)
43 (describe 'make-matrix
)
45 (defparameter *indep-vars-2-matrix
*
46 (make-matrix (length iron
) 2
48 (mapcar #'(lambda (x y
)
49 (list (coerce x
'double-float
)
50 (coerce y
'double-float
)))
54 (defparameter *dep-var
*
55 (make-vector (length absorbtion
)
59 (mapcar #'(lambda (x) (coerce x
'double-float
))
62 (defparameter *dep-var-int
*
63 (make-vector (length absorbtion
)
65 :element-type
'integer
66 :initial-contents
(list absorbtion
)))
72 :initial-contents
#2A
((1d0 1d0
)
86 :initial-contents
'((1d0)
96 (m= *xv
+1a
* *xv
+1b
*) ; => T
98 (princ "Data Set up"))
103 (defparameter *my-df-1
*
104 (make-instance 'dataframe-array
105 :storage
#2A
((1 2 3 4 5)
107 :doc
"This is an interesting dataframe-array"
108 :case-labels
(list "x" "y")
109 :var-labels
(list "a" "b" "c" "d" "e")))
112 (defparameter *my-df-2
*
113 (make-instance 'dataframe-array
115 (make-array-from-listoflists
116 (cybertiggyr-dsv::load-escaped
117 "/media/disk/Desktop/sandbox/CLS.git/Data/example-mixed.csv"))
118 :doc
"This is an interesting dataframe-array"))
119 #|
:case-labels
(list "x" "y")
120 :var-labels
(list "a" "b" "c" "d" "e")
127 ;; REVIEW: general Lisp use guidance
129 (fdefinition 'make-matrix
)
130 (documentation 'make-matrix
'function
)
132 #| Examples from CLHS
, a bit of guidance.
134 ;; This function assumes its callers have checked the types of the
135 ;; arguments, and authorizes the compiler to build in that assumption.
136 (defun discriminant (a b c
)
137 (declare (number a b c
))
138 "Compute the discriminant for a quadratic equation."
139 (- (* b b
) (* 4 a c
))) => DISCRIMINANT
140 (discriminant 1 2/3 -
2) => 76/9
142 ;; This function assumes its callers have not checked the types of the
143 ;; arguments, and performs explicit type checks before making any assumptions.
144 (defun careful-discriminant (a b c
)
145 "Compute the discriminant for a quadratic equation."
146 (check-type a number
)
147 (check-type b number
)
148 (check-type c number
)
149 (locally (declare (number a b c
))
150 (- (* b b
) (* 4 a c
)))) => CAREFUL-DISCRIMINANT
151 (careful-discriminant 1 2/3 -
2) => 76/9
157 (progn ;; FIXME: Regression modeling
159 ;; data setup in previous FIXME
160 (defparameter *m
* nil
162 ;; need to make vectors and matrices from the lists...
165 (def *m
* (regression-model (list->vector-like iron
)
166 (list->vector-like absorbtion
)))
168 (def m
(regression-model (list->vector-like iron
)
169 (list->vector-like absorbtion
) :print nil
))
173 (send m
:own-methods
)
174 ;; (lsos::ls-objects-methods m) ; bogus?
177 (def m
(regression-model (list->vector-like iron
)
178 (list->vector-like absorbtion
)))
180 (def m
(regression-model (listoflists->matrix-like
(list iron aluminum
))
181 (list->vector-like absorbtion
) :print nil
))
185 (send m
:sweep-matrix
)
186 (format t
"~%~A~%" (send m
:sweep-matrix
))
188 ;; need to get multiple-linear regression working (simple linear regr
189 ;; works)... to do this, we need to redo the whole numeric structure,
190 ;; I'm keeping these in as example of brokenness...
192 (send m
:basis
) ;; this should be positive?
193 (send m
:coef-estimates
) )
196 (progn ;; FIXME: Need to clean up data examples, licenses, attributions, etc.
197 ;; The following breaks because we should use a package to hold
198 ;; configuration details, and this would be the only package outside
199 ;; of packages.lisp, as it holds the overall defsystem structure.
200 (load-data "iris.lsp") ;; (the above partially fixed).
207 (progn ;; FIXME: read data from CSV file. To do.
210 ;; challenge is to ensure that we get mixed arrays when we want them,
211 ;; and single-type (simple) arrays in other cases.
214 (defparameter *csv-num
*
215 (cybertiggyr-dsv::load-escaped
216 #p
"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv"
220 (nth 0 (nth 0 *csv-num
*))
222 (defparameter *csv-num
*
223 (cybertiggyr-dsv::load-escaped
224 #p
"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric2.dsv"
225 :field-separator
#\
:))
227 (nth 0 (nth 0 *csv-num
*))
230 ;; The handling of these types should be compariable to what we do for
231 ;; matrices, but without the numerical processing. i.e. mref, bind2,
232 ;; make-dataframe, and the class structure should be similar.
234 ;; With numerical data, there should be a straightforward mapping from
235 ;; the data.frame to a matrix. With categorical data (including
236 ;; dense categories such as doc-strings, as well as sparse categories
237 ;; such as binary data), we need to include metadata about ordering,
238 ;; coding, and such. So the structures should probably consider
240 ;; Using the CSV file:
242 (defun parse-number (s)
243 (let* ((*read-eval
* nil
)
244 (n (read-from-string s
)))
250 (parse-number " 34 ")
252 (+ (parse-number "3.4") 3)
253 (parse-number "3.4 ")
254 (parse-number " 3.4")
255 (+ (parse-number " 3.4 ") 3)
259 ;; (coerce "2.3" 'number) => ERROR
260 ;; (coerce "2" 'float) => ERROR
262 (defparameter *csv-num
*
263 (cybertiggyr-dsv::load-escaped
264 #p
"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv"
266 :filter
#'parse-number
269 (nth 0 (nth 0 *csv-num
*))
271 (defparameter *csv-num
*
272 (cybertiggyr-dsv::load-escaped
273 #p
"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric2.dsv"
275 :filter
#'parse-number
))
277 (nth 0 (nth 0 *csv-num
*))
279 ;; now we've got the DSV code in the codebase, auto-loaded I hope:
280 cybertiggyr-dsv
:*field-separator
*
281 (defparameter *example-numeric.csv
*
282 (cybertiggyr-dsv:load-escaped
"Data/example-numeric.csv"
283 :field-separator
#\
,))
284 *example-numeric.csv
*
286 ;; the following fails because we've got a bit of string conversion
287 ;; to do. 2 thoughts: #1 modify dsv package, but mucking with
288 ;; encapsulation. #2 add a coercion tool (better, but potentially
290 #+nil
(coerce (nth 3 (nth 3 *example-numeric.csv
*)) 'double-float
)
292 ;; cases, simple to not so
293 (defparameter *test-string1
* "1.2")
294 (defparameter *test-string2
* " 1.2")
295 (defparameter *test-string3
* " 1.2 ")
300 (progn ;; experiments with GSL and the Lisp interface.
301 (asdf:oos
'asdf
:load-op
'gsll
)
302 (asdf:oos
'asdf
:load-op
'gsll-tests
)
304 ;; the following should be equivalent
305 (setf *t1
* (LIST 6.18d0
6.647777777777779d0
6.18d0
))
306 (setf *t2
* (MULTIPLE-VALUE-LIST
308 (gsll:make-marray
'DOUBLE-FLOAT
309 :INITIAL-CONTENTS
'(-3.21d0
1.0d0
12.8d0
)))
311 (gsll:MAKE-MARRAY
'DOUBLE-FLOAT
312 :INITIAL-CONTENTS
'(3.0d0
1.0d0
2.0d0
))))
313 (LET ((MEAN (gsll:MEAN VEC
)))
314 (LIST (gsll:ABSOLUTE-DEVIATION VEC
)
315 (gsll:WEIGHTED-ABSOLUTE-DEVIATION VEC WEIGHTS
)
316 (gsll:ABSOLUTE-DEVIATION VEC MEAN
))))))
319 ;; from (gsll:examples 'gsll::numerical-integration) ...
320 (gsll:integration-qng gsll
::one-sine
0.0d0 PI
)
322 (gsll:defun-single axpb
(x) (+ (* 2 x
) 3)) ;; a<-2, b<-3
323 (gsll:integration-qng axpb
1d0
2d0
)
327 (defun-single axpb2
(x) (+ (* a x
) b
)))
328 (gsll:integration-qng axpb2
1d0
2d0
)
331 ;; (gsll:integration-qng
334 ;; (defun-single axpb2 (x) (+ (* a x) b)))
337 ;; right, but weird expansion...
338 (gsll:integration-qng
341 (defun axpb2 (x) (+ (* a x
) b
))
342 (gsll:def-single-function axpb2
)
346 ;; Linear least squares
348 (gsll:gsl-lookup
"gsl_linalg_LU_decomp") ; => gsll:lu-decomposition
349 (gsll:gsl-lookup
"gsl_linalg_LU_solve") ; => gsll:lu-solve
355 (progn ;; philosophy time
357 (setf my-model
(model :name
"ex1"
358 :data-slots
(list w x y z
)
359 :param-slots
(list alpha beta gamma
)
360 :math-form
(regression-model :formula
'(= w
(+ (* beta x
)
364 :centrality
'median
; 'mean
371 (setf my-dataset
(statistical-table :table data-frame-contents
372 :metadata
(list (:case-names
(list ))
374 (:documentation
"string of doc"))))
376 (setf my-analysis
(analysis
379 :parameter-map
(pairing (model-param-slots my-model
)
380 (data-var-names my-dataset
))))
382 ;; ontological implications -- the analysis is an abstract class of
383 ;; data, model, and mapping between the model and data. The fit is
384 ;; the instantiation of such. This provides a statistical object
385 ;; computation theory which can be realized as "executable
386 ;; statistics" or "computable statistics".
387 (setf my-analysis
(analyze my-fit
388 :estimation-method
'linear-least-squares-regression
))
390 ;; one of the tricks here is that one needs to provide the structure
391 ;; from which to consider estimation, and more importantly, the
392 ;; validity of the estimation.
395 (setf linear-least-squares-regression
396 (estimation-method-definition
397 :variable-defintions
((list
398 ;; from MachLearn: supervised,
400 :data-response-vars list-drv
; nil if unsup
403 :data-predictor-vars list-dpv
404 ;; nil in this case. these
405 ;; describe "out-of-box" specs
406 :hyper-vars list-hv
))
407 :form
'(regression-additive-error
408 :central-form
(linear-form drv pv dpv
)
409 :error-form
'normal-error
)
410 :resulting-decision
'(point-estimation interval-estimation
)
411 :philosophy
'frequentist
412 :documentation
"use least squares to fit a linear regression
415 (defparameter *statistical-philosophies
*
416 '(frequentist bayesian fiducial decision-analysis
)
417 "can be combined to build decision-making approaches and
420 (defparameter *decisions
*
421 '(estimation selection testing
)
422 "possible results from a...")
423 ;; is this really true? One can embedded hypothesis testing within
424 ;; estimation, as the hypothesis estimated to select. And
425 ;; categorical/continuous rear their ugly heads, but not really in
428 (defparameter *ontology-of-decision-procedures
*
432 (list :maximum-likelihood
437 (list :maximum-likelihood
443 :bioequivalence-inversion
)
448 :partially-parametric
))
449 "start of ontology"))
460 :initial-contents
'((1d0 2d0
3d0
4d0
5d0
6d0
7d0
8d0
))))
466 :initial-contents
'((1d0 1d0
)
476 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
477 (defparameter *xtx-2
* (m* (transpose *xv
+1*) *xv
+1*))
478 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
482 (defparameter *xty-2
* (m* (transpose *xv
+1*) (transpose *y
*)))
483 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
487 (defparameter *rcond-2
* 0.000001)
488 (defparameter *betahat-2
* (gelsy *xtx-2
* *xty-2
* *rcond-2
*))
489 ;; *xtx-2* => "details of complete orthogonal factorization"
490 ;; according to man page:
491 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
492 ;; -119.33147112141039d0 -29.095426104883202d0
493 ;; 0.7873402682880205d0 -1.20672274167718d0>
495 ;; *xty-2* => output becomes solution:
496 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
497 ;; -0.16666666666668312d0
498 ;; 1.333333333333337d0>
500 *betahat-2
* ; which matches R, see below
502 (documentation 'gelsy
'function
)
505 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
506 ;; -0.16666666666668312 1.333333333333337>
509 ;; ## Test case in R:
510 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
511 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
513 ;; ## => Call: lm(formula = y ~ x)
515 ;; Coefficients: (Intercept) x
522 ;; lm(formula = y ~ x)
525 ;; Min 1Q Median 3Q Max
526 ;; -1.833e+00 -6.667e-01 -3.886e-16 6.667e-01 1.833e+00
529 ;; Estimate Std. Error t value Pr(>|t|)
530 ;; (Intercept) -0.1667 1.1587 -0.144 0.89034
531 ;; x 1.3333 0.3043 4.382 0.00466 **
533 ;; Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
535 ;; Residual standard error: 1.291 on 6 degrees of freedom
536 ;; Multiple R-squared: 0.7619, Adjusted R-squared: 0.7222
537 ;; F-statistic: 19.2 on 1 and 6 DF, p-value: 0.004659
541 ;; which suggests one might do (modulo ensuring correct
542 ;; orientations). When this is finalized, it should migrate to
547 (defparameter *n
* 20) ; # rows = # obsns
548 (defparameter *p
* 10) ; # cols = # vars
549 (defparameter *x-temp
* (rand *n
* *p
*))
550 (defparameter *b-temp
* (rand *p
* 1))
551 (defparameter *y-temp
* (m* *x-temp
* *b-temp
*))
553 (defparameter *rcond
* (* (coerce (expt 2 -
52) 'double-float
)
554 (max (nrows *x-temp
*) (ncols *y-temp
*))))
555 (defparameter *orig-x
* (copy *x-temp
*))
556 (defparameter *orig-b
* (copy *b-temp
*))
557 (defparameter *orig-y
* (copy *y-temp
*))
559 (defparameter *lm-result
* (lm *x-temp
* *y-temp
*))
560 (princ (first *lm-result
*))
561 (princ (second *lm-result
*))
562 (princ (third *lm-result
*))
563 (v= (third *lm-result
*)
564 (v- (first (first *lm-result
*))
565 (first (second *lm-result
*))))
570 ;; Some issues exist in the LAPACK vs. LINPACK variants, hence R
571 ;; uses LINPACK primarily, rather than LAPACK. See comments in R
572 ;; source for issues.
575 ;; Goal is to start from X, Y and then realize that if
576 ;; Y = X \beta, then, i.e. 8x1 = 8xp px1 + 8x1
577 ;; XtX \hat\beta = Xt Y
578 ;; so that we can solve the equation W \beta = Z where W and Z
579 ;; are known, to estimate \beta.
581 ;; the above is known to be numerically instable -- some processing
582 ;; of X is preferred and should be done prior. And most of the
583 ;; transformation-based work does precisely that.
585 ;; recall: Var[Y] = E[(Y - E[Y])(Y-E[Y])t]
586 ;; = E[Y Yt] - 2 \mu \mut + \mu \mut
587 ;; = E[Y Yt] - \mu \mut
589 ;; Var Y = E[Y^2] - \mu^2
592 ;; For initial estimates of covariance of \hat\beta:
594 ;; \hat\beta = (Xt X)^-1 Xt Y
595 ;; with E[ \hat\beta ]
596 ;; = E[ (Xt X)^-1 Xt Y ]
597 ;; = E[(Xt X)^-1 Xt (X\beta)]
600 ;; So Var[\hat\beta] = ...
602 ;; and this gives SE(\beta_i) = (* (sqrt (mref Var i i)) adjustment)
608 (let ((*default-implementation
* :foreign-array
))
614 (rcond (* (coerce (expt 2 -
52) 'double-float
)
615 (max (nrows a
) (ncols a
))))
619 (list x
(gelsy a b rcond
))
620 ;; no applicable conversion?
621 ;; (m- (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1))
622 ;; (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1)) )
623 (v- x
(first (gelsy a b rcond
))))))
626 (princ *temp-result
*)
629 (let ((*default-implementation
* :lisp-array
))
635 (rcond (* (coerce (expt 2 -
52) 'double-float
)
636 (max (nrows a
) (ncols a
))))
640 (list x
(gelsy a b rcond
))
641 (m- x
(first (gelsy a b rcond
)))
643 (princ *temp-result
*)
649 :type
:row
;; default, not usually needed!
650 :initial-contents
'((1d0 3d0
2d0
4d0
3d0
5d0
4d0
6d0
))))
656 :initial-contents
'((1d0 2d0
3d0
4d0
5d0
6d0
7d0
8d0
))))
658 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
659 (defparameter *xtx-1
* (m* *xv
* (transpose *xv
*)))
660 (defparameter *xty-1
* (m* *xv
* (transpose *y
*)))
661 (defparameter *rcond-in
* (* (coerce (expt 2 -
52) 'double-float
)
665 (defparameter *betahat
* (gelsy *xtx-1
* *xty-1
* *rcond-in
*))
667 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (1 x 1)
668 ;; 1.293103448275862>
671 ;; ## Test case in R:
672 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
673 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
677 ;; lm(formula = y ~ x - 1)
690 (asdf:oos
'asdf
:load-op
'cl-plplot
)