adding in the reading of CSV files, start of numerical computation.
[CommonLispStat.git] / ls-demo.lisp
blob17bcfbef71f40cb212025eb784295f62fff27ce5
1 ;;; -*- mode: lisp -*-
2 ;;; Copyright (c) 2006-2008, 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 ;;; Time-stamp: <2009-05-26 20:56:17 tony>
7 ;;; Creation: sometime in 2006...
8 ;;; File: ls-demo.lisp
9 ;;; Author: AJ Rossini <blindglobe@gmail.com>
10 ;;; Copyright: (c) 2007, AJ Rossini. BSD.
11 ;;; Purpose: demonstrations of how one might use CLSv2.
13 ;;; What is this talk of 'release'? Klingons do not make software
14 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
15 ;;; designers and quality assurance people in its wake.
17 (in-package :cl-user)
19 ;; (asdf:oos 'asdf:compile-op 'lispstat :force t)
20 (asdf:oos 'asdf:load-op 'lispstat)
22 (in-package :ls-user)
25 ;;; == READ DATA
27 (defparameter *my-df-1*
28 (make-instance 'dataframe-array
29 :storage #2A((1 2 3 4 5)
30 (10 20 30 40 50))
31 :doc "This is an un-interesting dataframe-array"
32 :case-labels (list "x" "y")
33 :var-labels (list "a" "b" "c" "d" "e")))
35 (setf (dfref *my-df-1* 0 0) -1d0)
36 ;; *my-df-1*
39 (make-dataframe #2A((1 2 3 4 5)
40 (10 20 30 40 50)))
42 (make-dataframe (rand 4 3))
47 (defparameter *my-df-2*
48 (make-dataframe #2A((1 2 3 4 5)
49 (10 20 30 40 50))
50 :caselabels (list "x" "y")
51 :varlabels (list "a" "b" "c" "d" "e")
52 :doc "This is another boring dataframe-array"))
54 (caselabels *my-df-1*)
55 (varlabels *my-df-1*)
59 (defparameter *my-df-2*
60 (make-dataframe #2A((a 2 T 4 5)
61 (b 20 nil 40 50))
62 :caselabels (list "x" "y")
63 :varlabels (list "a" "b" "c" "d" "e")
64 :doc "This is another boring dataframe-array"))
66 ;; *my-df-2*
69 ;;; HERE
71 ;;; read in a CSV dataframe...
74 ;; a better approach is:
75 (asdf:oos 'asdf:load-op 'rsm-string)
76 (rsm.string:file->string-table
77 "/media/disk/Desktop/sandbox/CLS.git/Data/example-mixed.csv")
79 (rsm.string:file->number-table
80 "/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv")
82 (defparameter *my-df-2*
83 (make-instance 'dataframe-array
84 :storage
85 (listoflist->array
86 (transpose-listoflist
87 (rsm.string:file->string-table
88 "/media/disk/Desktop/sandbox/CLS.git/Data/example-mixed.csv")))
89 :doc "This is an interesting dataframe-array"))
90 ;; *my-df-2*
92 (defparameter *my-df-3*
93 (make-instance 'dataframe-array
94 :storage
95 (listoflist->array
96 (transpose-listoflist
97 (rsm.string:file->number-table
98 "/media/disk/Desktop/sandbox/CLS.git/Data/example-numeric.csv")))
99 :doc "This is an interesting dataframe-array"))
100 ;; *my-df-3*
103 (defparameter *mat-1*
104 (make-matrix 3 3
105 :initial-contents #2A((2d0 3d0 4d0) (1d0 2d0 4d0) (2d0 4d0 5d0))))
107 (potrf *mat-1*) ;; factor
108 (potri *mat-1*) ;; invert
110 (defun minv-cholesky (a)
111 (assert (matrix-like-symmetric-p a))
112 (let ((a-fac (first (potrf (copy a)))))
113 (trap2mat (first (potri a-fac)))))
115 ;; #2A((2 3 4) (1 2 4) (2 4 5))
117 (chol-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
118 ;; (#2A((1.7888543819998317 0.0 0.0)
119 ;; (1.6770509831248424 0.11180339887498929 0.0)
120 ;; (2.23606797749979 2.23606797749979 3.332000937312528e-8))
121 ;; 5.000000000000003)
125 (defparameter my-chol-decomp-test (chol-decomp #2A((2 3 4) (1 2 4) (2 4 5))))
126 my-chol-decomp-test
127 (nth 0 my-chol-decomp-test)
128 (nth 1 my-chol-decomp-test)
131 (lu-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
132 ;; (#2A((2.0 3.0 4.0) (1.0 1.0 1.0) (0.5 0.5 1.5)) #(0 2 2) -1.0 NIL)
134 (lu-solve
135 (lu-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
136 #(2 3 4))
137 ;; #(-2.333333333333333 1.3333333333333335 0.6666666666666666)
139 (inverse #2A((2 3 4) (1 2 4) (2 4 5)))
140 ;; #2A((2.0 -0.33333333333333326 -1.3333333333333335)
141 ;; (-1.0 -0.6666666666666666 1.3333333333333333)
142 ;; (0.0 0.6666666666666666 -0.3333333333333333))
144 (sv-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
145 ;; (#2A((-0.5536537653489974 0.34181191712789266 -0.7593629708013371)
146 ;; (-0.4653437312661058 -0.8832095891230851 -0.05827549615722014)
147 ;; (-0.6905959164998124 0.3211003503429828 0.6480523475178517))
148 ;; #(9.699290438141343 0.8971681569301373 0.3447525123483081)
149 ;; #2A((-0.30454218417339873 0.49334669582252344 -0.8147779426198863)
150 ;; (-0.5520024849987308 0.6057035911404464 0.5730762743603965)
151 ;; (-0.7762392122368734 -0.6242853493399995 -0.08786630745236332))
152 ;; T)
154 (qr-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
155 ;; (#2A((-0.6666666666666665 0.7453559924999298 5.551115123125783e-17)
156 ;; (-0.3333333333333333 -0.2981423969999719 -0.894427190999916)
157 ;; (-0.6666666666666666 -0.5962847939999439 0.44721359549995787))
158 ;; #2A((-3.0 -5.333333333333334 -7.333333333333332)
159 ;; (0.0 -0.7453559924999292 -1.1925695879998877)
160 ;; (0.0 0.0 -1.3416407864998738)))
162 (rcondest #2A((2 3 4) (1 2 4) (2 4 5)))
163 ;; 6.8157451e7
164 ;;; CURRENTLY FAILS!!
166 (eigen #2A((2 3 4) (1 2 4) (2 4 5)))
167 ;; (#(10.656854249492381 -0.6568542494923802 -0.9999999999999996)
168 ;; (#(0.4999999999999998 0.4999999999999997 0.7071067811865475)
169 ;; #(-0.49999999999999856 -0.5000000000000011 0.7071067811865474)
170 ;; #(0.7071067811865483 -0.7071067811865466 -1.2560739669470215e-15))
171 ;; NIL)
173 (spline #(1.0 1.2 1.3 1.8 2.1 2.5)
174 #(1.2 2.0 2.1 2.0 1.1 2.8) :xvals 6)
175 ;; ((1.0 1.3 1.6 1.9 2.2 2.5)
176 ;; (1.2 2.1 2.2750696543866313 1.6465231041904045 1.2186576148879609 2.8))
178 ;;; using KERNEL-SMOOTH-FRONT, not KERNEL-SMOOTH-CPORT
179 (kernel-smooth #(1.0 1.2 1.3 1.8 2.1 2.5)
180 #(1.2 2.0 2.1 2.0 1.1 2.8) :xvals 5)
181 ;; ((1.0 1.375 1.75 2.125 2.5)
182 ;; (1.6603277642110226 1.9471748095239771 1.7938127405752287
183 ;; 1.5871511322219498 2.518194783156392))
185 (kernel-dens #(1.0 1.2 2.5 2.1 1.8 1.2) :xvals 5)
186 ;; ((1.0 1.375 1.75 2.125 2.5)
187 ;; (0.7224150453621405 0.5820045548233707 0.38216411702854214
188 ;; 0.4829822708587095 0.3485939156929503))
190 (fft #(1.0 1.2 2.5 2.1 1.8))
191 ;; #(#C(1.0 0.0) #C(1.2 0.0) #C(2.5 0.0) #C(2.1 0.0) #C(1.8 0.0))
193 (lowess #(1.0 1.2 2.5 2.1 1.8 1.2) #(1.2 2.0 2.1 2.0 1.1 2.8))
194 ;; (#(1.0 1.2 1.2 1.8 2.1 2.5))
198 ;;;; Special functions
200 ;; Log-gamma function
202 (log-gamma 3.4) ;;1.0923280596789584
206 ;;;; Probability functions
208 ;; looking at these a bit more, perhaps a more CLOSy style is needed, i.e.
209 ;; (quantile :list-or-cons loc :type type (one of 'empirical 'normal 'cauchy, etc...))
210 ;; similar for the cdf, density, and rand.
211 ;; Probably worth figuring out how to add a new distribution
212 ;; efficiently, i.e. by keeping some kind of list.
214 ;; Normal distribution
216 (normal-quant 0.95) ;;1.6448536279366268
217 (normal-cdf 1.3) ;;0.9031995154143897
218 (normal-dens 1.3) ;;0.17136859204780736
219 (normal-rand 2) ;;(-0.40502015f0 -0.8091404f0)
221 (bivnorm-cdf 0.2 0.4 0.6) ;;0.4736873734160288
223 ;; Cauchy distribution
225 (cauchy-quant 0.95) ;;6.313751514675031
226 (cauchy-cdf 1.3) ;;0.7912855998398473
227 (cauchy-dens 1.3) ;;0.1183308127104695
228 (cauchy-rand 2) ;;(-1.06224644160405 -0.4524695943939537)
230 ;; Gamma distribution
232 (gamma-quant 0.95 4.3) ;;8.178692439291645
233 (gamma-cdf 1.3 4.3) ;;0.028895150986674906
234 (gamma-dens 1.3 4.3) ;;0.0731517686447374
235 (gamma-rand 2 4.3) ;;(2.454918912880936 4.081365384357454)
237 ;; Chi-square distribution
239 (chisq-quant 0.95 3) ;;7.814727903379012
240 (chisq-cdf 1 5) ;;0.03743422675631789
241 (chisq-dens 1 5) ;;0.08065690818083521
242 (chisq-rand 2 4) ;;(1.968535826180572 2.9988646156942997)
244 ;; Beta distribution
246 (beta-quant 0.95 3 2) ;;0.9023885371149876
247 (beta-cdf 0.4 2 2.4) ;;0.4247997418541529
248 (beta-dens 0.4 2 2.4) ;;1.5964741858913518
249 (beta-rand 2 2 2.4) ;;(0.8014897077282279 0.6516371997922659)
251 ;; t distribution
253 (t-quant 0.95 3) ;;2.35336343484194
254 (t-cdf 1 2.3) ;;0.794733624298342
255 (t-dens 1 2.3) ;;0.1978163816318102
256 (t-rand 2 2.3) ;;(-0.34303672776089306 -1.142505872436518)
258 ;; F distribution
260 (f-quant 0.95 3 5) ;;5.409451318117459
261 (f-cdf 1 3.2 5.4) ;;0.5347130905510765
262 (f-dens 1 3.2 5.4) ;;0.37551128864591415
263 (f-rand 2 3 2) ;;(0.7939093442091963 0.07442694152491144)
265 ;; Poisson distribution
267 (poisson-quant 0.95 3.2) ;;6
268 (poisson-cdf 1 3.2) ;;0.17120125672252395
269 (poisson-pmf 1 3.2) ;;0.13043905274097067
270 (poisson-rand 5 3.2) ;;(2 1 2 0 3)
272 ;; Binomial distribution
274 (binomial-quant 0.95 3 0.4) ;;; DOESN'T RETURN
275 (binomial-quant 0 3 0.4) ;;; -2147483648
276 (binomial-cdf 1 3 0.4) ;;0.6479999999965776
277 (binomial-pmf 1 3 0.4) ;;0.4320000000226171
278 (binomial-rand 5 3 0.4) ;;(2 2 0 1 2)
280 ;;;; OBJECT SYSTEM
282 (in-package :ls-user)
283 (defproto *test-proto*)
284 *test-proto*
285 (defmeth *test-proto* :make-data (&rest args) nil)
287 (defparameter my-proto-instance nil)
288 (setf my-proto-instance (send *test-proto* :new))
289 (send *test-proto* :own-slots)
290 (lsos::ls-object-slots *test-proto*)
291 (lsos::ls-object-methods *test-proto*)
292 (lsos::ls-object-parents *test-proto*)
293 (lsos::ls-object-preclist *test-proto*)
294 ;;; The following fail and I do not know why?
295 (send *test-proto* :has-slot 'proto-name)
296 (send *test-proto* :has-slot 'PROTO-NAME)
297 (send *test-proto* :has-slot 'make-data)
298 (send *test-proto* :has-slot 'MAKE-DATA)
299 (send *test-proto* :has-method 'make-data)
300 (send *test-proto* :has-method 'MAKE-DATA)
303 (defproto2 *test-proto3* (list) (list) (list) "test doc" t)
304 (defproto2 *test-proto4*)
305 *test-proto2*
306 (defmeth *test-proto* :make-data (&rest args) nil)
308 (defparameter my-proto-instance nil)
309 (setf my-proto-instance (send *test-proto* :new))
310 (send *test-proto* :own-slots)
311 (send *test-proto* :has-slot 'proto-name)
312 (send *test-proto* :has-slot 'PROTO-NAME)
315 ;;;; Testing
317 (in-package :lisp-stat-unittests)
318 (testsuites)
319 (print-tests)
320 (run-tests)
321 (last-test-status)
322 ;;(failures)
324 (describe (run-tests :suite 'lisp-stat-ut-testsupport))
325 (describe (run-tests :suite 'lisp-stat-ut-testsupport2))
327 (testsuite-tests 'lisp-stat-ut)
328 (run-tests :suite 'lisp-stat-ut)
329 (describe (run-tests :suite 'lisp-stat-ut))
331 (run-tests :suite 'lisp-stat-ut-probdistn)
332 (describe (run-tests :suite 'lisp-stat-ut-probdistn))
333 (run-tests :suite 'lisp-stat-ut-spec-fns)
334 (describe (run-tests :suite 'lisp-stat-ut-spec-fns))
336 (find-testsuite 'lisp-stat-ut-lin-alg)
337 (testsuite-tests 'lisp-stat-ut-lin-alg)
338 (run-tests :suite 'lisp-stat-ut-lin-alg)
339 (describe (run-tests :suite 'lisp-stat-ut-lin-alg))
341 ;;;; Data Analysis test
343 (in-package :ls-user)
345 ;; LispStat 1 approach to variables
347 (progn
348 (def iron (list 61 175 111 124 130 173 169 169 160 224 257 333 199))
349 iron
350 (def aluminum (list 13 21 24 23 64 38 33 61 39 71 112 88 54))
351 aluminum
352 (def absorbtion (list 4 18 14 18 26 26 21 30 28 36 65 62 40))
353 absorbtion
355 ;; LispStat 1 approach to data frames... (list of lists).
357 (DEF DIABETES
358 (QUOTE ((80 97 105 90 90 86 100 85 97 97 91 87 78 90 86 80 90 99 85 90 90 88 95 90 92 74 98 100 86 98 70 99 75 90 85 99 100 78 106 98 102 90 94 80 93 86 85 96 88 87 94 93 86 86 96 86 89 83 98 100 110 88 100 80 89 91 96 95 82 84 90 100 86 93 107 112 94 93 93 90 99 93 85 89 96 111 107 114 101 108 112 105 103 99 102 110 102 96 95 112 110 92 104 75 92 92 92 93 112 88 114 103 300 303 125 280 216 190 151 303 173 203 195 140 151 275 260 149 233 146 124 213 330 123 130 120 138 188 339 265 353 180 213 328 346)
359 (356 289 319 356 323 381 350 301 379 296 353 306 290 371 312 393 364 359 296 345 378 304 347 327 386 365 365 352 325 321 360 336 352 353 373 376 367 335 396 277 378 360 291 269 318 328 334 356 291 360 313 306 319 349 332 323 323 351 478 398 426 439 429 333 472 436 418 391 390 416 413 385 393 376 403 414 426 364 391 356 398 393 425 318 465 558 503 540 469 486 568 527 537 466 599 477 472 456 517 503 522 476 472 455 442 541 580 472 562 423 643 533 1468 1487 714 1470 1113 972 854 1364 832 967 920 613 857 1373 1133 849 1183 847 538 1001 1520 557 670 636 741 958 1354 1263 1428 923 1025 1246 1568)
360 (124 117 143 199 240 157 221 186 142 131 221 178 136 200 208 202 152 185 116 123 136 134 184 192 279 228 145 172 179 222 134 143 169 263 174 134 182 241 128 222 165 282 94 121 73 106 118 112 157 292 200 220 144 109 151 158 73 81 151 122 117 208 201 131 162 148 130 137 375 146 344 192 115 195 267 281 213 156 221 199 76 490 143 73 237 748 320 188 607 297 232 480 622 287 266 124 297 326 564 408 325 433 180 392 109 313 132 285 139 212 155 120 28 23 232 54 81 87 76 42 102 138 160 131 145 45 118 159 73 103 460 42 13 130 44 314 219 100 10 83 41 77 29 124 15)
361 (3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 2 3 3 2 2 3 2 2 3 3 3 3 2 3 3 3 3 3 2 3 3 3 3 3 2 3 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1))))
364 (DEF DLABS (QUOTE ("GLUFAST" "GLUTEST" "INSTEST" "CCLASS")))
365 (format t "loaded data.~%")
366 ) ;; eval at this point.
368 ;; Simple univariate variable-specific descriptions.
369 (fivnum absorbtion)
370 (median absorbtion)
371 (sort-data absorbtion)
372 (rank absorbtion)
373 (standard-deviation absorbtion)
374 (interquartile-range absorbtion)
376 (lisp-stat-matrix::bind-columns aluminum iron)
377 (bind-columns aluminum iron)
378 (apply #'bind-columns (list aluminum iron))
379 (lisp-stat-matrix::bind-columns #2a((1 2)(3 4)) #(5 6))
380 (bind-columns #2a((1 2)(3 4)) #(5 6))
383 (defparameter fit1 nil)
384 (setf fit1 (regression-model absorbtion iron))
385 (send fit1 :display)
386 (send fit1 :residuals)
388 iron
389 (defparameter fit1a nil)
390 (setf fit1a (regression-model absorbtion iron :print nil))
391 (send fit1a :doc)
392 ;; (setf (send fit1a :doc) "this") ;; FIXME: this error...
393 (send fit1a :doc "this") ;; FIXME: this is a more natural
394 (send fit1a :doc)
395 (send fit1a :x)
396 (send fit1a :y)
397 (send fit1a :compute)
398 (send fit1a :sweep-matrix)
399 (send fit1a :basis)
400 (send fit1a :residuals)
401 (send fit1a :display)
403 #+nil(progn
404 ;; syntax example
405 (array-dimension #2A ((1)) 0)
408 ;;; FIXME: need to get multiple-linear regression working -- clearly
409 ;;; simple linear is working above!
410 (defvar m nil "holding variable.")
411 (def m (regression-model (list iron aluminum) absorbtion :print nil))
412 (send m :compute)
413 (send m :sweep-matrix)
414 (format t "~%~A~%" (send m :sweep-matrix))
416 ;; ERROR... FIX-ME!!
417 (send m :basis) ;; this should be positive?
418 (send m :coef-estimates)
420 (send m :display)
421 (def m (regression-model (bind-columns iron aluminum) absorbtion))
422 (send m :help)
423 (send m :help :display)
424 (send m :help :basis)
425 ;; No graphics! But handle the error gracefully...
426 (send m :plot-residuals)
429 (typep aluminum 'sequence)
430 (typep iron 'sequence)
431 (matrixp iron)
433 *variables*
435 (variables)
436 (undef 'iron)
437 (variables)
439 ;;; Plotting!
441 (asdf:oos 'asdf:compile-op 'cl-cairo2 :force t)
442 (asdf:oos 'asdf:load-op 'cl-cairo2)
444 ;; The above can be used to generate PDF, PS, PNG, and X11/Microsoft
445 ;; displays (the latter being a proof of concept, of limited use for
446 ;; "real work".
448 ;; and this below, as well.
449 (asdf:oos 'asdf:load-op 'cl-plplot)
451 ;;; Using R!
453 (asdf:oos 'asdf:compile-op 'rclg :force t)
454 (asdf:oos 'asdf:load-op 'rclg)
457 (in-package :rclg-user)
459 ;; rclg-init::*r-started*
461 ;;;#3 Start R within Lisp
463 (start-rclg)
464 ;; rclg-init::*r-started*
465 (rclg-init::check-stack)
466 (r "Cstack_info")
467 (defparameter *x* (r seq 1 11))
468 (defparameter *y* (r rnorm 10))
470 (r plot *x* *y*)
473 (defparameter *r-version* (r "version"))
475 ;; This is for illustrative purposes only. It is not a "good" use of rnbi.
476 ;; Really, you'll want rnbi to hold anonymous intermeditae results, like:
477 (r plot *x* (rnbi rnorm 10))
479 (r "Sys.getenv" "LD_LIBRARY_PATH")
480 (r "Sys.getenv" "LD_PRELOAD")
482 (r "ls")
483 (r ls)
484 (r "search")
486 (r "geterrmessage")
488 (r "library" "stats")
489 (r library "MASS")
490 (r "library" "Biobase")
492 (setf my.lib "Biobase")
493 my.lib
494 (r library my.lib)
496 (r "ls")
498 (r "print.default" 3)
499 (r "rnorm" 10)
501 ;; Working in the R space
503 (r assign "x" 5)
504 (r assign "x2" (list 1 2 3 5))
506 (r assign "x2" #(1 2 3 5 3 4 5))
507 (r assign "z" "y") ;; unlike the above, this assigns character data
508 (r "ls")
509 (r ls)
511 (setf my.r.x2 (r get "x2")) ;; moving data from R to CL
512 (r assign "x2" my.r.x2) ;; moving data from CL to R
514 ;; The following is not the smartest thing to do!
515 ;;(r q)
519 ;;; How might we do statistics with Common Lisp?
520 ;;; How might we work with a data.frame?
521 ;;; What could the structures be?
522 ;;; How much hinting, and of what type, should drive the data
523 ;;; analysis?
525 (defpackage :my-data-analysis-example
526 (:documentation "Example work-package for a data analysis")
527 (:use :common-lisp :lisp-stat)
528 (:export results figures report))
530 (in-package :my-data-analysis-example)
532 (defvar my-dataset1 (read-file "data/test1.lisp"))
533 ;; or
534 (defvar my-dataset2 (read-file "data/test1.csv" :type 'csv))
536 ;;; manipulate
538 (setf my-dataset2 (set-description my-datasets2
539 :dependent-variables (list of symbols)))
540 (setf my-dataset2 (set-description my-datasets2
541 :independent-variables (list of symbols)))
543 ;; the following could be true in many cases.
544 (assert
545 (list-intersection (get-description my-datasets2 :independent-variables)
546 (get-description my-datasets2 :dependent-variables)))
548 ;; but we could phrase better,i.e.
550 (get-description
551 my-datasets2
552 :predicate-list-on-variable-metadata (list (and 'independent-variables
553 'dependent-variables)))
556 ;; statistical relations re: input/output, as done above, is one
557 ;; issue, another one is getting the right approach for statistical
558 ;; typing, i.e.
559 (get-description
560 my-datasets2
561 :predicate-list-on-variable-metadata (list 'ordinal-variables))
564 ;; so we could use a set of logical ops to selection from variable
565 ;; metadata, i.e.
566 ;; and, or, not
567 ;; do we really need the simplifying extensions?
570 ;;; output to REPL
572 (report my-dataset1 :style 'five-num)
573 (report my-dataset1 :style 'univariate)
574 (report my-dataset1 :style 'bivariate)
575 (report my-dataset1 :style 'metadata)
577 ;;; to file?
579 (report my-dataset1
580 :style 'five-num
581 :format 'pdf
582 :stream (filename-as-stream "my-dataset1-5num.pdf"))
583 (report my-dataset1 :style 'univariate)
584 (report my-dataset1 :style 'bivariate)
585 (report my-dataset1 :style 'metadata)
587 ;;; so report could handle datasets... and models?
589 (report my-model :style 'formula)
590 (report my-model :style 'simulate
591 (list :parameters (:eta 5 :mu 4 :sigma (list 2 1 0.5))
592 :number-of-reps 10))
593 ;; should return a list of parameters along with range information,
594 ;; useful for auto-building the above. Note that there are 3 types
595 ;; of parameters that can be considered -- we can have values which
596 ;; define ddata, we can have values which define fixed values and some
597 ;; could be things tht we estimate.
600 (defgeneric report (object &optional style format stream)
601 (:documentation "method for reporting on data"))
603 (defmethod report ((object dataset)
604 (style report-dataset-style-type)
605 (format output-format-type)
606 ((stream *repl*) output-stream-type))
607 "dataset reporting")
610 (defmethod report ((object model)
611 (style report-model-style-type)
612 (format output-format-type)
613 ((stream *repl*) output-stream-type))
614 "model reporting")
616 (defmethod report ((object analysis-instance)
617 (style report-analysis-style-type)
618 (format output-format-type)
619 ((stream *repl*) output-stream-type))
620 "model + dataset reporting")
623 ;; parameters are just things which get filled with values, repeatedly
624 ;; with data, or by considering to need estimation.
625 (parameters my-model)
626 (parameters my-model :type 'data)
627 (parameters my-model :type 'fixed)
628 (parameters my-model :type 'estimate)
629 (parameters my-model :type '(estimate fixed))
630 (parameters my-model :list-types) ;; useful for list-based extraction
631 ;; of particular types
633 (setf my-model-data-instance
634 (compute model data :specification (list :spec 'linear-model
635 :depvar y
636 :indepvar (list x1 x2))))
637 (report my-model-data-instance)
640 ;;; So how might we use this? Probably need to consider the
641 ;;; serialization of any lisp objects generated, perhaps via some form
642 ;;; of memoization...?
643 (in-package :cl-user)
645 (my-data-analysis-example:report :type 'full)
646 (my-data-analysis-example:report :type 'summary)
647 (my-data-analysis-example:figures :type 'pdf :file "results-figs.pdf")
649 (my-data-analysis-example:report)
651 ;;; more stuff
653 (send m :display)
654 (def m (regression-model (bind-columns iron aluminum) absorbtion))
655 (send m :help)
656 (send m :help :display)
657 (send m :help :basis)
659 (send m :plot-residuals)
661 (progn
662 ;; General Lisp, there is also a need to add, remove symbols from the
663 ;; workspace/namespace. This is a fundamental skill, similar to
664 ;; stopping, which is critical.
666 ;; boundp, fboundp
667 ;; makunbound, fmakunbound
671 (progn
672 ;;; A study in array vs list access
673 (defparameter *x* (list 1 2 3))
674 (defparameter *y* #(1 2 3))
675 (defparameter *z* (list 1 (list 2 3) (list 4 5 (list 6 7)) ))
676 (length *x*)
677 (length *y*)
678 (length *z*) ; => need a means to make this 7.
679 (length (reduce #'cons *z*)) ; => not quite -- missing iterative
681 (nelts *x*)
682 (nth 1 *x*)
683 (aref *y* 1)
684 (setf (nth 1 *x*) 6)
686 (setf (aref *y* 1) 6)
690 (in-package :ls-user)
692 (progn
693 (defparameter *x* (make-vector 5 :initial-contents '((1d0 2d0 3d0 4d0 5d0))))
694 ;; estimating a mean, simple way.
695 (/ (loop for i from 0 to (- (nelts *x*) 1)
696 summing (vref *x* i))
697 (nelts *x*))
699 (defun mean (x)
700 (checktype x 'vector-like)
701 (/ (loop for i from 0 to (- (nelts *x*) 1)
702 summing (vref *x* i))
703 (nelts *x*)))
705 ;; estimating variance, Moments
706 (let ((meanx (mean *x*))
707 (n (nelts *x*)))
708 (/ (loop for i from 0 to (1- n)
709 summing (* (- (vref *x* i) meanx)
710 (- (vref *x* i) meanx)))
713 ;; estimating variance, Moments
714 (let ((meanx (mean *x*))
715 (nm1 (1- (nelts *x*))))
716 (/ (loop for i from 0 to nm1
717 summing (* (- (vref *x* i) meanx)
718 (- (vref *x* i) meanx) ))
719 nm1))
723 ;;;;;;;;;;;;;;; Data stuff
725 (progn ;; Data setup
727 ;; Making data-frames (i.e. cases (rows) by variables (columns))
728 ;; takes a bit of getting used to. For this, it is important to
729 ;; realize that we can do the following:
730 ;; #1 - consider the possibility of having a row, and transposing
731 ;; it, so the list-of-lists is: ((1 2 3 4 5)) (1 row, 5 columns)
732 ;; #2 - naturally list-of-lists: ((1)(2)(3)(4)(5)) (5 rows, 1 column)
733 ;; see src/data/listoflist.lisp for code to process this particular
734 ;; data structure.
735 (defparameter *indep-vars-1-matrix*
736 (transpose (make-matrix 1 (length iron)
737 :initial-contents
738 (list (mapcar #'(lambda (x) (coerce x 'double-float))
739 iron))))
740 "creating iron into double float, straightforward")
742 (documentation '*indep-vars-1-matrix* 'variable)
743 ;; *indep-vars-1-matrix*
745 ;; or directly:
746 (defparameter *indep-vars-1a-matrix*
747 (make-matrix (length iron) 1
748 :initial-contents
749 (mapcar #'(lambda (x) (list (coerce x 'double-float)))
750 iron)))
751 ;; *indep-vars-1a-matrix*
753 ;; and mathematically, they seem equal:
754 (m= *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => T
755 ;; but of course not completely...
756 (eql *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => NIL
757 (eq *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => NIL
759 ;; and verify...
760 (print *indep-vars-1-matrix*)
761 (print *indep-vars-1a-matrix*)
763 (documentation 'lisp-matrix:bind2 'function) ; by which we mean:
764 (documentation 'bind2 'function)
765 (bind2 *indep-vars-1-matrix* *indep-vars-1a-matrix* :by :column) ; 2 col
766 (bind2 *indep-vars-1-matrix* *indep-vars-1a-matrix* :by :row) ; 1 long col
768 ;; the weird way
769 (defparameter *indep-vars-2-matrix*
770 (transpose (make-matrix 2 (length iron)
771 :initial-contents
772 (list
773 (mapcar #'(lambda (x) (coerce x 'double-float))
774 iron)
775 (mapcar #'(lambda (x) (coerce x 'double-float))
776 aluminum)))))
777 ;; *indep-vars-2-matrix*
779 ;; the "right"? way
780 (defparameter *indep-vars-2-matrix*
781 (make-matrix (length iron) 2
782 :initial-contents
783 (mapcar #'(lambda (x y)
784 (list (coerce x 'double-float)
785 (coerce y 'double-float)))
786 iron aluminum)))
787 ;; *indep-vars-2-matrix*
790 ;; The below FAILS due to coercion issues; it just isn't lispy, it's R'y.
792 (defparameter *dep-var* (make-vector (length absorbtion)
793 :initial-contents (list absorbtion)))
795 ;; BUT below, this should be the right type.
796 (defparameter *dep-var*
797 (make-vector (length absorbtion)
798 :type :row
799 :initial-contents
800 (list
801 (mapcar #'(lambda (x) (coerce x 'double-float))
802 absorbtion))))
803 ;; *dep-var*
806 (defparameter *dep-var-int*
807 (make-vector (length absorbtion)
808 :type :row
809 :element-type 'integer
810 :initial-contents (list absorbtion)))
812 (typep *dep-var* 'matrix-like) ; => T
813 (typep *dep-var* 'vector-like) ; => T
815 (typep *indep-vars-1-matrix* 'matrix-like) ; => T
816 (typep *indep-vars-1-matrix* 'vector-like) ; => T
817 (typep *indep-vars-2-matrix* 'matrix-like) ; => T
818 (typep *indep-vars-2-matrix* 'vector-like) ; => F
820 iron
821 ;; following fails, need to ensure that we work on list elts, not just
822 ;; elts within a list:
824 ;; (coerce iron 'real)
826 ;; the following is a general list-conversion coercion approach -- is
827 ;; there a more efficient way?
828 ;; (coerce 1 'real)
829 ;; (mapcar #'(lambda (x) (coerce x 'double-float)) iron)
831 (princ "Data Set up"))
836 (progn ;; Data setup
838 (describe 'make-matrix)
840 (defparameter *indep-vars-2-matrix*
841 (make-matrix (length iron) 2
842 :initial-contents
843 (mapcar #'(lambda (x y)
844 (list (coerce x 'double-float)
845 (coerce y 'double-float)))
846 iron aluminum)))
849 (defparameter *dep-var*
850 (make-vector (length absorbtion)
851 :type :row
852 :initial-contents
853 (list
854 (mapcar #'(lambda (x) (coerce x 'double-float))
855 absorbtion))))
857 (make-dataframe *dep-var*)
858 (make-dataframe (transpose *dep-var*))
860 (defparameter *dep-var-int*
861 (make-vector (length absorbtion)
862 :type :row
863 :element-type 'integer
864 :initial-contents (list absorbtion)))
867 (defparameter *xv+1a*
868 (make-matrix
870 :initial-contents #2A((1d0 1d0)
871 (1d0 3d0)
872 (1d0 2d0)
873 (1d0 4d0)
874 (1d0 3d0)
875 (1d0 5d0)
876 (1d0 4d0)
877 (1d0 6d0))))
879 (defparameter *xv+1b*
880 (bind2
881 (ones 8 1)
882 (make-matrix
884 :initial-contents '((1d0)
885 (3d0)
886 (2d0)
887 (4d0)
888 (3d0)
889 (5d0)
890 (4d0)
891 (6d0)))
892 :by :column))
894 (m= *xv+1a* *xv+1b*) ; => T
896 (princ "Data Set up"))
900 ;;;; LM
902 (progn
904 (defparameter *y*
905 (make-vector
907 :type :row
908 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
911 (defparameter *xv+1*
912 (make-matrix
914 :initial-contents '((1d0 1d0)
915 (1d0 3d0)
916 (1d0 2d0)
917 (1d0 4d0)
918 (1d0 3d0)
919 (1d0 5d0)
920 (1d0 4d0)
921 (1d0 6d0))))
924 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
925 (defparameter *xtx-2* (m* (transpose *xv+1*) *xv+1*))
926 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
927 ;; 8.0d0 28.0d0
928 ;; 28.0d0 116.0d0>
930 (defparameter *xty-2* (m* (transpose *xv+1*) (transpose *y*)))
931 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
932 ;; 36.0d0
933 ;; 150.0d0>
935 (defparameter *rcond-2* 0.000001)
936 (defparameter *betahat-2* (gelsy *xtx-2* *xty-2* *rcond-2*))
937 ;; *xtx-2* => "details of complete orthogonal factorization"
938 ;; according to man page:
939 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
940 ;; -119.33147112141039d0 -29.095426104883202d0
941 ;; 0.7873402682880205d0 -1.20672274167718d0>
943 ;; *xty-2* => output becomes solution:
944 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
945 ;; -0.16666666666668312d0
946 ;; 1.333333333333337d0>
948 *betahat-2* ; which matches R, see below
950 (documentation 'gelsy 'function)
953 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
954 ;; -0.16666666666668312 1.333333333333337>
955 ;; 2)
957 ;; ## Test case in R:
958 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
959 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
960 ;; lm(y~x)
961 ;; ## => Call: lm(formula = y ~ x)
963 ;; Coefficients: (Intercept) x
964 ;; -0.1667 1.3333
966 ;; summary(lm(y~x))
967 ;; ## =>
969 ;; Call:
970 ;; lm(formula = y ~ x)
972 ;; Residuals:
973 ;; Min 1Q Median 3Q Max
974 ;; -1.833e+00 -6.667e-01 -3.886e-16 6.667e-01 1.833e+00
976 ;; Coefficients:
977 ;; Estimate Std. Error t value Pr(>|t|)
978 ;; (Intercept) -0.1667 1.1587 -0.144 0.89034
979 ;; x 1.3333 0.3043 4.382 0.00466 **
980 ;; ---
981 ;; Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
983 ;; Residual standard error: 1.291 on 6 degrees of freedom
984 ;; Multiple R-squared: 0.7619, Adjusted R-squared: 0.7222
985 ;; F-statistic: 19.2 on 1 and 6 DF, p-value: 0.004659
989 ;; which suggests one might do (modulo ensuring correct
990 ;; orientations). When this is finalized, it should migrate to
991 ;; CLS.
995 (defparameter *n* 20) ; # rows = # obsns
996 (defparameter *p* 10) ; # cols = # vars
997 (defparameter *x-temp* (rand *n* *p*))
998 (defparameter *b-temp* (rand *p* 1))
999 (defparameter *y-temp* (m* *x-temp* *b-temp*))
1000 ;; so Y=Xb + \eps
1001 (defparameter *rcond* (* (coerce (expt 2 -52) 'double-float)
1002 (max (nrows *x-temp*) (ncols *y-temp*))))
1003 (defparameter *orig-x* (copy *x-temp*))
1004 (defparameter *orig-b* (copy *b-temp*))
1005 (defparameter *orig-y* (copy *y-temp*))
1007 (defparameter *lm-result* (lm *x-temp* *y-temp*))
1008 (princ (first *lm-result*))
1009 (princ (second *lm-result*))
1010 (princ (third *lm-result*))
1011 (v= (third *lm-result*)
1012 (v- (first (first *lm-result*))
1013 (first (second *lm-result*))))
1018 ;; Some issues exist in the LAPACK vs. LINPACK variants, hence R
1019 ;; uses LINPACK primarily, rather than LAPACK. See comments in R
1020 ;; source for issues.
1023 ;; Goal is to start from X, Y and then realize that if
1024 ;; Y = X \beta, then, i.e. 8x1 = 8xp px1 + 8x1
1025 ;; XtX \hat\beta = Xt Y
1026 ;; so that we can solve the equation W \beta = Z where W and Z
1027 ;; are known, to estimate \beta.
1029 ;; the above is known to be numerically instable -- some processing
1030 ;; of X is preferred and should be done prior. And most of the
1031 ;; transformation-based work does precisely that.
1033 ;; recall: Var[Y] = E[(Y - E[Y])(Y-E[Y])t]
1034 ;; = E[Y Yt] - 2 \mu \mut + \mu \mut
1035 ;; = E[Y Yt] - \mu \mut
1037 ;; Var Y = E[Y^2] - \mu^2
1040 ;; For initial estimates of covariance of \hat\beta:
1042 ;; \hat\beta = (Xt X)^-1 Xt Y
1043 ;; with E[ \hat\beta ]
1044 ;; = E[ (Xt X)^-1 Xt Y ]
1045 ;; = E[(Xt X)^-1 Xt (X\beta)]
1046 ;; = \beta
1048 ;; So Var[\hat\beta] = ...
1049 ;; (Xt X)
1050 ;; and this gives SE(\beta_i) = (* (sqrt (mref Var i i)) adjustment)
1053 ;; from docs:
1055 (setf *temp-result*
1056 (let ((*default-implementation* :foreign-array))
1057 (let* ((m 10)
1058 (n 10)
1059 (a (rand m n))
1060 (x (rand n 1))
1061 (b (m* a x))
1062 (rcond (* (coerce (expt 2 -52) 'double-float)
1063 (max (nrows a) (ncols a))))
1064 (orig-a (copy a))
1065 (orig-b (copy b))
1066 (orig-x (copy x)))
1067 (list x (gelsy a b rcond))
1068 ;; no applicable conversion?
1069 ;; (m- (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1))
1070 ;; (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1)) )
1071 (v- x (first (gelsy a b rcond))))))
1074 (princ *temp-result*)
1076 (setf *temp-result*
1077 (let ((*default-implementation* :lisp-array))
1078 (let* ((m 10)
1079 (n 10)
1080 (a (rand m n))
1081 (x (rand n 1))
1082 (b (m* a x))
1083 (rcond (* (coerce (expt 2 -52) 'double-float)
1084 (max (nrows a) (ncols a))))
1085 (orig-a (copy a))
1086 (orig-b (copy b))
1087 (orig-x (copy x)))
1088 (list x (gelsy a b rcond))
1089 (m- x (first (gelsy a b rcond)))
1091 (princ *temp-result*)
1094 (defparameter *xv*
1095 (make-vector
1097 :type :row ;; default, not usually needed!
1098 :initial-contents '((1d0 3d0 2d0 4d0 3d0 5d0 4d0 6d0))))
1100 (defparameter *y*
1101 (make-vector
1103 :type :row
1104 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
1106 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
1107 (defparameter *xtx-1* (m* *xv* (transpose *xv*)))
1108 (defparameter *xty-1* (m* *xv* (transpose *y*)))
1109 (defparameter *rcond-in* (* (coerce (expt 2 -52) 'double-float)
1110 (max (nrows *xtx-1*)
1111 (ncols *xty-1*))))
1113 (defparameter *betahat* (gelsy *xtx-1* *xty-1* *rcond-in*))
1115 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (1 x 1)
1116 ;; 1.293103448275862>
1117 ;; 1)
1119 ;; ## Test case in R:
1120 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
1121 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
1122 ;; lm(y~x-1)
1123 ;; ## =>
1124 ;; Call:
1125 ;; lm(formula = y ~ x - 1)
1127 ;; Coefficients:
1128 ;; x
1129 ;; 1.293
1131 (first *betahat*))
1136 (type-of #2A((1 2 3 4 5)
1137 (10 20 30 40 50)))
1139 (type-of (rand 10 20))
1141 (typep #2A((1 2 3 4 5)
1142 (10 20 30 40 50))
1143 'matrix-like)
1145 (typep (rand 10 20) 'matrix-like)
1147 (typep #2A((1 2 3 4 5)
1148 (10 20 30 40 50))
1149 'array)
1151 (typep (rand 10 20) 'array)