remove any last thoughts of dfref returning a non-scalar. We don't go there. Overen...
[CommonLispStat.git] / TODO.lisp
blob53a9d41942fe29b6260138a0a2541de6247fc13c
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2009-03-26 08:27:28 tony>
4 ;;; Creation: <2008-09-08 08:06:30 tony>
5 ;;; File: TODO.lisp
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....
17 ;;; SET UP
19 (in-package :cl-user)
20 ;;(asdf:oos 'asdf:compile-op 'lispstat)
21 ;;(asdf:oos 'asdf:load-op 'lispstat)
23 (in-package :lisp-stat-unittests)
25 ;; tests = 87, failures = 7, errors = 35
27 (describe (run-tests :suite 'lisp-stat-ut))
28 (run-tests :suite 'lisp-stat-ut)
31 ;; FIXME: Example: currently not relevant, yet
32 (describe
33 (lift::run-test
34 :test-case 'lisp-stat-unittests::create-proto
35 :suite 'lisp-stat-unittests::lisp-stat-ut-proto))
38 (describe 'lisp-stat-ut)
39 (in-package :ls-user)
42 (progn ;; dataframe
44 (describe (lift::run-tests :suite 'lisp-stat-ut-dataclos))
45 (lift::run-tests :suite 'lisp-stat-ut-dataclos)
47 (describe
48 (lift::run-test
49 :test-case 'lisp-stat-unittests::create-proto
50 :suite 'lisp-stat-unittests::lisp-stat-ut-proto))
52 (defparameter *my-df-1*
53 (make-instance 'dataframe-array
54 :storage #2A((1 2 3 4 5)
55 (10 20 30 40 50))
56 :doc "This is an interesting dataframe-array"
57 :case-labels (list "x" "y")
58 :var-labels (list "a" "b" "c" "d" "e")))
61 (make-dataframe #2A((1 2 3 4 5)
62 (10 20 30 40 50)))
64 (defparameter *my-df-1*
65 (make-dataframe #2A((1 2 3 4 5)
66 (10 20 30 40 50))
67 :caselabels (list "x" "y")
68 :varlabels (list "a" "b" "c" "d" "e")
69 :doc "This is an interesting dataframe-array")
72 (defparameter *my-df-2*
73 (make-instance 'dataframe-array
74 :storage
75 (make-array-from-listoflists
76 (cybertiggyr-dsv::load-escaped
77 "/media/disk/Desktop/sandbox/CLS.git/Data/example-mixed.csv"))
78 :doc "This is an interesting dataframe-array"))
79 #| :case-labels (list "x" "y")
80 :var-labels (list "a" "b" "c" "d" "e")
81 |#
86 (progn ;; Data setup
88 (describe 'make-matrix)
90 (defparameter *indep-vars-2-matrix*
91 (make-matrix (length iron) 2
92 :initial-contents
93 (mapcar #'(lambda (x y)
94 (list (coerce x 'double-float)
95 (coerce y 'double-float)))
96 iron aluminum)))
99 (defparameter *dep-var*
100 (make-vector (length absorbtion)
101 :type :row
102 :initial-contents
103 (list
104 (mapcar #'(lambda (x) (coerce x 'double-float))
105 absorbtion))))
107 (defparameter *dep-var-int*
108 (make-vector (length absorbtion)
109 :type :row
110 :element-type 'integer
111 :initial-contents (list absorbtion)))
114 (defparameter *xv+1a*
115 (make-matrix
117 :initial-contents #2A((1d0 1d0)
118 (1d0 3d0)
119 (1d0 2d0)
120 (1d0 4d0)
121 (1d0 3d0)
122 (1d0 5d0)
123 (1d0 4d0)
124 (1d0 6d0))))
126 (defparameter *xv+1b*
127 (bind2
128 (ones 8 1)
129 (make-matrix
131 :initial-contents '((1d0)
132 (3d0)
133 (2d0)
134 (4d0)
135 (3d0)
136 (5d0)
137 (4d0)
138 (6d0)))
139 :by :column))
141 (m= *xv+1a* *xv+1b*) ; => T
143 (princ "Data Set up"))
148 (progn
149 ;; REVIEW: general Lisp use guidance
151 (fdefinition 'make-matrix)
152 (documentation 'make-matrix 'function)
154 #| Examples from CLHS, a bit of guidance.
156 ;; This function assumes its callers have checked the types of the
157 ;; arguments, and authorizes the compiler to build in that assumption.
158 (defun discriminant (a b c)
159 (declare (number a b c))
160 "Compute the discriminant for a quadratic equation."
161 (- (* b b) (* 4 a c))) => DISCRIMINANT
162 (discriminant 1 2/3 -2) => 76/9
164 ;; This function assumes its callers have not checked the types of the
165 ;; arguments, and performs explicit type checks before making any assumptions.
166 (defun careful-discriminant (a b c)
167 "Compute the discriminant for a quadratic equation."
168 (check-type a number)
169 (check-type b number)
170 (check-type c number)
171 (locally (declare (number a b c))
172 (- (* b b) (* 4 a c)))) => CAREFUL-DISCRIMINANT
173 (careful-discriminant 1 2/3 -2) => 76/9
178 #+nil
179 (progn ;; FIXME: Regression modeling
181 ;; data setup in previous FIXME
182 (defparameter *m* nil
183 "holding variable.")
184 ;; need to make vectors and matrices from the lists...
186 ;; BROKEN
187 (def *m* (regression-model (list->vector-like iron)
188 (list->vector-like absorbtion)))
190 (def m (regression-model (list->vector-like iron)
191 (list->vector-like absorbtion) :print nil))
192 ;;Good
193 (send m :print)
194 (send m :own-slots)
195 (send m :own-methods)
196 ;; (lsos::ls-objects-methods m) ; bogus?
197 (send m :show)
199 (def m (regression-model (list->vector-like iron)
200 (list->vector-like absorbtion)))
202 (def m (regression-model (listoflists->matrix-like (list iron aluminum))
203 (list->vector-like absorbtion) :print nil))
206 (send m :compute)
207 (send m :sweep-matrix)
208 (format t "~%~A~%" (send m :sweep-matrix))
210 ;; need to get multiple-linear regression working (simple linear regr
211 ;; works)... to do this, we need to redo the whole numeric structure,
212 ;; I'm keeping these in as example of brokenness...
214 (send m :basis) ;; this should be positive?
215 (send m :coef-estimates) )
217 #+nil
218 (progn ;; FIXME: Need to clean up data examples, licenses, attributions, etc.
219 ;; The following breaks because we should use a package to hold
220 ;; configuration details, and this would be the only package outside
221 ;; of packages.lisp, as it holds the overall defsystem structure.
222 (load-data "iris.lsp") ;; (the above partially fixed).
223 (variables)
224 diabetes )
229 (progn ;; FIXME: read data from CSV file. To do.
232 ;; challenge is to ensure that we get mixed arrays when we want them,
233 ;; and single-type (simple) arrays in other cases.
236 (defparameter *csv-num*
237 (cybertiggyr-dsv::load-escaped
238 #p"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv"
239 :field-separator #\,
240 :trace T))
242 (nth 0 (nth 0 *csv-num*))
244 (defparameter *csv-num*
245 (cybertiggyr-dsv::load-escaped
246 #p"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric2.dsv"
247 :field-separator #\:))
249 (nth 0 (nth 0 *csv-num*))
252 ;; The handling of these types should be compariable to what we do for
253 ;; matrices, but without the numerical processing. i.e. mref, bind2,
254 ;; make-dataframe, and the class structure should be similar.
256 ;; With numerical data, there should be a straightforward mapping from
257 ;; the data.frame to a matrix. With categorical data (including
258 ;; dense categories such as doc-strings, as well as sparse categories
259 ;; such as binary data), we need to include metadata about ordering,
260 ;; coding, and such. So the structures should probably consider
262 ;; Using the CSV file:
264 (defun parse-number (s)
265 (let* ((*read-eval* nil)
266 (n (read-from-string s)))
267 (if (numberp n) n)))
269 (parse-number "34")
270 (parse-number "34 ")
271 (parse-number " 34")
272 (parse-number " 34 ")
274 (+ (parse-number "3.4") 3)
275 (parse-number "3.4 ")
276 (parse-number " 3.4")
277 (+ (parse-number " 3.4 ") 3)
279 (parse-number "a")
281 ;; (coerce "2.3" 'number) => ERROR
282 ;; (coerce "2" 'float) => ERROR
284 (defparameter *csv-num*
285 (cybertiggyr-dsv::load-escaped
286 #p"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv"
287 :field-separator #\,
288 :filter #'parse-number
289 :trace T))
291 (nth 0 (nth 0 *csv-num*))
293 (defparameter *csv-num*
294 (cybertiggyr-dsv::load-escaped
295 #p"/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric2.dsv"
296 :field-separator #\:
297 :filter #'parse-number))
299 (nth 0 (nth 0 *csv-num*))
301 ;; now we've got the DSV code in the codebase, auto-loaded I hope:
302 cybertiggyr-dsv:*field-separator*
303 (defparameter *example-numeric.csv*
304 (cybertiggyr-dsv:load-escaped "Data/example-numeric.csv"
305 :field-separator #\,))
306 *example-numeric.csv*
308 ;; the following fails because we've got a bit of string conversion
309 ;; to do. 2 thoughts: #1 modify dsv package, but mucking with
310 ;; encapsulation. #2 add a coercion tool (better, but potentially
311 ;; inefficient).
312 #+nil(coerce (nth 3 (nth 3 *example-numeric.csv*)) 'double-float)
314 ;; cases, simple to not so
315 (defparameter *test-string1* "1.2")
316 (defparameter *test-string2* " 1.2")
317 (defparameter *test-string3* " 1.2 ")
321 #+nil
322 (progn ;; experiments with GSL and the Lisp interface.
323 (asdf:oos 'asdf:load-op 'gsll)
324 (asdf:oos 'asdf:load-op 'gsll-tests)
326 ;; the following should be equivalent
327 (setf *t1* (LIST 6.18d0 6.647777777777779d0 6.18d0))
328 (setf *t2* (MULTIPLE-VALUE-LIST
329 (LET ((VEC
330 (gsll:make-marray 'DOUBLE-FLOAT
331 :INITIAL-CONTENTS '(-3.21d0 1.0d0 12.8d0)))
332 (WEIGHTS
333 (gsll:MAKE-MARRAY 'DOUBLE-FLOAT
334 :INITIAL-CONTENTS '(3.0d0 1.0d0 2.0d0))))
335 (LET ((MEAN (gsll:MEAN VEC)))
336 (LIST (gsll:ABSOLUTE-DEVIATION VEC)
337 (gsll:WEIGHTED-ABSOLUTE-DEVIATION VEC WEIGHTS)
338 (gsll:ABSOLUTE-DEVIATION VEC MEAN))))))
339 (eql *t1* *t2*)
341 ;; from (gsll:examples 'gsll::numerical-integration) ...
342 (gsll:integration-qng gsll::one-sine 0.0d0 PI)
344 (gsll:defun-single axpb (x) (+ (* 2 x) 3)) ;; a<-2, b<-3
345 (gsll:integration-qng axpb 1d0 2d0)
347 (let ((a 2)
348 (b 3))
349 (defun-single axpb2 (x) (+ (* a x) b)))
350 (gsll:integration-qng axpb2 1d0 2d0)
352 ;; BAD
353 ;; (gsll:integration-qng
354 ;; (let ((a 2)
355 ;; (b 3))
356 ;; (defun-single axpb2 (x) (+ (* a x) b)))
357 ;; 1d0 2d0)
359 ;; right, but weird expansion...
360 (gsll:integration-qng
361 (let ((a 2)
362 (b 3))
363 (defun axpb2 (x) (+ (* a x) b))
364 (gsll:def-single-function axpb2)
365 axpb2)
366 1d0 2d0)
368 ;; Linear least squares
370 (gsll:gsl-lookup "gsl_linalg_LU_decomp") ; => gsll:lu-decomposition
371 (gsll:gsl-lookup "gsl_linalg_LU_solve") ; => gsll:lu-solve
376 #+nil
377 (progn ;; philosophy time
379 (setf my-model (model :name "ex1"
380 :data-slots (list w x y z)
381 :param-slots (list alpha beta gamma)
382 :math-form (regression-model :formula '(= w (+ (* beta x)
383 (* alpha y)
384 (* gamma z)
385 normal-error))
386 :centrality 'median ; 'mean
389 #| or:
390 #R"W ~ x+ y + z "
393 (setf my-dataset (statistical-table :table data-frame-contents
394 :metadata (list (:case-names (list ))
395 (:var-names (list ))
396 (:documentation "string of doc"))))
398 (setf my-analysis (analysis
399 :model my-model
400 :data my-dataset
401 :parameter-map (pairing (model-param-slots my-model)
402 (data-var-names my-dataset))))
404 ;; ontological implications -- the analysis is an abstract class of
405 ;; data, model, and mapping between the model and data. The fit is
406 ;; the instantiation of such. This provides a statistical object
407 ;; computation theory which can be realized as "executable
408 ;; statistics" or "computable statistics".
409 (setf my-analysis (analyze my-fit
410 :estimation-method 'linear-least-squares-regression))
412 ;; one of the tricks here is that one needs to provide the structure
413 ;; from which to consider estimation, and more importantly, the
414 ;; validity of the estimation.
417 (setf linear-least-squares-regression
418 (estimation-method-definition
419 :variable-defintions ((list
420 ;; from MachLearn: supervised,
421 ;; unsupervised
422 :data-response-vars list-drv ; nil if unsup
424 :param-vars list-pv
425 :data-predictor-vars list-dpv
426 ;; nil in this case. these
427 ;; describe "out-of-box" specs
428 :hyper-vars list-hv))
429 :form '(regression-additive-error
430 :central-form (linear-form drv pv dpv)
431 :error-form 'normal-error)
432 :resulting-decision '(point-estimation interval-estimation)
433 :philosophy 'frequentist
434 :documentation "use least squares to fit a linear regression
435 model to data."))
437 (defparameter *statistical-philosophies*
438 '(frequentist bayesian fiducial decision-analysis)
439 "can be combined to build decision-making approaches and
440 characterizations")
442 (defparameter *decisions*
443 '(estimation selection testing)
444 "possible results from a...")
445 ;; is this really true? One can embedded hypothesis testing within
446 ;; estimation, as the hypothesis estimated to select. And
447 ;; categorical/continuous rear their ugly heads, but not really in
448 ;; an essential way.
450 (defparameter *ontology-of-decision-procedures*
451 (list :decisions
452 (list :estimation
453 (list :point
454 (list :maximum-likelihood
455 :minimum-entropy
456 :least-squares
457 :method-of-moments)
458 :interval
459 (list :maximum-likelihood
461 :testing
462 (list :fisherian
463 :neyman-pearson
464 (list :traditional
465 :bioequivalence-inversion)
466 :selection
467 (list :ranking
468 :top-k-of-n-select))
469 :parametric
470 :partially-parametric))
471 "start of ontology"))
474 ;;;; LM
476 (progn
478 (defparameter *y*
479 (make-vector
481 :type :row
482 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
485 (defparameter *xv+1*
486 (make-matrix
488 :initial-contents '((1d0 1d0)
489 (1d0 3d0)
490 (1d0 2d0)
491 (1d0 4d0)
492 (1d0 3d0)
493 (1d0 5d0)
494 (1d0 4d0)
495 (1d0 6d0))))
498 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
499 (defparameter *xtx-2* (m* (transpose *xv+1*) *xv+1*))
500 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
501 ;; 8.0d0 28.0d0
502 ;; 28.0d0 116.0d0>
504 (defparameter *xty-2* (m* (transpose *xv+1*) (transpose *y*)))
505 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
506 ;; 36.0d0
507 ;; 150.0d0>
509 (defparameter *rcond-2* 0.000001)
510 (defparameter *betahat-2* (gelsy *xtx-2* *xty-2* *rcond-2*))
511 ;; *xtx-2* => "details of complete orthogonal factorization"
512 ;; according to man page:
513 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
514 ;; -119.33147112141039d0 -29.095426104883202d0
515 ;; 0.7873402682880205d0 -1.20672274167718d0>
517 ;; *xty-2* => output becomes solution:
518 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
519 ;; -0.16666666666668312d0
520 ;; 1.333333333333337d0>
522 *betahat-2* ; which matches R, see below
524 (documentation 'gelsy 'function)
527 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
528 ;; -0.16666666666668312 1.333333333333337>
529 ;; 2)
531 ;; ## Test case in R:
532 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
533 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
534 ;; lm(y~x)
535 ;; ## => Call: lm(formula = y ~ x)
537 ;; Coefficients: (Intercept) x
538 ;; -0.1667 1.3333
540 ;; summary(lm(y~x))
541 ;; ## =>
543 ;; Call:
544 ;; lm(formula = y ~ x)
546 ;; Residuals:
547 ;; Min 1Q Median 3Q Max
548 ;; -1.833e+00 -6.667e-01 -3.886e-16 6.667e-01 1.833e+00
550 ;; Coefficients:
551 ;; Estimate Std. Error t value Pr(>|t|)
552 ;; (Intercept) -0.1667 1.1587 -0.144 0.89034
553 ;; x 1.3333 0.3043 4.382 0.00466 **
554 ;; ---
555 ;; Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
557 ;; Residual standard error: 1.291 on 6 degrees of freedom
558 ;; Multiple R-squared: 0.7619, Adjusted R-squared: 0.7222
559 ;; F-statistic: 19.2 on 1 and 6 DF, p-value: 0.004659
563 ;; which suggests one might do (modulo ensuring correct
564 ;; orientations). When this is finalized, it should migrate to
565 ;; CLS.
569 (defparameter *n* 20) ; # rows = # obsns
570 (defparameter *p* 10) ; # cols = # vars
571 (defparameter *x-temp* (rand *n* *p*))
572 (defparameter *b-temp* (rand *p* 1))
573 (defparameter *y-temp* (m* *x-temp* *b-temp*))
574 ;; so Y=Xb + \eps
575 (defparameter *rcond* (* (coerce (expt 2 -52) 'double-float)
576 (max (nrows *x-temp*) (ncols *y-temp*))))
577 (defparameter *orig-x* (copy *x-temp*))
578 (defparameter *orig-b* (copy *b-temp*))
579 (defparameter *orig-y* (copy *y-temp*))
581 (defparameter *lm-result* (lm *x-temp* *y-temp*))
582 (princ (first *lm-result*))
583 (princ (second *lm-result*))
584 (princ (third *lm-result*))
585 (v= (third *lm-result*)
586 (v- (first (first *lm-result*))
587 (first (second *lm-result*))))
592 ;; Some issues exist in the LAPACK vs. LINPACK variants, hence R
593 ;; uses LINPACK primarily, rather than LAPACK. See comments in R
594 ;; source for issues.
597 ;; Goal is to start from X, Y and then realize that if
598 ;; Y = X \beta, then, i.e. 8x1 = 8xp px1 + 8x1
599 ;; XtX \hat\beta = Xt Y
600 ;; so that we can solve the equation W \beta = Z where W and Z
601 ;; are known, to estimate \beta.
603 ;; the above is known to be numerically instable -- some processing
604 ;; of X is preferred and should be done prior. And most of the
605 ;; transformation-based work does precisely that.
607 ;; recall: Var[Y] = E[(Y - E[Y])(Y-E[Y])t]
608 ;; = E[Y Yt] - 2 \mu \mut + \mu \mut
609 ;; = E[Y Yt] - \mu \mut
611 ;; Var Y = E[Y^2] - \mu^2
614 ;; For initial estimates of covariance of \hat\beta:
616 ;; \hat\beta = (Xt X)^-1 Xt Y
617 ;; with E[ \hat\beta ]
618 ;; = E[ (Xt X)^-1 Xt Y ]
619 ;; = E[(Xt X)^-1 Xt (X\beta)]
620 ;; = \beta
622 ;; So Var[\hat\beta] = ...
623 ;; (Xt X)
624 ;; and this gives SE(\beta_i) = (* (sqrt (mref Var i i)) adjustment)
627 ;; from docs:
629 (setf *temp-result*
630 (let ((*default-implementation* :foreign-array))
631 (let* ((m 10)
632 (n 10)
633 (a (rand m n))
634 (x (rand n 1))
635 (b (m* a x))
636 (rcond (* (coerce (expt 2 -52) 'double-float)
637 (max (nrows a) (ncols a))))
638 (orig-a (copy a))
639 (orig-b (copy b))
640 (orig-x (copy x)))
641 (list x (gelsy a b rcond))
642 ;; no applicable conversion?
643 ;; (m- (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1))
644 ;; (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1)) )
645 (v- x (first (gelsy a b rcond))))))
648 (princ *temp-result*)
650 (setf *temp-result*
651 (let ((*default-implementation* :lisp-array))
652 (let* ((m 10)
653 (n 10)
654 (a (rand m n))
655 (x (rand n 1))
656 (b (m* a x))
657 (rcond (* (coerce (expt 2 -52) 'double-float)
658 (max (nrows a) (ncols a))))
659 (orig-a (copy a))
660 (orig-b (copy b))
661 (orig-x (copy x)))
662 (list x (gelsy a b rcond))
663 (m- x (first (gelsy a b rcond)))
665 (princ *temp-result*)
668 (defparameter *xv*
669 (make-vector
671 :type :row ;; default, not usually needed!
672 :initial-contents '((1d0 3d0 2d0 4d0 3d0 5d0 4d0 6d0))))
674 (defparameter *y*
675 (make-vector
677 :type :row
678 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
680 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
681 (defparameter *xtx-1* (m* *xv* (transpose *xv*)))
682 (defparameter *xty-1* (m* *xv* (transpose *y*)))
683 (defparameter *rcond-in* (* (coerce (expt 2 -52) 'double-float)
684 (max (nrows *xtx-1*)
685 (ncols *xty-1*))))
687 (defparameter *betahat* (gelsy *xtx-1* *xty-1* *rcond-in*))
689 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (1 x 1)
690 ;; 1.293103448275862>
691 ;; 1)
693 ;; ## Test case in R:
694 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
695 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
696 ;; lm(y~x-1)
697 ;; ## =>
698 ;; Call:
699 ;; lm(formula = y ~ x - 1)
701 ;; Coefficients:
702 ;; x
703 ;; 1.293
705 (first *betahat*))
709 #+nil
710 (progn
712 (asdf:oos 'asdf:load-op 'cl-plplot)
714 (plot-ex))