remove any last thoughts of dfref returning a non-scalar. We don't go there. Overen...
[CommonLispStat.git] / src / data / data-clos.lisp
blob94d26f7991ef82dc885cc343d9a0f3b56e21075b
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2009-03-26 18:32:57 tony>
4 ;;; Creation: <2008-03-12 17:18:42 blindglobe@gmail.com>
5 ;;; File: data-clos.lisp
6 ;;; Author: AJ Rossini <blindglobe@gmail.com>
7 ;;; Copyright: (c)2008, AJ Rossini. BSD, LLGPL, or GPLv2, depending
8 ;;; on how it arrives.
10 ;;; Purpose: Data packaging and access for Common Lisp Statistics.
11 ;;; This redoes data storage structures in a CLOS based
12 ;;; framework.
13 ;;;
15 ;;; What is this talk of 'release'? Klingons do not make software
16 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
17 ;;; designers and quality assurance people in its wake.
19 (in-package :lisp-stat-data-clos)
21 ;;; No real basis for work, there is a bit of new-ness and R-ness to
22 ;;; this work. In particular, the notion of relation is key and
23 ;;; integral to the analysis. Tables are related and matched vectors,
24 ;;; for example. "column" vectors are related observations (by
25 ;;; measure/recording) while "row" vectors are related readings (by
26 ;;; case)
28 ;;; Relational structure -- can we capture a completely unnormalized
29 ;;; data strucutre to propose possible modeling approaches, and
30 ;;; propose appropriate models and inferential strategies?
32 ;;; So we want a verb-driven API for data collection construction. We
33 ;;; should encode independence or lack of, as possible.
35 ;;; Need to figure out typed vectors. We then map a series of typed
36 ;;; vectors over to tables where columns are equal typed. In a sense,
37 ;;; this is a relation (1-1) of equal-typed arrays. For the most
38 ;;; part, this ends up making the R data.frame into a relational
39 ;;; building block (considering 1-1 mappings using row ID as a
40 ;;; relation). Is this a worthwhile generalization?
42 ;;; verbs vs semantics for DS conversion -- consider the possibily of
43 ;;; how adverbs and verbs relate, where to put which semantically to
44 ;;; allow for general approach.
46 ;;; eg. Kasper's talk on the FUSION collection of parsers.
48 ;;;
49 ;;; Need to consider modification APIs
50 ;;; actions are:
51 ;;; - import
52 ;;; - get/set row names (case names)
53 ;;; - column names (variable names)
54 ;;; - dataset values
55 ;;; - annotation/metadata
56 ;;; - make sure that we do coherency checking in the exported
57 ;;; - functions.
58 ;;; - ...
59 ;;; - reshapeData/reformat/reshapr a reformed version of the dataset (no
60 ;;; additional input).
61 ;;; - either overwriting or not, i.e. with or without copy.
62 ;;; - check consistency of resulting data with metadata and related
63 ;;; data information.
64 ;;; -
67 ;;; Misc Functions (to move into a lisp data manipulation support package)
69 (defun gen-seq (n &optional (start 1))
70 "There has to be a better way -- I'm sure of it! default count from 1.
71 (gen-seq 4) ; => (1 2 3 4)
72 (gen-seq 0) ; => nil
73 (gen-seq 5 3) ; => 3 4 5
75 (if (>= n start)
76 (append (gen-seq (- n 1) start) (list n))))
78 (defun repeat-seq (n item)
79 "FIXME: There has to be a better way -- I'm sure of it!
80 (repeat-seq 3 \"d\") ; => (\"d\" \"d\" \"d\")
81 (repeat-seq 3 'd) ; => ('d 'd 'd)
83 (if (>= n 1)
84 (append (repeat-seq (1- n) item) (list item))))
88 (defun strsym->indexnum (df strsym)
89 "Returns a number indicating which column in DF has STRSYM labeling
90 it. Probably should be a method dispatching on the type of
91 DATAFRAME-LIKE."
92 (position strsym (varlabels df)))
94 (defun string->number (str)
95 "Convert a string <str> representing a number to a number. A second value is
96 returned indicating the success of the conversion.
97 Example: (rsm.string:string->number \"123\")
98 123
100 (let ((*read-eval* nil))
101 (let ((num (read-from-string str)))
102 (values num (numberp num)))))
104 (string->number "1.22")
109 (equal 'testme 'testme)
110 (defparameter *test-pos* 'testme)
111 (position *test-pos* (list 'a 'b 'testme 'c))
112 (position #'(lambda (x) (equal x "testme")) (list "a" "b" "testme" "c"))
113 (position #'(lambda (x) (equal x 1)) (list 2 1 3 4))
117 ;;; abstract dataframe class
119 (defclass dataframe-like (matrix-like)
121 ;; Matrix-like (from lisp-matrix) is basically a rectangular table
122 ;; without storage. We emulate that, and add storage, row/column
123 ;; labels, and within-column-typing.
125 ;; STORE is the storage component. We ignore this in the DATAFRAME-LIKE
126 ;; class, as it is the primary differentiator, driving how access
127 ;; (getting/setting) is done. We create methods depending on the
128 ;; storage component, which access data as appropriate. See
129 ;; DATAFRAME-ARRAY for an example implementation.
130 ;; the rest of this is metadata. In particular, we should find a
131 ;; more flexible, compact way to store this.
132 (case-labels :initform nil
133 :initarg :case-labels
134 :type list
135 :accessor case-labels
136 :documentation "labels used for describing cases (doc
137 metadata), possibly used for merging.")
138 (var-labels :initform nil
139 :initarg :var-labels
140 :type list
141 :accessor var-labels
142 :documentation "Variable names.")
143 (var-types :initform nil
144 :initarg :var-types
145 :type list
146 :accessor var-types
147 :documentation "variable types to ensure fit")
148 (documentation-string :initform nil
149 :initarg :doc
150 :accessor doc-string
151 :documentation "additional information,
152 potentially uncomputable, possibly metadata, about dataframe-like
153 instance."))
154 (:documentation "Abstract class for standard statistical analysis
155 dataset for independent data. Rows are considered
156 to be independent, matching observations. Columns
157 are considered to be type-consistent, match a
158 variable with distribution. inherits from
159 lisp-matrix base MATRIX-LIKE class.
161 DATAFRAME-LIKE is the basic cases by variables
162 framework. Need to embed this within other
163 structures which allow for generalized relations.
164 Goal is to ensure that relations imply and drive
165 the potential for statistical relativeness such as
166 correlation, interference, and similar concepts."))
169 ;;; Generics specialized above matrix-like, particularly for
170 ;;; dataframe-like objects. Need methods for any storage
171 ;;; implementation.
173 (defgeneric dataframe-dimensions (df)
174 (:documentation "")
175 (:method ((df dataframe-like))
176 (error "dispatch on virtual class.")))
178 (defgeneric dataframe-dimension (df index)
179 (:documentation "")
180 (:method ((df dataframe-like) index)
181 (elt (dataframe-dimensions df) index)))
183 (defgeneric dfref (df index1 index2) ; &key return-type
184 (:documentation "scalar access with selection of possible return
185 object types.")
186 (:method ((df dataframe-like) index1 index2) ; &key return-type
187 (error "need a real class with real storage to reference elements.")))
189 ;;; Specializing on superclasses...
190 ;;; Access and Extraction: implementations needed for any storage
191 ;;; type. But here, just to point out that we've got a specializing
192 ;;; virtual subclass (DATAFRAME-LIKE specializing MATRIX-LIKE).
194 (defmethod nrows ((df dataframe-like))
195 "specializes on inheritance from matrix-like in lisp-matrix."
196 (error "Need implementation; can't dispatch on virtual class DATAFRAME-LIKE."))
198 (defmethod ncols ((df dataframe-like))
199 "specializes on inheritance from matrix-like in lisp-matrix."
200 (error "Need implementation; can't dispatch on virtual class DATAFRAME-LIKE."))
202 ;; Testing consistency/coherency.
204 (defgeneric consistent-dataframe-p (df)
205 (:documentation "methods to check for consistency.")
206 (:method ((df dataframe-like))
207 (error "Need implementation; can't dispatch on virtual class DATAFRAME-LIKE.")))
211 (defun ensure-consistent-datatable-type (dt lot)
212 "given a datatable and a listoftypes, ensure that the datatble
213 variables are consistent."
214 (destructuring-bind (n p) ;; why use let when we can be cool? Sigh.
215 (array-dimensions dt)
216 (dotimes (i n)
217 (dotimes (j p)
218 (check-type (aref dt i j) (elt lot j))))))
222 ;;; GENERAL FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
224 ;;; Q: change the following to generic functions and dispatch on
225 ;;; array, matrix, and dataframe? Others?
226 (defun make-labels (initstr num &key (return-type 'string))
227 "generate a list of strings (or symbols?) which can be used as
228 labels, i.e. something like
229 '(a1 a2 a3)
231 '(\"a1\" \"a2\" \"a3\")."
232 (check-type initstr string)
233 (mapcar #'(lambda (x y) (concatenate 'string x y))
234 (repeat-seq num initstr)
235 (mapcar #'(lambda (x) (format nil "~A" x)) (gen-seq num))))
238 (make-labels 'c 2)
239 (make-labels "c" 4)
242 (defun make-dataframe (newdata
243 &key (vartypes nil)
244 (caselabels nil) (varlabels nil)
245 (doc "no docs"))
246 "Helper function to use instead of make-instance to assure
247 construction of proper DF-array."
248 (check-type newdata array)
249 (check-type caselabels sequence)
250 (check-type varlabels sequence)
251 (check-type doc string)
252 (if caselabels (assert (= (array-dimension newdata 0) (length caselabels))))
253 (if varlabels (assert (= (array-dimension newdata 1) (length varlabels))))
254 (let ((newcaselabels (if caselabels
255 caselabels
256 (make-labels "C" (array-dimension newdata 0))))
257 (newvarlabels (if varlabels
258 varlabels
259 (make-labels "V" (array-dimension newdata 1)))))
260 (make-instance 'dataframe-array
261 :storage newdata
262 :nrows (length newcaselabels)
263 :ncols (length newvarlabels)
264 :case-labels newcaselabels
265 :var-labels newvarlabels
266 :var-types vartypes)))
269 (make-dataframe #2A((1.2d0 1.3d0) (2.0d0 4.0d0)))
270 (make-dataframe #2A(('a 1) ('b 2)))
271 (dfref (make-dataframe #2A(('a 1) ('b 2))) 0 1)
272 (dfref (make-dataframe #2A(('a 1) ('b 2))) 1 0)
273 (make-dataframe 4) ; ERROR
274 (make-dataframe #2A((4)))
278 (defun row-order-as-list (ary)
279 "Pull out data in row order into a list."
280 (let ((result (list))
281 (nrows (nth 0 (array-dimensions ary)))
282 (ncols (nth 1 (array-dimensions ary))))
283 (dotimes (i ncols)
284 (dotimes (j nrows)
285 (append result (aref ary i j))))))
287 (defun col-order-as-list (ary)
288 "Pull out data in row order into a list."
289 (let ((result (list))
290 (nrows (nth 0 (array-dimensions ary)))
291 (ncols (nth 1 (array-dimensions ary))))
292 (dotimes (i nrows)
293 (dotimes (j ncols)
294 (append result (aref ary i j))))))
296 (defun transpose-array (ary)
297 "map NxM to MxN."
298 (make-array (reverse (array-dimensions ary))
299 :initial-contents (col-order-as-list ary)))
301 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
302 ;;; possibilities on top of the generic function structure. Not
303 ;;; intended as make-work!
305 (defun varlabels (df)
306 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
307 (var-labels df))
309 (defun set-varlabels (df vl)
310 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
311 (if (= (length (var-labels df))
312 (length vl))
313 (setf (var-labels df) vl)
314 (error "wrong size.")))
316 (defsetf varlabels set-varlabels)
318 ;;; Case-name handling for Tables. Needs error checking.
319 (defun caselabels (df)
320 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
321 (case-labels df))
323 (defun set-caselabels (df cl)
324 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
325 (if (= (length (case-labels df))
326 (length cl))
327 (setf (case-labels df) cl)
328 (error "wrong size.")))
330 (defsetf caselabels set-caselabels)
332 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
334 ;; See also:
335 ;; (documentation 'dataframe-like 'type)
337 (defclass dataframe-array (dataframe-like)
338 ((store :initform nil
339 :initarg :storage
340 :type (array * *)
341 :accessor dataset
342 :documentation "Data storage: typed as array."))
343 (:documentation "example implementation of dataframe-like using storage
344 based on lisp arrays. An obvious alternative could be a
345 dataframe-matrix-like which uses the lisp-matrix classes."))
347 (defmethod nrows ((df dataframe-array))
348 "specializes on inheritance from matrix-like in lisp-matrix."
349 (array-dimension (dataset df) 0))
351 (defmethod ncols ((df dataframe-array))
352 "specializes on inheritance from matrix-like in lisp-matrix."
353 (array-dimension (dataset df) 1))
355 (defmethod consistent-dataframe-p ((ds dataframe-array))
356 "Test that dataframe-like is internally consistent with metadata.
357 Ensure that dims of stored data are same as case and var labels.
359 Currently checks length of things, but needs to check type of things
360 as well."
361 (and
362 ;; ensure dimensionality
363 (equal (list (ncols ds) (nrows ds)) ; array-dimensions (dataset ds))
364 (list (length (var-labels ds))
365 (length (case-labels ds))))
366 ;; when dims sane, check-type for each variable
367 (progn
368 (dolist (i (ncols ds))
369 (dotimes (j (nrows ds))
370 (typep (aref (dataset ds) i j) (nth i (var-types ds)))))
371 t)))
377 (defun testecase (s)
378 (ecase s
379 ((scalar) 1)
380 ((asd asdf) 2)))
382 (testecase 'scalar)
383 (testecase 'asd)
384 (testecase 'asdf)
385 (testecase 'as)
388 (defmethod dfref ((df dataframe-array)
389 (index1 number) (index2 number))
390 "Returns a scalar in array, in the same vein as aref, mref, vref, etc.
391 idx1/2 is row/col or case/var."
392 (aref (dataset df) index1 index2))
395 (defun dfref-var (df index return-type)
396 "Returns the data in a single variable as type.
397 type = sequence, vector, vector-like (if valid numeric type) or dataframe."
398 (ecase return-type
399 (('list)
400 (map 'list
401 #'(lambda (x) (dfref df index x))
402 (gen-seq (nth 2 (array-dimensions (dataset df))))))
403 (('vector) t)
404 (:vector-like t)
405 (:matrix-like t)
406 (:dataframe t)))
408 (defun dfref-case (df index return-type)
409 "Returns row as sequence."
410 (ecase return-type
411 (:list
412 (map 'list
413 #'(lambda (x) (dfref df x index))
414 (gen-seq (nth 1 (array-dimensions (dataset df))))))
415 (:vector t)
416 (:vector-like t)
417 (:matrix-like t)
418 (:dataframe t)))
420 ;; FIXME
421 (defun dfref-2indexlist (df indexlist1 indexlist2 &key (return-type :array))
422 "return an array, row X col dims. FIXME TESTME"
423 (case return-type
424 (:array
425 (let ((my-pre-array (list)))
426 (dolist (x indexlist1)
427 (dolist (y indexlist2)
428 (append my-pre-array (dfref df x y))))
429 (make-array (list (length indexlist1)
430 (length indexlist2))
431 :initial-contents my-pre-array)))
432 (:dataframe
433 (make-instance 'dataframe-array
434 :storage (make-array
435 (list (length indexlist1)
436 (length indexlist2))
437 :initial-contents (dataset df))
438 ;; ensure copy for this and following
439 :doc (doc-string df)
440 ;; the following 2 need to be subseted based on
441 ;; the values of indexlist1 and indexlist2
442 :case-labels (case-labels df)
443 :var-labels (var-labels df)))))
445 ;;; Do we establish methods for dataframe-like, which specialize to
446 ;;; particular instances of storage?
448 (defmethod print-object ((object dataframe-array) stream)
449 (print-unreadable-object (object stream :type t)
450 (format stream " ~d x ~d" (nrows object) (ncols object))
451 (terpri stream)
452 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
453 (dotimes (j (ncols object))
454 (write-char #\tab stream)
455 (format stream "~A~T" (nth j (var-labels object))))
456 (dotimes (i (nrows object))
457 (terpri stream)
458 (format stream "~A:~T" (nth i (case-labels object)))
459 (dotimes (j (ncols object))
460 ;; (write-char #\space stream)
461 (write-char #\tab stream)
462 (write (dfref object i j) :stream stream)))))
465 (defun print-structure-relational (ds)
466 "example of what we want the methods to look like. Should be sort
467 of like a graph of spreadsheets if the storage is a relational
468 structure."
469 (dolist (k (relations ds))
470 (let ((currentRelationSet (getRelation ds k)))
471 (print-as-row (var-labels currentRelationSet))
472 (let ((j -1))
473 (dolist (i (case-labels currentRelationSet))
474 (print-as-row
475 (append (list i)
476 (dfref-obsn (dataset currentRelationSet)
477 (incf j)))))))))