cleanup of dataframe code. Still lots more work to go.
[CommonLispStat.git] / TODO.lisp
blob5777c547e75d86d8c0e8a262428646c40c8b2a61
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2009-03-21 09:32:59 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 = 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
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)
41 (progn ;; Data setup
43 (describe 'make-matrix)
45 (defparameter *indep-vars-2-matrix*
46 (make-matrix (length iron) 2
47 :initial-contents
48 (mapcar #'(lambda (x y)
49 (list (coerce x 'double-float)
50 (coerce y 'double-float)))
51 iron aluminum)))
54 (defparameter *dep-var*
55 (make-vector (length absorbtion)
56 :type :row
57 :initial-contents
58 (list
59 (mapcar #'(lambda (x) (coerce x 'double-float))
60 absorbtion))))
62 (defparameter *dep-var-int*
63 (make-vector (length absorbtion)
64 :type :row
65 :element-type 'integer
66 :initial-contents (list absorbtion)))
69 (defparameter *xv+1a*
70 (make-matrix
71 8 2
72 :initial-contents #2A((1d0 1d0)
73 (1d0 3d0)
74 (1d0 2d0)
75 (1d0 4d0)
76 (1d0 3d0)
77 (1d0 5d0)
78 (1d0 4d0)
79 (1d0 6d0))))
81 (defparameter *xv+1b*
82 (bind2
83 (ones 8 1)
84 (make-matrix
85 8 1
86 :initial-contents '((1d0)
87 (3d0)
88 (2d0)
89 (4d0)
90 (3d0)
91 (5d0)
92 (4d0)
93 (6d0)))
94 :by :column))
96 (m= *xv+1a* *xv+1b*) ; => T
98 (princ "Data Set up"))
101 (progn ;; dataframe
103 (defparameter *my-df-1*
104 (make-instance 'dataframe-array
105 :storage #2A((1 2 3 4 5)
106 (10 20 30 40 50))
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
114 :storage
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")
126 (progn
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
156 #+nil
157 (progn ;; FIXME: Regression modeling
159 ;; data setup in previous FIXME
160 (defparameter *m* nil
161 "holding variable.")
162 ;; need to make vectors and matrices from the lists...
164 ;; BROKEN
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))
170 ;;Good
171 (send m :print)
172 (send m :own-slots)
173 (send m :own-methods)
174 ;; (lsos::ls-objects-methods m) ; bogus?
175 (send m :show)
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))
184 (send m :compute)
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) )
195 #+nil
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).
201 (variables)
202 diabetes )
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"
217 :field-separator #\,
218 :trace T))
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)))
245 (if (numberp n) n)))
247 (parse-number "34")
248 (parse-number "34 ")
249 (parse-number " 34")
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)
257 (parse-number "a")
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"
265 :field-separator #\,
266 :filter #'parse-number
267 :trace T))
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"
274 :field-separator #\:
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
289 ;; inefficient).
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 ")
299 #+nil
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
307 (LET ((VEC
308 (gsll:make-marray 'DOUBLE-FLOAT
309 :INITIAL-CONTENTS '(-3.21d0 1.0d0 12.8d0)))
310 (WEIGHTS
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))))))
317 (eql *t1* *t2*)
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)
325 (let ((a 2)
326 (b 3))
327 (defun-single axpb2 (x) (+ (* a x) b)))
328 (gsll:integration-qng axpb2 1d0 2d0)
330 ;; BAD
331 ;; (gsll:integration-qng
332 ;; (let ((a 2)
333 ;; (b 3))
334 ;; (defun-single axpb2 (x) (+ (* a x) b)))
335 ;; 1d0 2d0)
337 ;; right, but weird expansion...
338 (gsll:integration-qng
339 (let ((a 2)
340 (b 3))
341 (defun axpb2 (x) (+ (* a x) b))
342 (gsll:def-single-function axpb2)
343 axpb2)
344 1d0 2d0)
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
354 #+nil
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)
361 (* alpha y)
362 (* gamma z)
363 normal-error))
364 :centrality 'median ; 'mean
367 #| or:
368 #R"W ~ x+ y + z "
371 (setf my-dataset (statistical-table :table data-frame-contents
372 :metadata (list (:case-names (list ))
373 (:var-names (list ))
374 (:documentation "string of doc"))))
376 (setf my-analysis (analysis
377 :model my-model
378 :data my-dataset
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,
399 ;; unsupervised
400 :data-response-vars list-drv ; nil if unsup
402 :param-vars list-pv
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
413 model to data."))
415 (defparameter *statistical-philosophies*
416 '(frequentist bayesian fiducial decision-analysis)
417 "can be combined to build decision-making approaches and
418 characterizations")
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
426 ;; an essential way.
428 (defparameter *ontology-of-decision-procedures*
429 (list :decisions
430 (list :estimation
431 (list :point
432 (list :maximum-likelihood
433 :minimum-entropy
434 :least-squares
435 :method-of-moments)
436 :interval
437 (list :maximum-likelihood
439 :testing
440 (list :fisherian
441 :neyman-pearson
442 (list :traditional
443 :bioequivalence-inversion)
444 :selection
445 (list :ranking
446 :top-k-of-n-select))
447 :parametric
448 :partially-parametric))
449 "start of ontology"))
452 ;;;; LM
454 (progn
456 (defparameter *y*
457 (make-vector
459 :type :row
460 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
463 (defparameter *xv+1*
464 (make-matrix
466 :initial-contents '((1d0 1d0)
467 (1d0 3d0)
468 (1d0 2d0)
469 (1d0 4d0)
470 (1d0 3d0)
471 (1d0 5d0)
472 (1d0 4d0)
473 (1d0 6d0))))
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
479 ;; 8.0d0 28.0d0
480 ;; 28.0d0 116.0d0>
482 (defparameter *xty-2* (m* (transpose *xv+1*) (transpose *y*)))
483 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
484 ;; 36.0d0
485 ;; 150.0d0>
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>
507 ;; 2)
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)
512 ;; lm(y~x)
513 ;; ## => Call: lm(formula = y ~ x)
515 ;; Coefficients: (Intercept) x
516 ;; -0.1667 1.3333
518 ;; summary(lm(y~x))
519 ;; ## =>
521 ;; Call:
522 ;; lm(formula = y ~ x)
524 ;; Residuals:
525 ;; Min 1Q Median 3Q Max
526 ;; -1.833e+00 -6.667e-01 -3.886e-16 6.667e-01 1.833e+00
528 ;; Coefficients:
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 **
532 ;; ---
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
543 ;; CLS.
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*))
552 ;; so Y=Xb + \eps
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)]
598 ;; = \beta
600 ;; So Var[\hat\beta] = ...
601 ;; (Xt X)
602 ;; and this gives SE(\beta_i) = (* (sqrt (mref Var i i)) adjustment)
605 ;; from docs:
607 (setf *temp-result*
608 (let ((*default-implementation* :foreign-array))
609 (let* ((m 10)
610 (n 10)
611 (a (rand m n))
612 (x (rand n 1))
613 (b (m* a x))
614 (rcond (* (coerce (expt 2 -52) 'double-float)
615 (max (nrows a) (ncols a))))
616 (orig-a (copy a))
617 (orig-b (copy b))
618 (orig-x (copy x)))
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*)
628 (setf *temp-result*
629 (let ((*default-implementation* :lisp-array))
630 (let* ((m 10)
631 (n 10)
632 (a (rand m n))
633 (x (rand n 1))
634 (b (m* a x))
635 (rcond (* (coerce (expt 2 -52) 'double-float)
636 (max (nrows a) (ncols a))))
637 (orig-a (copy a))
638 (orig-b (copy b))
639 (orig-x (copy x)))
640 (list x (gelsy a b rcond))
641 (m- x (first (gelsy a b rcond)))
643 (princ *temp-result*)
646 (defparameter *xv*
647 (make-vector
649 :type :row ;; default, not usually needed!
650 :initial-contents '((1d0 3d0 2d0 4d0 3d0 5d0 4d0 6d0))))
652 (defparameter *y*
653 (make-vector
655 :type :row
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)
662 (max (nrows *xtx-1*)
663 (ncols *xty-1*))))
665 (defparameter *betahat* (gelsy *xtx-1* *xty-1* *rcond-in*))
667 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (1 x 1)
668 ;; 1.293103448275862>
669 ;; 1)
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)
674 ;; lm(y~x-1)
675 ;; ## =>
676 ;; Call:
677 ;; lm(formula = y ~ x - 1)
679 ;; Coefficients:
680 ;; x
681 ;; 1.293
683 (first *betahat*))
687 #+nil
688 (progn
690 (asdf:oos 'asdf:load-op 'cl-plplot)
692 (plot-ex))