3 ;;; Time-stamp: <2009-04-28 23:15:27 tony>
4 ;;; Creation: <2008-03-12 17:18:42 blindglobe@gmail.com>
5 ;;; File: dataframe.lisp
6 ;;; Author: AJ Rossini <blindglobe@gmail.com>
7 ;;; Copyright: (c)2008, AJ Rossini. BSD, LLGPL, or GPLv2, depending
10 ;;; Purpose: Data packaging and access for Common Lisp Statistics.
11 ;;; This redoes dataframe structures in a CLOS based
12 ;;; framework. Currently contains the virtual class
13 ;;; DATAFRAME-LIKE as well as the actual classes
14 ;;; DATAFRAME-ARRAY and DATAFRAME-MATRIXLIKE
16 ;;; What is this talk of 'release'? Klingons do not make software
17 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
18 ;;; designers and quality assurance people in its wake.
20 (in-package :cls-dataframe
)
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 vectors,
25 ;;; for example. "column" vectors are related observations (by
26 ;;; measure/recording) while "row" vectors are related readings (by
27 ;;; case, independence). This does mean that we are placing
28 ;;; statistical semantics into the computational data object -- and
29 ;;; that it is a violation of use to consider rows which are not at
30 ;;; the least conditionally independent (though the conditioning
31 ;;; should be outside the data set, not internally specified).
33 ;;; So we want a verb-driven API for data collection construction. We
34 ;;; should encode independence or lack of, as possible.
36 ;;; Need to figure out statistically-typed vectors. We then map a
37 ;;; series of typed vectors over to tables where columns are equal
38 ;;; typed. In a sense, this is a relation (1-1) of equal-typed
39 ;;; arrays. For the most part, this ends up making the R data.frame
40 ;;; into a relational building block (considering 1-1 mappings using
41 ;;; row ID as a relation). Is this a worthwhile generalization or
42 ;;; communicable analogy?
44 ;;; verbs vs semantics for DF construction -- consider the possibily
45 ;;; of how adverbs and verbs relate, where to put which semantically
46 ;;; to allow for general approach.
48 ;;; Need to consider modification APIs
51 ;;; - get/set row names (case names)
52 ;;; - column names (variable names)
54 ;;; - annotation/metadata
55 ;;; - make sure that we do coherency checking in the exported
58 ;;; - reshapeData/reformat/reshapr a reformed version of the dataset (no
59 ;;; additional input).
60 ;;; - either overwriting or not, i.e. with or without copy.
61 ;;; - check consistency of resulting data with metadata and related
65 ;;; Misc Functions (to move into a lisp data manipulation support package)
67 ;; the next two should be merged into a general replicator pattern.
68 (defun gen-seq (n &optional
(start 1))
69 "Generates an integer sequence of length N starting at START. Used
72 (append (gen-seq (- n
1) start
) (list n
))))
74 (defun repeat-seq (n item
)
75 "FIXME: There has to be a better way -- I'm sure of it!
76 (repeat-seq 3 \"d\") ; => (\"d\" \"d\" \"d\")
77 (repeat-seq 3 'd) ; => ('d 'd 'd)
78 (repeat-seq 3 (list 1 2))"
80 (append (repeat-seq (1- n
) item
) (list item
))))
83 (defun strsym->indexnum
(df strsym
)
84 "Returns a number indicating the DF column labelled by STRSYM.
85 Probably should be a method dispatching on DATAFRAME-LIKE type."
86 (position strsym
(varlabels df
)))
88 (defun string->number
(str)
89 "Convert a string <str> representing a number to a number. A second value is
90 returned indicating the success of the conversion.
92 (string->number \"123\") ; => 123 t
93 (string->number \"1.23\") ; => 1.23 t"
94 (let ((*read-eval
* nil
))
95 (let ((num (read-from-string str
)))
96 (values num
(numberp num
)))))
99 (equal 'testme
'testme
)
100 (defparameter *test-pos
* 'testme
)
101 (position *test-pos
* (list 'a
'b
'testme
'c
))
102 (position #'(lambda (x) (equal x
"testme")) (list "a" "b" "testme" "c"))
103 (position #'(lambda (x) (equal x
1)) (list 2 1 3 4))
106 ;;; abstract dataframe class
108 (defclass dataframe-like
(matrix-like)
109 ((case-labels :initform nil
110 :initarg
:case-labels
112 :accessor case-labels
113 :documentation
"labels used for describing cases (doc
114 metadata), possibly used for merging.")
115 (var-labels :initform nil
119 :documentation
"Variable names.")
120 (var-types :initform nil
124 :documentation
"variable types to ensure fit")
125 (doc-string :initform nil
128 :documentation
"additional information, potentially
129 uncomputable, possibly metadata, about
130 dataframe-like instance."))
131 (:documentation
"Abstract class for standard statistical analysis
132 dataset for independent data. Rows are considered
133 to be independent, matching observations. Columns
134 are considered to be type-consistent, match a
135 variable with distribution. inherits from
136 lisp-matrix base MATRIX-LIKE class.
137 MATRIX-LIKE (from lisp-matrix) is basically a
138 rectangular table without storage. We emulate
139 that, and add storage, row/column labels, and
140 within-column-typing.
142 DATAFRAME-LIKE is the basic cases by variables
143 framework. Need to embed this within other
144 structures which allow for generalized relations.
145 Goal is to ensure that relations imply and drive
146 the potential for statistical relativeness such as
147 correlation, interference, and similar concepts.
149 STORE is the storage component. We ignore this in
150 the DATAFRAME-LIKE class, as it is the primary
151 differentiator, spec'ing the structure used for
152 storing the actual data. We create methods which
153 depend on STORE for access. See DATAFRAME-ARRAY
154 and DATAFRAME-MATRIXLIKE for examples. The rest of
157 ;;; Generics specialized above matrix-like, particularly for
158 ;;; dataframe-like objects. Need implementation of methods which
159 ;;; depend on storage form.
161 (defgeneric dataframe-dimensions
(df)
163 (:method
((df dataframe-like
))
164 (error "Dispatch on virtual class, Method needed for
165 DATAFRAME-DIMENSIONS with class ~A." (find-class df
))))
167 (defgeneric dataframe-dimension
(df index
)
169 (:method
((df dataframe-like
) index
)
170 (elt (dataframe-dimensions df
) index
)))
172 (defgeneric dfref
(df index1 index2
)
173 (:documentation
"Scalar access to entries in dataframe.")
174 (:method
((df dataframe-like
) index1 index2
)
175 (error "Dispatch on virtual class, Method needed for DFREF with
176 class ~A." (find-class df
))))
178 (defgeneric set-dfref
(df index1 index2 val
)
179 (:documentation
"setter for dfref")
180 (:method
((df dataframe-like
) index1 index2 val
)
181 (error "Dispatch on virtual class, Method needed for SET-DFREF
182 with class ~A." (find-class df
))))
184 (defsetf dfref set-dfref
)
186 (defgeneric dfselect
(df &optional cases vars indices
)
187 (:documentation
"access to sub-dataframes. Always returns a dataframe.")
188 (:method
((df dataframe-like
) &optional cases vars indices
)
189 (declare (ignorable cases vars
))
190 (if indices
(error "Indicies not used yet"))
191 (error "Dispatch on virtual class, Method needed for DFSELECT with
192 class ~A." (find-class df
))))
194 ;;; Specializing on superclasses...
196 ;;; Access and Extraction: implementations needed for any storage
197 ;;; type. But here, just to point out that we've got a specializing
198 ;;; virtual subclass (DATAFRAME-LIKE specializing MATRIX-LIKE).
200 (defmethod nrows ((df dataframe-like
))
201 "specializes on inheritance from matrix-like in lisp-matrix."
202 (error "Need implementation; can't dispatch on virtual class DATAFRAME-LIKE."))
204 (defmethod ncols ((df dataframe-like
))
205 "specializes on inheritance from matrix-like in lisp-matrix."
206 (error "Need implementation; can't dispatch on virtual class DATAFRAME-LIKE."))
208 ;; Testing consistency/coherency.
210 (defgeneric consistent-dataframe-p
(df)
211 (:documentation
"methods to check for consistency.")
212 (:method
((df dataframe-like
))
214 ;; ensure dimensionality
215 (= (length (var-labels df
)) (ncols df
)) ; array-dimensions (dataset df))
216 (= (length (case-labels df
)) (nrows df
))
217 ;; when dims sane, check-type for each variable
219 (dotimes (i (nrows df
))
220 (dotimes (j (ncols df
))
221 ;; dfref bombs if not a df-like subclass so we don't worry
222 ;; about specialization.
223 ;; (check-type (aref dt i j) (elt lot j)))))) ???
224 (typep (dfref df i j
) (nth j
(var-types df
)))))
228 ;;; FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
230 ;;; Q: change the following to generic functions and dispatch on
231 ;;; array, matrix, and dataframe? Others?
232 (defun make-labels (initstr num
)
233 "generate a list of strings which can be used as labels, i.e. something like
234 (make-labels \"a\" 3) => '(\"a1\" \"a2\" \"a3\")."
235 (check-type initstr string
)
236 (mapcar #'(lambda (x y
) (concatenate 'string x y
))
237 (repeat-seq num initstr
)
238 (mapcar #'(lambda (x) (format nil
"~A" x
)) (gen-seq num
))))
240 (defun ncase-store (store)
242 (array (array-dimension store
0))
243 (matrix-like (nrows store
))))
245 (defun nvars-store (store)
247 (array (array-dimension store
1))
248 (matrix-like (ncols store
))))
251 (defun make-dataframe (newdata
253 (caselabels nil
) (varlabels nil
)
255 "Helper function to use instead of make-instance to assure
256 construction of proper DF-array."
257 (check-type newdata
(or matrix-like array
))
258 (check-type caselabels sequence
)
259 (check-type varlabels sequence
)
260 (check-type doc string
)
261 (let ((ncases (ncase-store newdata
))
262 (nvars (nvars-store newdata
)))
263 (if caselabels
(assert (= ncases
(length caselabels
))))
264 (if varlabels
(assert (= nvars
(length varlabels
))))
265 (let ((newcaselabels (if caselabels
267 (make-labels "C" ncases
)))
268 (newvarlabels (if varlabels
270 (make-labels "V" nvars
))))
273 (make-instance 'dataframe-array
275 :nrows
(length newcaselabels
)
276 :ncols
(length newvarlabels
)
277 :case-labels newcaselabels
278 :var-labels newvarlabels
279 :var-types vartypes
))
281 (make-instance 'dataframe-matrixlike
283 :nrows
(length newcaselabels
)
284 :ncols
(length newvarlabels
)
285 :case-labels newcaselabels
286 :var-labels newvarlabels
287 :var-types vartypes
))))))
290 (make-dataframe #2A
((1.2d0
1.3d0
) (2.0d0
4.0d0
)))
291 (make-dataframe #2A
(('a
1) ('b
2)))
292 (dfref (make-dataframe #2A
(('a
1) ('b
2))) 0 1)
293 (dfref (make-dataframe #2A
(('a
1) ('b
2))) 1 0)
294 (make-dataframe 4) ; ERROR, should we allow?
295 (make-dataframe #2A
((4)))
296 (make-dataframe (rand 10 5)) ;; ERROR, but should work!
300 (defun row-order-as-list (ary)
301 "Pull out data in row order into a list."
302 (let ((result (list))
303 (nrows (nth 0 (array-dimensions ary
)))
304 (ncols (nth 1 (array-dimensions ary
))))
307 (append result
(aref ary i j
))))))
309 (defun col-order-as-list (ary)
310 "Pull out data in row order into a list."
311 (let ((result (list))
312 (nrows (nth 0 (array-dimensions ary
)))
313 (ncols (nth 1 (array-dimensions ary
))))
316 (append result
(aref ary i j
))))))
318 (defun transpose-array (ary)
320 (make-array (reverse (array-dimensions ary
))
321 :initial-contents
(col-order-as-list ary
)))
323 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
324 ;;; possibilities on top of the generic function structure. Not
325 ;;; intended as make-work!
327 (defun varlabels (df)
328 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
331 (defun set-varlabels (df vl
)
332 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
333 (if (= (length (var-labels df
))
335 (setf (var-labels df
) vl
)
336 (error "wrong size.")))
338 (defsetf varlabels set-varlabels
)
340 ;;; Case-name handling for Tables. Needs error checking.
341 (defun caselabels (df)
342 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
345 (defun set-caselabels (df cl
)
346 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
347 (if (= (length (case-labels df
))
349 (setf (case-labels df
) cl
)
350 (error "wrong size.")))
352 (defsetf caselabels set-caselabels
)
354 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
356 ;; (documentation 'dataframe-like 'type)
358 ;;;;; DATAFRAME-ARRAY
360 (defclass dataframe-array
(dataframe-like)
361 ((store :initform nil
365 :documentation
"Data storage: typed as array."))
366 (:documentation
"example implementation of dataframe-like using storage
367 based on lisp arrays. An obvious alternative could be a
368 dataframe-matrix-like which uses the lisp-matrix classes."))
370 (defmethod nrows ((df dataframe-array
))
371 "specializes on inheritance from matrix-like in lisp-matrix."
372 (array-dimension (dataset df
) 0))
374 (defmethod ncols ((df dataframe-array
))
375 "specializes on inheritance from matrix-like in lisp-matrix."
376 (array-dimension (dataset df
) 1))
378 (defmethod dfref ((df dataframe-array
)
379 (index1 number
) (index2 number
))
380 "Returns a scalar in array, in the same vein as aref, mref, vref, etc.
381 idx1/2 is row/col or case/var."
382 (aref (dataset df
) index1 index2
))
384 (defmethod set-dfref ((df dataframe-array
) (index1 number
) (index2 number
) val
)
385 "set value for df-ar."
386 ;; (check-type val (elt (var-type df) index2))
387 (setf (aref (dataset df
) index1 index2
) val
))
389 (defparameter *default-dataframe-class
* 'dataframe-array
)
391 (defmethod dfselect ((df dataframe-array
)
392 &optional cases vars indices
)
393 "Extract the OR of cases, vars, or have a list of indices to extract"
394 (if indices
(error "Indicies not used yet"))
395 (let ((newdf (make-instance *default-dataframe-class
*
396 :storage
(make-array (list (length cases
) (length vars
)))
397 :nrows
(length cases
)
400 :case-labels
(select-list caselist
(case-labels df
))
401 :var-labels
(select-list varlist
(var-labels df
))
402 :var-types
(select-list varlist
(vartypes df
))
405 (dotimes (i (length cases
))
406 (dotimes (j (length vars
))
407 (setf (dfref newdf i j
)
409 (position (elt cases i
) (case-labels df
))
410 (position (elt vars j
) (var-labels df
))))))))
412 ;;;;; DATAFRAME-MATRIXLIKE
414 (defclass dataframe-matrixlike
(dataframe-like)
415 ((store :initform nil
419 :documentation
"Data storage: typed as matrix-like
421 (:documentation
"example implementation of dataframe-like using storage
422 based on lisp-matrix structures."))
424 (defmethod nrows ((df dataframe-matrixlike
))
425 "specializes on inheritance from matrix-like in lisp-matrix."
426 (matrix-dimension (dataset df
) 0))
428 (defmethod ncols ((df dataframe-matrixlike
))
429 "specializes on inheritance from matrix-like in lisp-matrix."
430 (matrix-dimension (dataset df
) 1))
432 (defmethod dfref ((df dataframe-matrixlike
)
433 (index1 number
) (index2 number
))
434 "Returns a scalar in array, in the same vein as aref, mref, vref, etc.
435 idx1/2 is row/col or case/var."
436 (mref (dataset df
) index1 index2
))
438 (defmethod set-dfref ((df dataframe-matrixlike
)
439 (index1 number
) (index2 number
) val
)
440 "Sets a value for df-ml."
441 ;; NEED TO CHECK TYPE!
442 ;; (check-type val (elt (vartype df) index2))
443 (setf (mref (dataset df
) index1 index2
) val
))
447 ;;;;;; IMPLEMENTATION INDEPENDENT FUNCTIONS AND METHODS
448 ;;;;;; (use only dfref, nrows, ncols and similar dataframe-like
449 ;;;;;; components as core).
451 (defun dfref-var (df index return-type
)
452 "Returns the data in a single variable as type.
453 type = sequence, vector, vector-like (if valid numeric type) or dataframe."
457 #'(lambda (x) (dfref df index x
))
458 (gen-seq (nth 2 (array-dimensions (dataset df
))))))
464 (defun dfref-case (df index return-type
)
465 "Returns row as sequence."
469 #'(lambda (x) (dfref df x index
))
470 (gen-seq (nth 1 (array-dimensions (dataset df
))))))
477 (defun dfref-2indexlist (df indexlist1 indexlist2
&key
(return-type :array
))
478 "return an array, row X col dims. FIXME TESTME"
481 (let ((my-pre-array (list)))
482 (dolist (x indexlist1
)
483 (dolist (y indexlist2
)
484 (append my-pre-array
(dfref df x y
))))
485 (make-array (list (length indexlist1
)
487 :initial-contents my-pre-array
)))
489 (make-instance 'dataframe-array
491 (list (length indexlist1
)
493 :initial-contents
(dataset df
))
494 ;; ensure copy for this and following
496 ;; the following 2 need to be subseted based on
497 ;; the values of indexlist1 and indexlist2
498 :case-labels
(case-labels df
)
499 :var-labels
(var-labels df
)))))
501 ;;; Do we establish methods for dataframe-like, which specialize to
502 ;;; particular instances of storage?
504 (defmethod print-object ((object dataframe-like
) stream
)
505 (print-unreadable-object (object stream
:type t
)
506 (format stream
" ~d x ~d" (nrows object
) (ncols object
))
508 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
509 (dotimes (j (ncols object
)) ; print labels
510 (write-char #\tab stream
)
511 (write-char #\tab stream
)
512 (format stream
"~T~A~T" (nth j
(var-labels object
))))
513 (dotimes (i (nrows object
)) ; print obs row
515 (format stream
"~A:~T" (nth i
(case-labels object
)))
516 (dotimes (j (ncols object
))
517 (write-char #\tab stream
) ; (write-char #\space stream)
518 ;; (write (dfref object i j) :stream stream)
519 (format stream
"~7,3E" (dfref object i j
)) ; if works, need to include a general output mechanism control
523 (defun print-structure-relational (ds)
524 "example of what we want the methods to look like. Should be sort
525 of like a graph of spreadsheets if the storage is a relational
527 (dolist (k (relations ds
))
528 (let ((currentRelationSet (getRelation ds k
)))
529 (print-as-row (var-labels currentRelationSet
))
531 (dolist (i (case-labels currentRelationSet
))
534 (dfref-obsn (dataset currentRelationSet
)