use index1 / index2, etc, not X/Y or COL/ROW to denote indices.
[CommonLispStat.git] / data-clos.lisp
blob0143c7251f8b01746ae41ade1d8be8e15402190c
1 ;;; -*- mode: lisp -*-
3 ;;; File: data-clos.lisp
4 ;;; Author: AJ Rossini <blindglobe@gmail.com>
5 ;;; Copyright: (c)2008, AJ Rossini. BSD, LLGPL, or GPLv2, depending
6 ;;; on how it arrives.
7 ;;; Purpose: data package for lispstat
8 ;;; Time-stamp: <2008-03-12 17:18:42 user>
9 ;;; Creation: <2008-03-12 17:18:42 user>
11 ;;; What is this talk of 'release'? Klingons do not make software
12 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
13 ;;; designers and quality assurance people in its wake.
15 ;;; This organization and structure is new to the 21st Century
16 ;;; version.
18 ;;; data-clos.lisp
19 ;;;
20 ;;; redoing data structures in a CLOS based framework.
21 ;;;
22 ;;; No real basis for work, there is a bit of new-ness and R-ness to
23 ;;; this work. In particular, the notion of relation is key and
24 ;;; integral to the analysis. Tables are related and matched
25 ;;; vectors,for example. "column" vectors are related observations
26 ;;; (by measure/recording) while "row" vectors are related readings
27 ;;; (by case)
28 ;;;
30 ;;; Relational structure -- can we capture a completely unnormalized
31 ;;; data strucutre to propose possible modeling approaches, and
32 ;;; propose appropriate models and inferential strategies?
33 ;;;
35 ;; verb-driven schema for data collection. Should encode independence
36 ;; or lack of when possible.
38 #+nil(progn
39 (def-statschema MyDB
40 :tables (list (list t1 )
41 (list t2 )
42 (list t4 ))
43 :unique-key key
44 :stat-relation '(t1 (:nest-within t2) (:nest-within t3))
45 :))
49 (in-package :cl-user)
51 (defpackage :lisp-stat-data-clos
52 (:use :common-lisp
53 ;;:clem
55 (:export statistical-dataset ;; primary class for working.
57 modifyData ;; metadata mods
58 importData ;; get it in
59 reshapeData ;; data mods
61 consistent-statistical-dataset-p
62 varNames caseNames ;; metadata explicit modifiers
64 extract
65 ;; and later, we remove the following, exposing only
66 ;; through the above method.
67 extract-1 extract-row extract-col extract-idx
70 (in-package :lisp-stat-data-clos)
72 ;; Need to figure out typed vectors. We then map a series of typed
73 ;; vectors over to tables where columns are equal typed. In a sense,
74 ;; this is a relation (1-1) of equal-typed arrays. For the most part,
75 ;; this ends up making the R data.frame into a relational building
76 ;; block (considering 1-1 mappings using row ID as a relation).
77 ;; Is this a worthwhile generalization?
79 (defclass statistical-dataset ()
80 ((store :initform nil
81 :initarg :storage
82 :accessor dataset
83 :documentation "Data storage slot. Should be an array or a
84 relation,")
85 (documentation-string :initform nil
86 :initarg :doc
87 :accessor doc-string
88 :documentation "Information about statistical-dataset.")
89 (case-labels :initform nil
90 :initarg :case-labels
91 :accessor case-labels
92 :documentation "labels used for describing cases (doc
93 metadata), possibly used for merging.")
94 (var-labels :initform nil
95 :initarg :var-labels
96 :accessor var-labels
97 :documentation "Variable names."))
98 (:documentation "Standard Cases by Variables Statistical-Dataset."))
101 ;; statistical-dataset is the basic cases by variables framework.
102 ;; Need to embed this within other structures which allow for
103 ;; generalized relations. Goal is to ensure that relations imply and
104 ;; drive the potential for statistical relativeness such as
105 ;; correlation, interference, and similar concepts.
107 ;; Actions on a statistical data structure.
110 (defgeneric consistent-statistical-dataset-p (ds)
111 (:documentation "methods to check for consistency."))
113 (defmethod consistent-statistical-dataset-p ((ds statistical-dataset))
114 "Test that statistical-dataset is internally consistent with metadata.
115 Ensure that dims of stored data are same as case and var labels."
116 (equal (array-dimensions (dataset ds))
117 (list (length (var-labels ds))
118 (length (case-labels ds)))))
120 ;;; Extraction
122 (defun extract-1 (sds idx1 idx2)
123 "Returns a scalar."
124 (aref (dataset sds) idx1 idx2))
126 (defun extract-1-as-sds (sds idx1 idx2)
127 "Need a version which returns a dataset."
128 (make-instance 'statistical-dataset
129 :storage #2A((extract-1 sds idx1 idx2))
130 ;; ensure copy for this and following
131 :doc (doc-string sds)
132 :case-labels (caseNames sds)
133 :var-labels (varNames sds)))
135 (defun gen-seq (n &optional (start 1))
136 "There has to be a better way -- I'm sure of it! Always count from 1."
137 (if (>= n start)
138 (append (gen-seq (- n 1) start) (list n))))
139 ;; (gen-seq 4)
140 ;; => (1 2 3 4)
141 ;; (gen-seq 0)
142 ;; => nil
143 ;; (gen-seq 5 3)
144 ;; => 3 4 5
147 (defun extract-col (sds index)
148 "Returns data as sequence."
149 (map 'sequence
150 #'(lambda (x) (extract-1 sds index x))
151 (gen-seq (nth 2 (array-dimensions (dataset sds))))))
153 (defun extract-col-as-sds (sds index)
154 "Returns data as SDS, copied."
155 (map 'sequence
156 #'(lambda (x) (extract-1 sds index x))
157 (gen-seq (nth 2 (array-dimensions (dataset sds))))))
159 (defun extract-row (sds index)
160 "Returns row as sequence."
161 (map 'sequence
162 #'(lambda (x) (extract-1 sds x index))
163 (gen-seq (nth 1 (array-dimensions (dataset sds))))))
165 (defun extract-idx (sds idx1Lst idx2Lst)
166 "return an array, row X col dims."
167 (let ((my-pre-array (list)))
168 (dolist (x idx1Lst)
169 (dolist (y idx2Lst)
170 (append my-pre-array (extract-1 sds x y))))
171 (make-array (list (length idx1Lst idx2Lst))
172 :store my-pre-array)))
175 (defun extract-idx-sds (sds idx1Lst idx2Lst)
176 "return a dataset encapsulated version of extract-idx."
177 (make-instance 'statistical-dataset
178 :storage #2A((extract-idx sds idx1Lst idx2Lst))
179 ;; ensure copy for this and following
180 :doc (doc-string sds)
181 :case-labels (caseNames sds)
182 :var-labels (varNames sds)))
184 (defgeneric extract (sds whatAndRange)
185 (:documentation "data extraction approach"))
187 ;;; Printing methods and support.
189 (defun print-structure-table (ds)
190 "example of what we want the methods to look like. Should be sort
191 of like a spreadsheet if the storage is a table."
192 (print-as-row (var-labels ds))
193 (let ((j -1))
194 (dolist (i (case-labels ds))
195 (princ (format "%i %v" i (extract-row (dataset ds) (incr j)))))))
197 (defun print-structure-relational (ds)
198 "example of what we want the methods to look like. Should be sort
199 of like a graph of spreadsheets if the storage is a relational
200 structure."
201 (dolist (k (relations ds))
202 (print-as-row (var-labels ds))
203 (let ((j -1))
204 (dolist (i (case-labels ds))
205 (princ "%i %v" i (extract-row (dataset ds) (incr j)))))))
210 (defgeneric reshapeData (dataform into-form as-copy)
211 (:documentation "pulling data into a new form"))
213 (defmethod reshapeData ((ds statistical-dataset) what into-form)
214 (reshape (get ds what) into-form))
216 (defmethod reshapeData ((ds array) (sp list) copy-p)
217 "Array via specList specialization: similar to the common R
218 approaches to redistribution."
219 (let ((widep (getf sp :toWide))
220 (primaryKey (getf sp :primaryKey)))
224 (defclass data-format () ())
226 (defun transpose (x)
227 "map NxM to MxN.")
229 (defun reorder-by-rank (x order &key (by-row t))
230 " .")
232 (defun reorder-by-permutation (x perm &key (by-row t))
233 " .")
235 ;;; verbs vs semantics for dt conversion -- consider the possibily of
236 ;;; how adverbs and verbs relate, where to put which semantically to
237 ;;; allow for general approach.
239 ;;; eg. Kasper's talk on the FUSION collection of parsers.
253 ;;; Need to consider modification APIs
254 ;;; actions are:
255 ;;; - import
256 ;;; - get/set row names (case names)
257 ;;; - column names (variable names)
258 ;;; - dataset values
259 ;;; - annotation/metadata
260 ;;; - make sure that we do coherency checking in the exported
261 ;;; - functions.
262 ;;; - ...
263 ;;; - reshapeData/reformat/reshapr a reformed version of the dataset (no
264 ;;; additional input).
265 ;;; - either overwriting or not, i.e. with or without copy.
266 ;;; - check consistency of resulting data with metadata and related
267 ;;; data information.
268 ;;; -
270 ;;; Variable-name handling for Tables. Needs error checking.
271 (defun varNames (ds)
272 (var-labels ds))
274 (defun set-varNames (ds vN)
275 (if (= (length (var-labels ds))
276 (length vN))
277 (setf (var-labels ds) vN)
278 (error "wrong size.")))
280 (defsetf varNames set-varNames)
282 ;;; Case-name handling for Tables. Needs error checking.
283 (defun caseNames (ds)
284 (case-labels ds))
286 (defun set-caseNames (ds vN)
287 (if (= (length (case-labels ds))
288 (length vN))
289 (setf (case-labels ds) vN)
290 (error "wrong size.")))
292 (defsetf caseNames set-caseNames)
294 ;;; General modification approaches.
296 (defgeneric importData (source featureList)
297 (:documentation "command to get data into CLS. Specific methods
298 will need to handle files, internal data structures, and DBMS's. We
299 would like to be able to do:
306 (defun pathname-example (name)
307 (let ((my-path (parse-namestring name)))
308 (values (pathname-name my-path :case :common)
309 (pathname-name my-path :case :local))))
311 (defvar sourceTypes (list 'csv 'lisp 'tsv 'special)
312 "list of possible symbols used to specify source formats that might
313 be supported for input. CSV and TSV are standard, LISP refers to
314 forms, and SPECIAL refers to a FUNCTION which parses as
315 appropriately.")
317 ;;; WRONG LOGIC.
318 (defmethod importData ((fileHandle pathname)
319 (fmt list)) ;sourceTypes))
320 "File-based input for data.
321 Usually used by:
322 (importData (parse-namestring 'path/to/file')
323 (list :format 'csv))
325 (importData myPathName (list :format 'lisp))
327 (let* ((fmtType (getf fmt :format))
328 (newData (getDataAsLists fileHandle fmtType)))
329 (case fmtType
330 ('csv ( ))
331 ('tsv ( ))
332 ('lisp ( ))
333 ('special (let ((parserFcn (getf fmt :special-parser)))))
334 (:default (error "no standard default importData format")))))
336 (defmethod importData ((ds array) (fmt list))
337 "mapping arrays into CLS data.")
340 (defmethod importData ((dsSpec DBMSandSQLextract)
341 (fmt mappingTypes))
342 "mapping DBMS into CLS data.")
346 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
347 ;;; EXPERIMENT
348 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
350 (in-package :cl-user)
352 ;; if needed, but need to set the ASDf path first...!
353 ;; (asdf:oos 'asdf:load-op :lift)
355 (defpackage :lisp-stat-data-clos-example
356 (:use :common-lisp
357 :lift :lisp-stat-unittests
358 :lisp-stat-data-clos))
360 (in-package :lisp-stat-data-clos-example)
364 ;;; Use of this package: To see what gets exported for use in others,
365 ;;; and how much corruption can be done to objects within a package.
369 (deftestsuite lisp-stat-dataclos () ()) ;;(lisp-stat) ())
371 (addtest (lisp-stat-dataclos) equaltestnameData
372 (ensure-error
373 (eql (dataset (list 'a 'b 'c 'd) :form (list 2 2))
374 #2A(('a 'b) ('c 'd)))))
376 (defvar my-ds-1 nil
377 "test ds for experiment.")
378 (setf my-ds-1 (make-instance 'statistical-dataset))
379 my-ds-1
382 (defvar my-ds-2 nil
383 "test ds for experiment.")
384 (setf my-ds-2 (make-instance 'statistical-dataset
385 :storage #2A((1 2 3 4 5) (10 20 30 40 50))
386 :doc "This is an interesting statistical-dataset"
387 :case-labels (list "a" "b" "c" "d" "e")
388 :var-labels (list "x" "y")))
389 my-ds-2
390 (make-array (list 3 5))
392 (array-dimensions (lisp-stat-data-clos::dataset my-ds-2))
395 (addtest (lisp-stat-dataclos) consData
396 (ensure
397 (consistent-statistical-dataset-p my-ds-2)))
399 (addtest (lisp-stat-dataclos) badAccess1
400 (ensure-error
401 (slot-value my-ds-2 'store)))
403 (addtest (lisp-stat-dataclos) badAccess2
404 (ensure-error
405 (slot-value my-ds-2 'store)))
407 (addtest (lisp-stat-dataclos) badAccess3
408 (ensure-error
409 (dataset my-ds-2)))
411 (addtest (lisp-stat-dataclos) badAccess4
412 (ensure
413 (equal
414 (slot-value my-ds-2 'lisp-stat-data-clos::store)
415 (lisp-stat-data-clos::dataset my-ds-2))))
418 (addtest (lisp-stat-dataclos) badAccess5
419 (ensure
420 (eq (lisp-stat-data-clos::dataset my-ds-2)
421 (slot-value my-ds-2 'lisp-stat-data-clos::store))))
424 ;; NEVER DO THE FOLLOWING, UNLESS YOU WANT TO MUCK UP STRUCTURES...
425 (addtest (lisp-stat-dataclos) badAccess6
426 (ensure
427 (lisp-stat-data-clos::doc-string my-ds-2)))
429 (addtest (lisp-stat-dataclos) badAccess7
430 (ensure
431 (lisp-stat-data-clos::case-labels my-ds-2)))
433 (addtest (lisp-stat-dataclos) badAccess8
434 (ensure
435 (lisp-stat-data-clos::var-labels my-ds-2)))
437 ;; need to ensure that for things like the following, that we protect
438 ;; this a bit more so that the results are not going to to be wrong.
439 ;; That would be a bit nasty if the statistical-dataset becomes
440 ;; inconsistent.
442 (addtest (lisp-stat-dataclos) badAccess9
443 (ensure
444 (setf (lisp-stat-data-clos::var-labels my-ds-2)
445 (list "a" "b"))))
447 (addtest (lisp-stat-dataclos) badAccess10
448 (ensure
449 (progn
450 ;; no error, but corrupts structure
451 (setf (lisp-stat-data-clos::var-labels my-ds-2)
452 (list "a" "b" "c"))
453 ;; error happens here
454 (not (consistent-statistical-dataset-p my-ds-2))))) ;; Nil
456 (addtest (lisp-stat-dataclos) badAccess12
457 (ensure
458 (setf (lisp-stat-data-clos::var-labels my-ds-2)
459 (list "a" "b"))))
461 (addtest (lisp-stat-dataclos) badAccess13
462 (ensure
463 (consistent-statistical-dataset-p my-ds-2))) ;; T
465 ;; This is now done by:
466 (addtest (lisp-stat-dataclos) badAccess14
467 (ensure-error
468 (let ((old-varnames (varNames my-ds-2)))
469 (setf (varNames my-ds-2) (list "a" "b")) ;; should error
470 (setf (varNames my-ds-2) old-varnames)
471 (error "don't reach this point in badaccess14"))))
473 ;; break this up.
474 (defvar origCaseNames nil)
476 (addtest (lisp-stat-dataclos) badAccess15
477 (ensure
478 (progn
479 (setf origCaseNames (caseNames my-ds-2))
480 (setf (caseNames my-ds-2) (list "a" "b" "c" 4 5))
481 (caseNames my-ds-2)
482 (ignore-errors (setf (caseNames my-ds-2) (list "a" "b" 4 5)))
483 (setf (caseNames my-ds-2) origCaseNames))))
485 ;; (run-tests)
486 ;; (describe (run-tests))