cl-pdf and cl-typesetting examples.
[CommonLispStat.git] / ls-demo.lisp
blob3e28eb145821e14a711b2af909ca2e24984a3590
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-06-15 08:15:54 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)
20 ;; (asdf:oos 'asdf:compile-op 'lispstat :force t)
21 (asdf:oos 'asdf:load-op 'lispstat)
23 (in-package :ls-user)
25 ;; a bit of infrastructure for beginners
26 (defparameter *my-cls-homedir*
27 "/media/disk/Desktop/sandbox/CLS.git/")
28 (concatenate 'string *my-cls-homedir* "Data/example.csv")
29 ;; implies
30 (defun localized-pathto (x)
31 (check-type x string)
32 (concatenate 'string *my-cls-homedir* x))
34 ;;; == READ DATA
36 (defparameter *my-df-1*
37 (make-instance 'dataframe-array
38 :storage #2A((1 2 3 4 5)
39 (10 20 30 40 50))
40 :doc "This is an un-interesting dataframe-array"
41 :case-labels (list "x" "y")
42 :var-labels (list "a" "b" "c" "d" "e")))
44 (setf (dfref *my-df-1* 0 0) -1d0)
45 ;; *my-df-1*
48 (make-dataframe #2A((1 2 3 4 5)
49 (10 20 30 40 50)))
51 (make-dataframe (rand 4 3))
56 (defparameter *my-df-2*
57 (make-dataframe #2A((1 2 3 4 5)
58 (10 20 30 40 50))
59 :caselabels (list "x" "y")
60 :varlabels (list "a" "b" "c" "d" "e")
61 :doc "This is another boring dataframe-array"))
63 (caselabels *my-df-1*)
64 (varlabels *my-df-1*)
68 (defparameter *my-df-2*
69 (make-dataframe #2A((a 2 T 4 5)
70 (b 20 nil 40 50))
71 :caselabels (list "x" "y")
72 :varlabels (list "a" "b" "c" "d" "e")
73 :doc "This is another boring dataframe-array"))
75 ;; *my-df-2*
78 ;;; HERE#1
80 ;;; read in a CSV dataframe...
83 ;; a better approach is:
84 (asdf:oos 'asdf:load-op 'rsm-string)
85 (rsm.string:file->string-table
86 (localized-pathto "Data/example-mixed.csv")
87 :delims ",")
89 (rsm.string:file->number-table
90 (localized-pathto "Data/example-numeric.csv")
91 :delims ",")
93 (rsm.string:file->number-table
94 (localized-pathto "Data/R-chickwts.csv")
95 :delims ",")
96 (rsm.string:file->string-table
97 (localized-pathto "Data/R-chickwts.csv")
98 :delims ",")
100 (defparameter *my-df-2*
101 (make-instance 'dataframe-array
102 :storage
103 (listoflist->array
104 (rsm.string:file->string-table
105 (localized-pathto "Data/example-mixed.csv")))
106 :doc "This is an interesting dataframe-array"))
107 ;; *my-df-2*
109 (defparameter *my-df-3*
110 (make-instance 'dataframe-array
111 :storage
112 (listoflist->array
113 (transpose-listoflist
114 (rsm.string:file->number-table
115 (localized-pathto "Data/example-numeric.csv"))))
116 :doc "This is an interesting dataframe-array"))
117 ;; *my-df-3*
120 (defparameter *my-df-4*
121 (make-instance 'dataframe-array
122 :storage
123 (listoflist->array
124 (rsm.string:file->number-table
125 (localized-pathto "Data/R-chickwts.csv")
126 :delims ","))
127 :doc "This is an interesting dataframe-array that currently fails"))
128 ;; *my-df-4*
131 (defparameter *my-df-5*
132 (make-instance 'dataframe-array
133 :storage
134 (listoflist->array
135 (transpose-listoflist
136 (rsm.string:file->number-table
137 (localized-pathto "Data/R-swiss.csv"))))
138 :doc "This is an interesting dataframe-array that currently fails"))
139 ;; *my-df-5*
142 (defparameter *mat-1*
143 (make-matrix 3 3
144 :initial-contents #2A((2d0 3d0 4d0) (3d0 2d0 4d0) (4d0 4d0 5d0))))
146 (defparameter *mat-2*
147 (let ((m (rand 3 3)))
148 (m* m (transpose m))))
150 (axpy 100.0d0 *mat-2* (eye 3 3))
152 (potrf (copy *mat-2*)) ;; factor
153 (potri (copy *mat-2*)) ;; invert
154 (minv-cholesky (copy *mat-2*))
155 (m* (minv-cholesky (copy *mat-2*)) *mat-2*)
157 (defparameter *mat-3*
158 (make-matrix
160 :initial-contents '((16d0 13d0 12d0)
161 (13d0 22d0 7d0)
162 (12d0 7d0 17d0))))
164 (potrf (copy *mat-3*)) ;; factor
167 *mat-3* =>
168 #<LA-SIMPLE-MATRIX-DOUBLE 3 x 3
169 16.0 13.0 12.0
170 13.0 22.0 7.0
171 12.0 7.0 17.0>
173 (potrf (copy *mat-3*)) =>
174 (#<LA-SIMPLE-MATRIX-DOUBLE 3 x 3
175 4.0 3.25 3.0
176 13.0 3.3819373146171707 -0.8131433980500301
177 12.0 7.0 2.7090215603069034>
178 "U" NIL)
180 ;; and compare with...
182 > testm <- matrix(data=c(16,13,12,13,22,7,12,7,17),nrow=3)
183 > chol(testm)
184 [,1] [,2] [,3]
185 [1,] 4 3.250000 3.0000000
186 [2,] 0 3.381937 -0.8131434
187 [3,] 0 0.000000 2.7090216
190 ;; which suggests that the major difference is that R zero's out the
191 ;; appropriate terms, and that CLS does not.
195 (potri (copy *mat-2*)) ;; invert
196 (minv-cholesky (copy *mat-2*))
197 (m* (minv-cholesky (copy *mat-2*)) *mat-2*)
201 (lu-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
202 ;; => (#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)
203 (lu-solve
204 (lu-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
205 #(2 3 4))
206 ;; => #(-2.333333333333333 1.3333333333333335 0.6666666666666666)
208 (getrf
209 (make-matrix 3 3
210 :initial-contents #2A((2d0 3d0 4d0) (1d0 2d0 4d0) (2d0 4d0 5d0))))
212 #| => ; so not so good for the vector, but matrix matches.
213 (#<LA-SIMPLE-MATRIX-DOUBLE 3 x 3
214 2.0 3.0 4.0
215 1.0 1.0 1.0
216 0.5 0.5 1.5>
217 #<FNV-INT32 (3) 1 3 3> NIL)
220 (msolve-lu
221 (make-matrix 3 3
222 :initial-contents #2A((2d0 3d0 4d0)
223 (1d0 2d0 4d0)
224 (2d0 4d0 5d0)))
225 (make-vector 3 :type :column
226 :initial-contents '((2d0)
227 (3d0)
228 (4d0))))
230 #| =>
231 #<LA-SIMPLE-VECTOR-DOUBLE (3 x 1)
232 -2.3333333333333335
233 1.3333333333333335
234 0.6666666666666666>
239 ;;; LU common applications
241 (defun minv-lu (a)
242 "invert A using LU Factorization"
243 (let ((a-fac (getrf (copy a))))
244 (first (getri (first a-fac) (second a-fac)))))
246 #+nil (progn
247 (let ((m1 (rand 3 3)))
248 (m* m1 (minv-lu m1))))
250 (defun msolve-lu (a b)
251 "Compute `x1' solving `A x = b', with LU factorization."
252 (let ((a-fac (getrf (copy a))))
253 (first (getrs (first a-fac) b (second a-fac)))))
257 ;; (inverse #2A((2 3 4) (1 2 4) (2 4 5)))
258 ;; #2A((2.0 -0.33333333333333326 -1.3333333333333335)
259 ;; (-1.0 -0.6666666666666666 1.3333333333333333)
260 ;; (0.0 0.6666666666666666 -0.3333333333333333))
262 (minv-lu
263 (make-matrix
265 :initial-contents #2A((2d0 3d0 4d0)
266 (1d0 2d0 4d0)
267 (2d0 4d0 5d0))))
271 #<LA-SIMPLE-MATRIX-DOUBLE 3 x 3
272 2.0 -0.3333333333333333 -1.3333333333333333
273 -1.0 -0.6666666666666666 1.3333333333333333
274 0.0 0.6666666666666666 -0.3333333333333333>
276 ;; so is correct.
280 ;;;;;HERE#2
282 (factorize
283 (make-matrix 3 3
284 :initial-contents #2A((2d0 3d0 4d0)
285 (1d0 2d0 4d0)
286 (2d0 4d0 5d0)))
287 :by :svd)
289 ;; (sv-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
290 ;; (#2A((-0.5536537653489974 0.34181191712789266 -0.7593629708013371)
291 ;; (-0.4653437312661058 -0.8832095891230851 -0.05827549615722014)
292 ;; (-0.6905959164998124 0.3211003503429828 0.6480523475178517))
293 ;; #(9.699290438141343 0.8971681569301373 0.3447525123483081)
294 ;; #2A((-0.30454218417339873 0.49334669582252344 -0.8147779426198863)
295 ;; (-0.5520024849987308 0.6057035911404464 0.5730762743603965)
296 ;; (-0.7762392122368734 -0.6242853493399995 -0.08786630745236332))
297 ;; T)
301 (qr-decomp #2A((2 3 4) (1 2 4) (2 4 5)))
302 ;; (#2A((-0.6666666666666665 0.7453559924999298 5.551115123125783e-17)
303 ;; (-0.3333333333333333 -0.2981423969999719 -0.894427190999916)
304 ;; (-0.6666666666666666 -0.5962847939999439 0.44721359549995787))
305 ;; #2A((-3.0 -5.333333333333334 -7.333333333333332)
306 ;; (0.0 -0.7453559924999292 -1.1925695879998877)
307 ;; (0.0 0.0 -1.3416407864998738)))
309 (rcondest #2A((2 3 4) (1 2 4) (2 4 5)))
310 ;; 6.8157451e7
311 ;;; CURRENTLY FAILS!!
313 (eigen #2A((2 3 4) (1 2 4) (2 4 5)))
314 ;; (#(10.656854249492381 -0.6568542494923802 -0.9999999999999996)
315 ;; (#(0.4999999999999998 0.4999999999999997 0.7071067811865475)
316 ;; #(-0.49999999999999856 -0.5000000000000011 0.7071067811865474)
317 ;; #(0.7071067811865483 -0.7071067811865466 -1.2560739669470215e-15))
318 ;; NIL)
320 (spline #(1.0 1.2 1.3 1.8 2.1 2.5)
321 #(1.2 2.0 2.1 2.0 1.1 2.8) :xvals 6)
322 ;; ((1.0 1.3 1.6 1.9 2.2 2.5)
323 ;; (1.2 2.1 2.2750696543866313 1.6465231041904045 1.2186576148879609 2.8))
325 ;;; using KERNEL-SMOOTH-FRONT, not KERNEL-SMOOTH-CPORT
326 (kernel-smooth #(1.0 1.2 1.3 1.8 2.1 2.5)
327 #(1.2 2.0 2.1 2.0 1.1 2.8) :xvals 5)
328 ;; ((1.0 1.375 1.75 2.125 2.5)
329 ;; (1.6603277642110226 1.9471748095239771 1.7938127405752287
330 ;; 1.5871511322219498 2.518194783156392))
332 (kernel-dens #(1.0 1.2 2.5 2.1 1.8 1.2) :xvals 5)
333 ;; ((1.0 1.375 1.75 2.125 2.5)
334 ;; (0.7224150453621405 0.5820045548233707 0.38216411702854214
335 ;; 0.4829822708587095 0.3485939156929503))
337 (fft #(1.0 1.2 2.5 2.1 1.8))
338 ;; #(#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))
340 (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))
341 ;; (#(1.0 1.2 1.2 1.8 2.1 2.5))
345 ;;;; Special functions
347 ;; Log-gamma function
349 (log-gamma 3.4) ;;1.0923280596789584
353 ;;;; Probability functions
355 ;; looking at these a bit more, perhaps a more CLOSy style is needed, i.e.
356 ;; (quantile :list-or-cons loc :type type (one of 'empirical 'normal 'cauchy, etc...))
357 ;; similar for the cdf, density, and rand.
358 ;; Probably worth figuring out how to add a new distribution
359 ;; efficiently, i.e. by keeping some kind of list.
361 ;; Normal distribution
363 (normal-quant 0.95) ;;1.6448536279366268
364 (normal-cdf 1.3) ;;0.9031995154143897
365 (normal-dens 1.3) ;;0.17136859204780736
366 (normal-rand 2) ;;(-0.40502015f0 -0.8091404f0)
368 (bivnorm-cdf 0.2 0.4 0.6) ;;0.4736873734160288
370 ;; Cauchy distribution
372 (cauchy-quant 0.95) ;;6.313751514675031
373 (cauchy-cdf 1.3) ;;0.7912855998398473
374 (cauchy-dens 1.3) ;;0.1183308127104695
375 (cauchy-rand 2) ;;(-1.06224644160405 -0.4524695943939537)
377 ;; Gamma distribution
379 (gamma-quant 0.95 4.3) ;;8.178692439291645
380 (gamma-cdf 1.3 4.3) ;;0.028895150986674906
381 (gamma-dens 1.3 4.3) ;;0.0731517686447374
382 (gamma-rand 2 4.3) ;;(2.454918912880936 4.081365384357454)
384 ;; Chi-square distribution
386 (chisq-quant 0.95 3) ;;7.814727903379012
387 (chisq-cdf 1 5) ;;0.03743422675631789
388 (chisq-dens 1 5) ;;0.08065690818083521
389 (chisq-rand 2 4) ;;(1.968535826180572 2.9988646156942997)
391 ;; Beta distribution
393 (beta-quant 0.95 3 2) ;;0.9023885371149876
394 (beta-cdf 0.4 2 2.4) ;;0.4247997418541529
395 (beta-dens 0.4 2 2.4) ;;1.5964741858913518
396 (beta-rand 2 2 2.4) ;;(0.8014897077282279 0.6516371997922659)
398 ;; t distribution
400 (t-quant 0.95 3) ;;2.35336343484194
401 (t-cdf 1 2.3) ;;0.794733624298342
402 (t-dens 1 2.3) ;;0.1978163816318102
403 (t-rand 2 2.3) ;;(-0.34303672776089306 -1.142505872436518)
405 ;; F distribution
407 (f-quant 0.95 3 5) ;;5.409451318117459
408 (f-cdf 1 3.2 5.4) ;;0.5347130905510765
409 (f-dens 1 3.2 5.4) ;;0.37551128864591415
410 (f-rand 2 3 2) ;;(0.7939093442091963 0.07442694152491144)
412 ;; Poisson distribution
414 (poisson-quant 0.95 3.2) ;;6
415 (poisson-cdf 1 3.2) ;;0.17120125672252395
416 (poisson-pmf 1 3.2) ;;0.13043905274097067
417 (poisson-rand 5 3.2) ;;(2 1 2 0 3)
419 ;; Binomial distribution
421 (binomial-quant 0.95 3 0.4) ;;; DOESN'T RETURN
422 (binomial-quant 0 3 0.4) ;;; -2147483648
423 (binomial-cdf 1 3 0.4) ;;0.6479999999965776
424 (binomial-pmf 1 3 0.4) ;;0.4320000000226171
425 (binomial-rand 5 3 0.4) ;;(2 2 0 1 2)
427 ;;;; OBJECT SYSTEM
429 (in-package :ls-user)
430 (defproto *test-proto*)
431 *test-proto*
432 (defmeth *test-proto* :make-data (&rest args) nil)
434 (defparameter my-proto-instance nil)
435 (setf my-proto-instance (send *test-proto* :new))
436 (send *test-proto* :own-slots)
437 (lsos::ls-object-slots *test-proto*)
438 (lsos::ls-object-methods *test-proto*)
439 (lsos::ls-object-parents *test-proto*)
440 (lsos::ls-object-preclist *test-proto*)
441 ;;; The following fail and I do not know why?
442 (send *test-proto* :has-slot 'proto-name)
443 (send *test-proto* :has-slot 'PROTO-NAME)
444 (send *test-proto* :has-slot 'make-data)
445 (send *test-proto* :has-slot 'MAKE-DATA)
446 (send *test-proto* :has-method 'make-data)
447 (send *test-proto* :has-method 'MAKE-DATA)
450 (defproto2 *test-proto3* (list) (list) (list) "test doc" t)
451 (defproto2 *test-proto4*)
452 *test-proto2*
453 (defmeth *test-proto* :make-data (&rest args) nil)
455 (defparameter my-proto-instance nil)
456 (setf my-proto-instance (send *test-proto* :new))
457 (send *test-proto* :own-slots)
458 (send *test-proto* :has-slot 'proto-name)
459 (send *test-proto* :has-slot 'PROTO-NAME)
462 ;;;; Testing
464 (in-package :lisp-stat-unittests)
465 (testsuites)
466 (print-tests)
467 (run-tests)
468 (last-test-status)
469 ;;(failures)
471 (describe (run-tests :suite 'lisp-stat-ut-testsupport))
472 (describe (run-tests :suite 'lisp-stat-ut-testsupport2))
474 (testsuite-tests 'lisp-stat-ut)
475 (run-tests :suite 'lisp-stat-ut)
476 (describe (run-tests :suite 'lisp-stat-ut))
478 (run-tests :suite 'lisp-stat-ut-probdistn)
479 (describe (run-tests :suite 'lisp-stat-ut-probdistn))
480 (run-tests :suite 'lisp-stat-ut-spec-fns)
481 (describe (run-tests :suite 'lisp-stat-ut-spec-fns))
483 (find-testsuite 'lisp-stat-ut-lin-alg)
484 (testsuite-tests 'lisp-stat-ut-lin-alg)
485 (run-tests :suite 'lisp-stat-ut-lin-alg)
486 (describe (run-tests :suite 'lisp-stat-ut-lin-alg))
488 ;;;; Data Analysis test
490 (in-package :ls-user)
492 ;; LispStat 1 approach to variables
494 (progn
495 (def iron (list 61 175 111 124 130 173 169 169 160 224 257 333 199))
496 iron
497 (def aluminum (list 13 21 24 23 64 38 33 61 39 71 112 88 54))
498 aluminum
499 (def absorbtion (list 4 18 14 18 26 26 21 30 28 36 65 62 40))
500 absorbtion
502 ;; LispStat 1 approach to data frames... (list of lists).
504 (DEF DIABETES
505 (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)
506 (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)
507 (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)
508 (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))))
511 (DEF DLABS (QUOTE ("GLUFAST" "GLUTEST" "INSTEST" "CCLASS")))
512 (format t "loaded data.~%")
513 ) ;; eval at this point.
515 ;; Simple univariate variable-specific descriptions.
516 (fivnum absorbtion)
517 (median absorbtion)
518 (sort-data absorbtion)
519 (rank absorbtion)
520 (standard-deviation absorbtion)
521 (interquartile-range absorbtion)
523 (lisp-stat-matrix::bind-columns aluminum iron)
524 (bind-columns aluminum iron)
525 (apply #'bind-columns (list aluminum iron))
526 (lisp-stat-matrix::bind-columns #2a((1 2)(3 4)) #(5 6))
527 (bind-columns #2a((1 2)(3 4)) #(5 6))
530 (defparameter fit1 nil)
531 (setf fit1 (regression-model absorbtion iron))
532 (send fit1 :display)
533 (send fit1 :residuals)
535 iron
536 (defparameter fit1a nil)
537 (setf fit1a (regression-model absorbtion iron :print nil))
538 (send fit1a :doc)
539 ;; (setf (send fit1a :doc) "this") ;; FIXME: this error...
540 (send fit1a :doc "this") ;; FIXME: this is a more natural
541 (send fit1a :doc)
542 (send fit1a :x)
543 (send fit1a :y)
544 (send fit1a :compute)
545 (send fit1a :sweep-matrix)
546 (send fit1a :basis)
547 (send fit1a :residuals)
548 (send fit1a :display)
550 #+nil(progn
551 ;; syntax example
552 (array-dimension #2A ((1)) 0)
555 ;;; FIXME: need to get multiple-linear regression working -- clearly
556 ;;; simple linear is working above!
557 (defvar m nil "holding variable.")
558 (def m (regression-model (list iron aluminum) absorbtion :print nil))
559 (send m :compute)
560 (send m :sweep-matrix)
561 (format t "~%~A~%" (send m :sweep-matrix))
563 ;; ERROR... FIX-ME!!
564 (send m :basis) ;; this should be positive?
565 (send m :coef-estimates)
567 (send m :display)
568 (def m (regression-model (bind-columns iron aluminum) absorbtion))
569 (send m :help)
570 (send m :help :display)
571 (send m :help :basis)
572 ;; No graphics! But handle the error gracefully...
573 (send m :plot-residuals)
576 (typep aluminum 'sequence)
577 (typep iron 'sequence)
578 (matrixp iron)
580 *variables*
582 (variables)
583 (undef 'iron)
584 (variables)
586 ;;; Plotting!
588 (asdf:oos 'asdf:compile-op 'cl-cairo2 :force t)
589 (asdf:oos 'asdf:load-op 'cl-cairo2)
591 ;; The above can be used to generate PDF, PS, PNG, and X11/Microsoft
592 ;; displays (the latter being a proof of concept, of limited use for
593 ;; "real work".
595 ;; and this below, as well.
596 (asdf:oos 'asdf:load-op 'cl-plplot)
598 ;;; Using R!
600 (asdf:oos 'asdf:compile-op 'rclg :force t)
601 (asdf:oos 'asdf:load-op 'rclg)
604 (in-package :rclg-user)
606 ;; rclg-init::*r-started*
608 ;;;#3 Start R within Lisp
610 (start-rclg)
611 ;; rclg-init::*r-started*
612 (rclg-init::check-stack)
613 (r "Cstack_info")
614 (defparameter *x* (r seq 1 11))
615 (defparameter *y* (r rnorm 10))
617 (r plot *x* *y*)
620 (defparameter *r-version* (r "version"))
622 ;; This is for illustrative purposes only. It is not a "good" use of rnbi.
623 ;; Really, you'll want rnbi to hold anonymous intermeditae results, like:
624 (r plot *x* (rnbi rnorm 10))
626 (r "Sys.getenv" "LD_LIBRARY_PATH")
627 (r "Sys.getenv" "LD_PRELOAD")
629 (r "ls")
630 (r ls)
631 (r "search")
633 (r "geterrmessage")
635 (r "library" "stats")
636 (r library "MASS")
637 (r "library" "Biobase")
639 (setf my.lib "Biobase")
640 my.lib
641 (r library my.lib)
643 (r "ls")
645 (r "print.default" 3)
646 (r "rnorm" 10)
648 ;; Working in the R space
650 (r assign "x" 5)
651 (r assign "x2" (list 1 2 3 5))
653 (r assign "x2" #(1 2 3 5 3 4 5))
654 (r assign "z" "y") ;; unlike the above, this assigns character data
655 (r "ls")
656 (r ls)
658 (setf my.r.x2 (r get "x2")) ;; moving data from R to CL
659 (r assign "x2" my.r.x2) ;; moving data from CL to R
661 ;; The following is not the smartest thing to do!
662 ;;(r q)
666 ;;; How might we do statistics with Common Lisp?
667 ;;; How might we work with a data.frame?
668 ;;; What could the structures be?
669 ;;; How much hinting, and of what type, should drive the data
670 ;;; analysis?
672 (defpackage :my-data-analysis-example
673 (:documentation "Example work-package for a data analysis")
674 (:use :common-lisp :lisp-stat)
675 (:export results figures report))
677 (in-package :my-data-analysis-example)
679 (defvar my-dataset1 (read-file "data/test1.lisp"))
680 ;; or
681 (defvar my-dataset2 (read-file "data/test1.csv" :type 'csv))
683 ;;; manipulate
685 (setf my-dataset2 (set-description my-datasets2
686 :dependent-variables (list of symbols)))
687 (setf my-dataset2 (set-description my-datasets2
688 :independent-variables (list of symbols)))
690 ;; the following could be true in many cases.
691 (assert
692 (list-intersection (get-description my-datasets2 :independent-variables)
693 (get-description my-datasets2 :dependent-variables)))
695 ;; but we could phrase better,i.e.
697 (get-description
698 my-datasets2
699 :predicate-list-on-variable-metadata (list (and 'independent-variables
700 'dependent-variables)))
703 ;; statistical relations re: input/output, as done above, is one
704 ;; issue, another one is getting the right approach for statistical
705 ;; typing, i.e.
706 (get-description
707 my-datasets2
708 :predicate-list-on-variable-metadata (list 'ordinal-variables))
711 ;; so we could use a set of logical ops to selection from variable
712 ;; metadata, i.e.
713 ;; and, or, not
714 ;; do we really need the simplifying extensions?
717 ;;; output to REPL
719 (report my-dataset1 :style 'five-num)
720 (report my-dataset1 :style 'univariate)
721 (report my-dataset1 :style 'bivariate)
722 (report my-dataset1 :style 'metadata)
724 ;;; to file?
726 (report my-dataset1
727 :style 'five-num
728 :format 'pdf
729 :stream (filename-as-stream "my-dataset1-5num.pdf"))
730 (report my-dataset1 :style 'univariate)
731 (report my-dataset1 :style 'bivariate)
732 (report my-dataset1 :style 'metadata)
734 ;;; so report could handle datasets... and models?
736 (report my-model :style 'formula)
737 (report my-model :style 'simulate
738 (list :parameters (:eta 5 :mu 4 :sigma (list 2 1 0.5))
739 :number-of-reps 10))
740 ;; should return a list of parameters along with range information,
741 ;; useful for auto-building the above. Note that there are 3 types
742 ;; of parameters that can be considered -- we can have values which
743 ;; define ddata, we can have values which define fixed values and some
744 ;; could be things tht we estimate.
747 (defgeneric report (object &optional style format stream)
748 (:documentation "method for reporting on data"))
750 (defmethod report ((object dataset)
751 (style report-dataset-style-type)
752 (format output-format-type)
753 ((stream *repl*) output-stream-type))
754 "dataset reporting")
757 (defmethod report ((object model)
758 (style report-model-style-type)
759 (format output-format-type)
760 ((stream *repl*) output-stream-type))
761 "model reporting")
763 (defmethod report ((object analysis-instance)
764 (style report-analysis-style-type)
765 (format output-format-type)
766 ((stream *repl*) output-stream-type))
767 "model + dataset reporting")
770 ;; parameters are just things which get filled with values, repeatedly
771 ;; with data, or by considering to need estimation.
772 (parameters my-model)
773 (parameters my-model :type 'data)
774 (parameters my-model :type 'fixed)
775 (parameters my-model :type 'estimate)
776 (parameters my-model :type '(estimate fixed))
777 (parameters my-model :list-types) ;; useful for list-based extraction
778 ;; of particular types
780 (setf my-model-data-instance
781 (compute model data :specification (list :spec 'linear-model
782 :depvar y
783 :indepvar (list x1 x2))))
784 (report my-model-data-instance)
787 ;;; So how might we use this? Probably need to consider the
788 ;;; serialization of any lisp objects generated, perhaps via some form
789 ;;; of memoization...?
790 (in-package :cl-user)
792 (my-data-analysis-example:report :type 'full)
793 (my-data-analysis-example:report :type 'summary)
794 (my-data-analysis-example:figures :type 'pdf :file "results-figs.pdf")
796 (my-data-analysis-example:report)
798 ;;; more stuff
800 (send m :display)
801 (def m (regression-model (bind-columns iron aluminum) absorbtion))
802 (send m :help)
803 (send m :help :display)
804 (send m :help :basis)
806 (send m :plot-residuals)
808 (progn
809 ;; General Lisp, there is also a need to add, remove symbols from the
810 ;; workspace/namespace. This is a fundamental skill, similar to
811 ;; stopping, which is critical.
813 ;; boundp, fboundp
814 ;; makunbound, fmakunbound
818 (progn
819 ;;; A study in array vs list access
820 (defparameter *x* (list 1 2 3))
821 (defparameter *y* #(1 2 3))
822 (defparameter *z* (list 1 (list 2 3) (list 4 5 (list 6 7)) ))
823 (length *x*)
824 (length *y*)
825 (length *z*) ; => need a means to make this 7.
826 (length (reduce #'cons *z*)) ; => not quite -- missing iterative
828 (nelts *x*)
829 (nth 1 *x*)
830 (aref *y* 1)
831 (setf (nth 1 *x*) 6)
833 (setf (aref *y* 1) 6)
837 (in-package :ls-user)
839 (progn
840 (defparameter *x* (make-vector 5 :initial-contents '((1d0 2d0 3d0 4d0 5d0))))
841 ;; estimating a mean, simple way.
842 (/ (loop for i from 0 to (- (nelts *x*) 1)
843 summing (vref *x* i))
844 (nelts *x*))
846 (defun mean (x)
847 (checktype x 'vector-like)
848 (/ (loop for i from 0 to (- (nelts *x*) 1)
849 summing (vref *x* i))
850 (nelts *x*)))
852 ;; estimating variance, Moments
853 (let ((meanx (mean *x*))
854 (n (nelts *x*)))
855 (/ (loop for i from 0 to (1- n)
856 summing (* (- (vref *x* i) meanx)
857 (- (vref *x* i) meanx)))
860 ;; estimating variance, Moments
861 (let ((meanx (mean *x*))
862 (nm1 (1- (nelts *x*))))
863 (/ (loop for i from 0 to nm1
864 summing (* (- (vref *x* i) meanx)
865 (- (vref *x* i) meanx) ))
866 nm1))
870 ;;;;;;;;;;;;;;; Data stuff
872 (progn ;; Data setup
874 ;; Making data-frames (i.e. cases (rows) by variables (columns))
875 ;; takes a bit of getting used to. For this, it is important to
876 ;; realize that we can do the following:
877 ;; #1 - consider the possibility of having a row, and transposing
878 ;; it, so the list-of-lists is: ((1 2 3 4 5)) (1 row, 5 columns)
879 ;; #2 - naturally list-of-lists: ((1)(2)(3)(4)(5)) (5 rows, 1 column)
880 ;; see src/data/listoflist.lisp for code to process this particular
881 ;; data structure.
882 (defparameter *indep-vars-1-matrix*
883 (transpose (make-matrix 1 (length iron)
884 :initial-contents
885 (list (mapcar #'(lambda (x) (coerce x 'double-float))
886 iron))))
887 "creating iron into double float, straightforward")
889 (documentation '*indep-vars-1-matrix* 'variable)
890 ;; *indep-vars-1-matrix*
892 ;; or directly:
893 (defparameter *indep-vars-1a-matrix*
894 (make-matrix (length iron) 1
895 :initial-contents
896 (mapcar #'(lambda (x) (list (coerce x 'double-float)))
897 iron)))
898 ;; *indep-vars-1a-matrix*
900 ;; and mathematically, they seem equal:
901 (m= *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => T
902 ;; but of course not completely...
903 (eql *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => NIL
904 (eq *indep-vars-1-matrix* *indep-vars-1a-matrix*) ; => NIL
906 ;; and verify...
907 (print *indep-vars-1-matrix*)
908 (print *indep-vars-1a-matrix*)
910 (documentation 'lisp-matrix:bind2 'function) ; by which we mean:
911 (documentation 'bind2 'function)
912 (bind2 *indep-vars-1-matrix* *indep-vars-1a-matrix* :by :column) ; 2 col
913 (bind2 *indep-vars-1-matrix* *indep-vars-1a-matrix* :by :row) ; 1 long col
915 ;; the weird way
916 (defparameter *indep-vars-2-matrix*
917 (transpose (make-matrix 2 (length iron)
918 :initial-contents
919 (list
920 (mapcar #'(lambda (x) (coerce x 'double-float))
921 iron)
922 (mapcar #'(lambda (x) (coerce x 'double-float))
923 aluminum)))))
924 ;; *indep-vars-2-matrix*
926 ;; the "right"? way
927 (defparameter *indep-vars-2-matrix*
928 (make-matrix (length iron) 2
929 :initial-contents
930 (mapcar #'(lambda (x y)
931 (list (coerce x 'double-float)
932 (coerce y 'double-float)))
933 iron aluminum)))
934 ;; *indep-vars-2-matrix*
937 ;; The below FAILS due to coercion issues; it just isn't lispy, it's R'y.
939 (defparameter *dep-var* (make-vector (length absorbtion)
940 :initial-contents (list absorbtion)))
942 ;; BUT below, this should be the right type.
943 (defparameter *dep-var*
944 (make-vector (length absorbtion)
945 :type :row
946 :initial-contents
947 (list
948 (mapcar #'(lambda (x) (coerce x 'double-float))
949 absorbtion))))
950 ;; *dep-var*
953 (defparameter *dep-var-int*
954 (make-vector (length absorbtion)
955 :type :row
956 :element-type 'integer
957 :initial-contents (list absorbtion)))
959 (typep *dep-var* 'matrix-like) ; => T
960 (typep *dep-var* 'vector-like) ; => T
962 (typep *indep-vars-1-matrix* 'matrix-like) ; => T
963 (typep *indep-vars-1-matrix* 'vector-like) ; => T
964 (typep *indep-vars-2-matrix* 'matrix-like) ; => T
965 (typep *indep-vars-2-matrix* 'vector-like) ; => F
967 iron
968 ;; following fails, need to ensure that we work on list elts, not just
969 ;; elts within a list:
971 ;; (coerce iron 'real)
973 ;; the following is a general list-conversion coercion approach -- is
974 ;; there a more efficient way?
975 ;; (coerce 1 'real)
976 ;; (mapcar #'(lambda (x) (coerce x 'double-float)) iron)
978 (princ "Data Set up"))
983 (progn ;; Data setup
985 (describe 'make-matrix)
987 (defparameter *indep-vars-2-matrix*
988 (make-matrix (length iron) 2
989 :initial-contents
990 (mapcar #'(lambda (x y)
991 (list (coerce x 'double-float)
992 (coerce y 'double-float)))
993 iron aluminum)))
996 (defparameter *dep-var*
997 (make-vector (length absorbtion)
998 :type :row
999 :initial-contents
1000 (list
1001 (mapcar #'(lambda (x) (coerce x 'double-float))
1002 absorbtion))))
1004 (make-dataframe *dep-var*)
1005 (make-dataframe (transpose *dep-var*))
1007 (defparameter *dep-var-int*
1008 (make-vector (length absorbtion)
1009 :type :row
1010 :element-type 'integer
1011 :initial-contents (list absorbtion)))
1014 (defparameter *xv+1a*
1015 (make-matrix
1017 :initial-contents #2A((1d0 1d0)
1018 (1d0 3d0)
1019 (1d0 2d0)
1020 (1d0 4d0)
1021 (1d0 3d0)
1022 (1d0 5d0)
1023 (1d0 4d0)
1024 (1d0 6d0))))
1026 (defparameter *xv+1b*
1027 (bind2
1028 (ones 8 1)
1029 (make-matrix
1031 :initial-contents '((1d0)
1032 (3d0)
1033 (2d0)
1034 (4d0)
1035 (3d0)
1036 (5d0)
1037 (4d0)
1038 (6d0)))
1039 :by :column))
1041 (m= *xv+1a* *xv+1b*) ; => T
1043 (princ "Data Set up"))
1047 ;;;; LM
1049 (progn
1051 (defparameter *y*
1052 (make-vector
1054 :type :row
1055 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
1058 (defparameter *xv+1*
1059 (make-matrix
1061 :initial-contents '((1d0 1d0)
1062 (1d0 3d0)
1063 (1d0 2d0)
1064 (1d0 4d0)
1065 (1d0 3d0)
1066 (1d0 5d0)
1067 (1d0 4d0)
1068 (1d0 6d0))))
1071 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
1072 (defparameter *xtx-2* (m* (transpose *xv+1*) *xv+1*))
1073 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
1074 ;; 8.0d0 28.0d0
1075 ;; 28.0d0 116.0d0>
1077 (defparameter *xty-2* (m* (transpose *xv+1*) (transpose *y*)))
1078 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
1079 ;; 36.0d0
1080 ;; 150.0d0>
1082 (defparameter *rcond-2* 0.000001)
1083 (defparameter *betahat-2* (gelsy *xtx-2* *xty-2* *rcond-2*))
1084 ;; *xtx-2* => "details of complete orthogonal factorization"
1085 ;; according to man page:
1086 ;; #<LA-SIMPLE-MATRIX-DOUBLE 2 x 2
1087 ;; -119.33147112141039d0 -29.095426104883202d0
1088 ;; 0.7873402682880205d0 -1.20672274167718d0>
1090 ;; *xty-2* => output becomes solution:
1091 ;; #<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
1092 ;; -0.16666666666668312d0
1093 ;; 1.333333333333337d0>
1095 *betahat-2* ; which matches R, see below
1097 (documentation 'gelsy 'function)
1100 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (2 x 1)
1101 ;; -0.16666666666668312 1.333333333333337>
1102 ;; 2)
1104 ;; ## Test case in R:
1105 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
1106 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
1107 ;; lm(y~x)
1108 ;; ## => Call: lm(formula = y ~ x)
1110 ;; Coefficients: (Intercept) x
1111 ;; -0.1667 1.3333
1113 ;; summary(lm(y~x))
1114 ;; ## =>
1116 ;; Call:
1117 ;; lm(formula = y ~ x)
1119 ;; Residuals:
1120 ;; Min 1Q Median 3Q Max
1121 ;; -1.833e+00 -6.667e-01 -3.886e-16 6.667e-01 1.833e+00
1123 ;; Coefficients:
1124 ;; Estimate Std. Error t value Pr(>|t|)
1125 ;; (Intercept) -0.1667 1.1587 -0.144 0.89034
1126 ;; x 1.3333 0.3043 4.382 0.00466 **
1127 ;; ---
1128 ;; Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
1130 ;; Residual standard error: 1.291 on 6 degrees of freedom
1131 ;; Multiple R-squared: 0.7619, Adjusted R-squared: 0.7222
1132 ;; F-statistic: 19.2 on 1 and 6 DF, p-value: 0.004659
1136 ;; which suggests one might do (modulo ensuring correct
1137 ;; orientations). When this is finalized, it should migrate to
1138 ;; CLS.
1142 (defparameter *n* 20) ; # rows = # obsns
1143 (defparameter *p* 10) ; # cols = # vars
1144 (defparameter *x-temp* (rand *n* *p*))
1145 (defparameter *b-temp* (rand *p* 1))
1146 (defparameter *y-temp* (m* *x-temp* *b-temp*))
1147 ;; so Y=Xb + \eps
1148 (defparameter *rcond* (* (coerce (expt 2 -52) 'double-float)
1149 (max (nrows *x-temp*) (ncols *y-temp*))))
1150 (defparameter *orig-x* (copy *x-temp*))
1151 (defparameter *orig-b* (copy *b-temp*))
1152 (defparameter *orig-y* (copy *y-temp*))
1154 (defparameter *lm-result* (lm *x-temp* *y-temp*))
1155 (princ (first *lm-result*))
1156 (princ (second *lm-result*))
1157 (princ (third *lm-result*))
1158 (v= (third *lm-result*)
1159 (v- (first (first *lm-result*))
1160 (first (second *lm-result*))))
1165 ;; Some issues exist in the LAPACK vs. LINPACK variants, hence R
1166 ;; uses LINPACK primarily, rather than LAPACK. See comments in R
1167 ;; source for issues.
1170 ;; Goal is to start from X, Y and then realize that if
1171 ;; Y = X \beta, then, i.e. 8x1 = 8xp px1 + 8x1
1172 ;; XtX \hat\beta = Xt Y
1173 ;; so that we can solve the equation W \beta = Z where W and Z
1174 ;; are known, to estimate \beta.
1176 ;; the above is known to be numerically instable -- some processing
1177 ;; of X is preferred and should be done prior. And most of the
1178 ;; transformation-based work does precisely that.
1180 ;; recall: Var[Y] = E[(Y - E[Y])(Y-E[Y])t]
1181 ;; = E[Y Yt] - 2 \mu \mut + \mu \mut
1182 ;; = E[Y Yt] - \mu \mut
1184 ;; Var Y = E[Y^2] - \mu^2
1187 ;; For initial estimates of covariance of \hat\beta:
1189 ;; \hat\beta = (Xt X)^-1 Xt Y
1190 ;; with E[ \hat\beta ]
1191 ;; = E[ (Xt X)^-1 Xt Y ]
1192 ;; = E[(Xt X)^-1 Xt (X\beta)]
1193 ;; = \beta
1195 ;; So Var[\hat\beta] = ...
1196 ;; (Xt X)
1197 ;; and this gives SE(\beta_i) = (* (sqrt (mref Var i i)) adjustment)
1200 ;; from docs:
1202 (setf *temp-result*
1203 (let ((*default-implementation* :foreign-array))
1204 (let* ((m 10)
1205 (n 10)
1206 (a (rand m n))
1207 (x (rand n 1))
1208 (b (m* a x))
1209 (rcond (* (coerce (expt 2 -52) 'double-float)
1210 (max (nrows a) (ncols a))))
1211 (orig-a (copy a))
1212 (orig-b (copy b))
1213 (orig-x (copy x)))
1214 (list x (gelsy a b rcond))
1215 ;; no applicable conversion?
1216 ;; (m- (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1))
1217 ;; (#<FA-SIMPLE-VECTOR-DOUBLE (10 x 1)) )
1218 (v- x (first (gelsy a b rcond))))))
1221 (princ *temp-result*)
1223 (setf *temp-result*
1224 (let ((*default-implementation* :lisp-array))
1225 (let* ((m 10)
1226 (n 10)
1227 (a (rand m n))
1228 (x (rand n 1))
1229 (b (m* a x))
1230 (rcond (* (coerce (expt 2 -52) 'double-float)
1231 (max (nrows a) (ncols a))))
1232 (orig-a (copy a))
1233 (orig-b (copy b))
1234 (orig-x (copy x)))
1235 (list x (gelsy a b rcond))
1236 (m- x (first (gelsy a b rcond)))
1238 (princ *temp-result*)
1241 (defparameter *xv*
1242 (make-vector
1244 :type :row ;; default, not usually needed!
1245 :initial-contents '((1d0 3d0 2d0 4d0 3d0 5d0 4d0 6d0))))
1247 (defparameter *y*
1248 (make-vector
1250 :type :row
1251 :initial-contents '((1d0 2d0 3d0 4d0 5d0 6d0 7d0 8d0))))
1253 ;; so something like (NOTE: matrices are transposed to begin with, hence the incongruety)
1254 (defparameter *xtx-1* (m* *xv* (transpose *xv*)))
1255 (defparameter *xty-1* (m* *xv* (transpose *y*)))
1256 (defparameter *rcond-in* (* (coerce (expt 2 -52) 'double-float)
1257 (max (nrows *xtx-1*)
1258 (ncols *xty-1*))))
1260 (defparameter *betahat* (gelsy *xtx-1* *xty-1* *rcond-in*))
1262 ;; (#<LA-SIMPLE-VECTOR-DOUBLE (1 x 1)
1263 ;; 1.293103448275862>
1264 ;; 1)
1266 ;; ## Test case in R:
1267 ;; x <- c( 1.0, 3.0, 2.0, 4.0, 3.0, 5.0, 4.0, 6.0)
1268 ;; y <- c( 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0)
1269 ;; lm(y~x-1)
1270 ;; ## =>
1271 ;; Call:
1272 ;; lm(formula = y ~ x - 1)
1274 ;; Coefficients:
1275 ;; x
1276 ;; 1.293
1278 (first *betahat*))
1283 (type-of #2A((1 2 3 4 5)
1284 (10 20 30 40 50)))
1286 (type-of (rand 10 20))
1288 (typep #2A((1 2 3 4 5)
1289 (10 20 30 40 50))
1290 'matrix-like)
1292 (typep (rand 10 20) 'matrix-like)
1294 (typep #2A((1 2 3 4 5)
1295 (10 20 30 40 50))
1296 'array)
1298 (typep (rand 10 20) 'array)