documentation and function clean up, leaving generics for nvars/ncases and better...
[CommonLispStat.git] / src / data / dataframe.lisp
blobb0fa51714f7cc482822920a516295c1b3dc4b184
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2010-01-15 08:18:48 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--2010, AJ Rossini. See LICENSE.mit in
8 ;;; toplevel directory for conditions.
10 ;;; Purpose: Data packaging and access for Common Lisp Statistics,
11 ;;; using a DATAFRAME-LIKE virtual structure.
12 ;;; This redoes dataframe structures in a CLOS based
13 ;;; framework. Currently contains the virtual class
14 ;;; DATAFRAME-LIKE as well as the actual classes
15 ;;; DATAFRAME-ARRAY and DATAFRAME-MATRIXLIKE.
17 ;;; What is this talk of 'release'? Klingons do not make software
18 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
19 ;;; designers and quality assurance people in its wake.
21 (in-package :cls-dataframe)
23 ;;; No real basis for work, there is a bit of new-ness and R-ness to
24 ;;; this work. In particular, the notion of relation is key and
25 ;;; integral to the analysis. Tables are related and matched vectors,
26 ;;; for example. "column" vectors are related observations (by
27 ;;; measure/recording) while "row" vectors are related readings (by
28 ;;; case, independence). This does mean that we are placing
29 ;;; statistical semantics into the computational data object -- and
30 ;;; that it is a violation of use to consider rows which are not at
31 ;;; the least conditionally independent (though the conditioning
32 ;;; should be outside the data set, not internally specified).
34 ;;; So we want a verb-driven API for data collection construction. We
35 ;;; should encode independence or lack of, as a computable status.
37 ;;; Need to figure out statistically-typed vectors. We then map a
38 ;;; series of typed vectors over to tables where columns are equal
39 ;;; typed. In a sense, this is a relation (1-1) of equal-typed
40 ;;; arrays. For the most part, this ends up making the R data.frame
41 ;;; into a relational building block (considering 1-1 mappings using
42 ;;; row ID as a relation). Is this a worthwhile generalization or
43 ;;; communicable analogy?
45 ;;; verbs vs semantics for DF construction -- consider the possibily
46 ;;; of how adverbs and verbs relate, where to put which semantically
47 ;;; to allow for general approach.
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.
65 ;;; Is there any need for an N-way dataframe (N>2) ? Am currently
66 ;;; assuming not, that this is specializing only the
67 ;;; "independent cases"-by-variables format and that there would be
68 ;;; other tools for other structures.
70 ;;; Misc Functions (to move into a lisp data manipulation support package)
72 ;; the next two should be merged into a general replicator pattern.
73 (defun gen-seq (n &optional (start 1))
74 "Generates an integer sequence of length N starting at START. Used
75 for indexing."
76 (if (>= n start)
77 (append (gen-seq (- n 1) start) (list n))))
79 (defun repeat-seq (n item)
80 "FIXME: There has to be a better way -- I'm sure of it!
81 (repeat-seq 3 \"d\") ; => (\"d\" \"d\" \"d\")
82 (repeat-seq 3 'd) ; => ('d 'd 'd)
83 (repeat-seq 3 (list 1 2))"
84 (if (>= n 1)
85 (append (repeat-seq (1- n) item) (list item))))
87 (defun strsym->indexnum (df strsym)
88 "Returns a number indicating the DF column labelled by STRSYM.
89 Probably should be generic/methods dispatching on DATAFRAME-LIKE type."
90 (position strsym (varlabels df)))
92 (defun string->number (str)
93 "Convert a string <str> representing a number to a number. A second
94 value is returned indicating the success of the conversion. Examples:
95 (string->number \"123\") ; => 123 t
96 (string->number \"1.23\") ; => 1.23 t"
97 (let ((*read-eval* nil))
98 (let ((num (read-from-string str)))
99 (values num (numberp num)))))
102 (equal 'testme 'testme)
103 (defparameter *test-pos* 'testme)
104 (position *test-pos* (list 'a 'b 'testme 'c))
105 (position #'(lambda (x) (equal x "testme")) (list "a" "b" "testme" "c"))
106 (position #'(lambda (x) (equal x 1)) (list 2 1 3 4))
109 ;;; abstract dataframe class
111 (defclass dataframe-like (matrix-like)
112 ((store :initform nil
113 :accessor store
114 :documentation "not useful in the -like virtual class case,
115 contains actual data")
116 (store-class :initform nil
117 :accessor store-class
118 :documentation "Lisp class used for the dataframe storage.")
119 (case-labels :initform nil
120 :initarg :case-labels
121 :type list
122 :accessor case-labels
123 :documentation "labels used for describing cases (doc
124 metadata), possibly used for merging.")
125 (var-labels :initform nil
126 :initarg :var-labels
127 :type list
128 :accessor var-labels
129 :documentation "Variable names. List order matches
130 order in STORE.")
131 (var-types :initform nil
132 :initarg :var-types
133 :type list
134 :accessor var-types
135 :documentation "List of symbols representing classes
136 which describe the range of contents for a particular
137 variable. Symbols must be valid types for check-type.
138 List order matches order in STORE.")
139 (doc-string :initform nil
140 :initarg :doc
141 :accessor doc-string
142 :documentation "additional information, potentially
143 uncomputable, possibly metadata, about dataframe-like
144 instance."))
145 (:documentation "Abstract class for standard statistical analysis
146 dataset for (possible conditionally, externally) independent
147 data. Rows are considered to be independent, matching
148 observations. Columns are considered to be type-consistent,
149 match a variable with distribution. inherits from lisp-matrix
150 base MATRIX-LIKE class. MATRIX-LIKE (from lisp-matrix) is
151 basically a rectangular table without storage. We emulate that,
152 and add storage, row/column labels, and within-column-typing.
154 DATAFRAME-LIKE is the basic cases by variables framework. Need
155 to embed this within other structures which allow for generalized
156 relations. Goal is to ensure that relations imply and drive the
157 potential for statistical relativeness such as correlation,
158 interference, and similar concepts.
160 STORE is the storage component. We ignore this in the
161 DATAFRAME-LIKE class, as it is the primary differentiator,
162 spec'ing the structure used for storing the actual data. We
163 create methods which depend on STORE for access. The only
164 critical component is that STORE be a class which is
165 xarray-compliant. Examples of such mixins are DATAFRAME-ARRAY
166 and DATAFRAME-MATRIXLIKE. The rest of this structure is
167 metadata."))
169 ;;; Specializing on superclasses...
171 ;;; Access and Extraction: implementations needed for any storage
172 ;;; type. But here, just to point out that we've got a specializing
173 ;;; virtual subclass (DATAFRAME-LIKE specializing MATRIX-LIKE).
175 (defgeneric nvars (df)
176 (:documentation "number of variables represented in storage type.")
177 (:method ((df dataframe-like))
178 (xdim (store df) 0)))
181 (defun nvars-store (store)
182 "Return number of variables (columns) in dataframe storage. Doesn't
183 test that that list is a valid listoflist dataframe structure."
184 (etypecase store
185 (array (array-dimension store 1))
186 (matrix-like (ncols store))
187 (list (length (elt store 0)))))
190 (defgeneric ncases (df)
191 (:documentation "number of cases (indep, or indep within context,
192 observantions) within STORE.")
193 (:method ((df dataframe-like))
194 (xdim (store df) 1)))
197 (defun ncase-store (store)
198 "Return number of cases (rows) in dataframe storage. Doesn't test
199 that that list is a valid listoflist dataframe structure."
200 (etypecase store
201 (array (array-dimension store 0))
202 (matrix-like (nrows store))
203 (list (length store))))
206 ;; Testing consistency/coherency.
208 (defgeneric consistent-dataframe-p (df)
209 (:documentation "methods to check for consistency. Mostly of
210 internal interest, since ideally we'd have to use standard
211 constructs to ensure that we do not get the dataframe structure
212 misaligned.")
213 (:method (object) "General objects are not consistent dataframes!" nil)
214 (:method ((df dataframe-like))
215 "At minimum, must dispatch on virtual-class."
216 (and
217 ;; ensure dimensionality
218 (= (length (var-labels df)) (ncols df)) ; array-dimensions (dataset df))
219 (= (length (case-labels df)) (nrows df))
220 ;; ensure claimed STORE-CLASS
221 ;; when dims are sane, ensure variable-typing is consistent
222 (progn
223 (dotimes (i (nrows df))
224 (dotimes (j (ncols df))
225 ;; xref bombs if not a df-like subclass so we don't worry
226 ;; about specialization. Need to ensure xref throws a
227 ;; condition we can recover from.
228 ;; (check-type (aref dt i j) (elt lot j)))))) ???
229 (typep (xref df i j) (nth j (var-types df)))))
230 t))))
233 ;;; FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
235 ;;; Q: change the following to generic functions and dispatch on
236 ;;; array, matrix, and dataframe? Others?
237 (defun make-labels (initstr num)
238 "generate a list of strings which can be used as labels, i.e. something like
239 (make-labels \"a\" 3) => '(\"a1\" \"a2\" \"a3\")."
240 (check-type initstr string)
241 (mapcar #'(lambda (x y) (concatenate 'string x y))
242 (repeat-seq num initstr)
243 (mapcar #'(lambda (x) (format nil "~A" x)) (gen-seq num))))
247 (defun make-dataframe (newdata
248 &key (vartypes nil)
249 (caselabels nil) (varlabels nil)
250 (doc "no docs"))
251 "Helper function to use instead of make-instance to assure
252 construction of proper DF-array."
253 (check-type newdata (or matrix-like array list))
254 (check-type caselabels sequence)
255 (check-type varlabels sequence)
256 (check-type doc string)
257 (let ((ncases (ncase-store newdata))
258 (nvars (nvars-store newdata)))
259 (if caselabels (assert (= ncases (length caselabels))))
260 (if varlabels (assert (= nvars (length varlabels))))
261 (let ((newcaselabels (if caselabels
262 caselabels
263 (make-labels "C" ncases)))
264 (newvarlabels (if varlabels
265 varlabels
266 (make-labels "V" nvars))))
267 (etypecase newdata
268 (list
269 (make-instance 'dataframe-listoflist
270 :storage newdata
271 :nrows (length newcaselabels)
272 :ncols (length newvarlabels)
273 :case-labels newcaselabels
274 :var-labels newvarlabels
275 :var-types vartypes))
276 (array
277 (make-instance 'dataframe-array
278 :storage newdata
279 :nrows (length newcaselabels)
280 :ncols (length newvarlabels)
281 :case-labels newcaselabels
282 :var-labels newvarlabels
283 :var-types vartypes))
284 (matrix-like
285 (make-instance 'dataframe-matrixlike
286 :storage newdata
287 :nrows (length newcaselabels)
288 :ncols (length newvarlabels)
289 :case-labels newcaselabels
290 :var-labels newvarlabels
291 :var-types vartypes))
293 ))))
296 (make-dataframe #2A((1.2d0 1.3d0) (2.0d0 4.0d0)))
297 (make-dataframe #2A(('a 1) ('b 2)))
298 (xref (make-dataframe #2A(('a 1) ('b 2))) 0 1)
299 (xref (make-dataframe #2A(('a 1) ('b 2))) 1 0)
300 (make-dataframe 4) ; ERROR, should we allow?
301 (make-dataframe #2A((4)))
302 (make-dataframe (rand 10 5)) ;; ERROR, but should work!
306 (defun row-order-as-list (ary)
307 "Pull out data in row order into a list."
308 (let ((result (list))
309 (nrows (nth 0 (array-dimensions ary)))
310 (ncols (nth 1 (array-dimensions ary))))
311 (dotimes (i ncols)
312 (dotimes (j nrows)
313 (append result (aref ary i j))))))
315 (defun col-order-as-list (ary)
316 "Pull out data in row order into a list."
317 (let ((result (list))
318 (nrows (nth 0 (array-dimensions ary)))
319 (ncols (nth 1 (array-dimensions ary))))
320 (dotimes (i nrows)
321 (dotimes (j ncols)
322 (append result (aref ary i j))))))
324 (defun transpose-array (ary)
325 "map NxM to MxN."
326 (make-array (reverse (array-dimensions ary))
327 :initial-contents (col-order-as-list ary)))
329 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
330 ;;; possibilities on top of the generic function structure. Not
331 ;;; intended as make-work!
333 (defun varlabels (df)
334 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
335 (var-labels df))
337 (defun set-varlabels (df vl)
338 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
339 (if (= (length (var-labels df))
340 (length vl))
341 (setf (var-labels df) vl)
342 (error "wrong size.")))
344 (defsetf varlabels set-varlabels)
346 ;;; Case-name handling for Tables. Needs error checking.
347 (defun caselabels (df)
348 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
349 (case-labels df))
351 (defun set-caselabels (df cl)
352 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
353 (if (= (length (case-labels df))
354 (length cl))
355 (setf (case-labels df) cl)
356 (error "wrong size.")))
358 (defsetf caselabels set-caselabels)
360 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
361 ;; See also:
362 ;; (documentation 'dataframe-like 'type)
367 ;;; Do we establish methods for dataframe-like, which specialize to
368 ;;; particular instances of storage?
370 (defmethod print-object ((object dataframe-like) stream)
371 (print-unreadable-object (object stream :type t)
372 (format stream " ~d x ~d" (nrows object) (ncols object))
373 (terpri stream)
374 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
375 (dotimes (j (ncols object)) ; print labels
376 (write-char #\tab stream)
377 (write-char #\tab stream)
378 (format stream "~T~A~T" (nth j (var-labels object))))
379 (dotimes (i (nrows object)) ; print obs row
380 (terpri stream)
381 (format stream "~A:~T" (nth i (case-labels object)))
382 (dotimes (j (ncols object))
383 (write-char #\tab stream) ; (write-char #\space stream)
384 ;; (write (xref object i j) :stream stream)
385 (format stream "~7,3E" (xref object i j)) ; if works, need to include a general output mechanism control
386 ))))
389 (defun print-structure-relational (ds)
390 "example of what we want the methods to look like. Should be sort
391 of like a graph of spreadsheets if the storage is a relational
392 structure."
393 (dolist (k (relations ds))
394 (let ((currentRelationSet (getRelation ds k)))
395 (print-as-row (var-labels currentRelationSet))
396 (let ((j -1))
397 (dolist (i (case-labels currentRelationSet))
398 (print-as-row
399 (append (list i)
400 (xref-obsn (dataset currentRelationSet)
401 (incf j)))))))))
403 (defun testecase (s)
404 (ecase s
405 ((scalar) 1)
406 ((asd asdf) 2)))
408 (testecase 'scalar)
409 (testecase 'asd)
410 (testecase 'asdf)
411 (testecase 'as)
415 ;;; Vector-like generalizations: we consider observation-like and
416 ;;; variable-like to be abstract classes which provide row and column
417 ;;; access to dataframe structures. These will be specialized, in
418 ;;; that rows correspond to an observation (or case?) which are
419 ;;; multitype, while columns correspond to a variable, which must be
420 ;;; singularly typed.
422 (defclass observation-like (dataframe-like)
424 (:documentation "dataframe-like with only 1 row, is an observation-like."))
426 (defclass variable-like (dataframe-like)
428 (:documentation "dataframe-like with only 1 column is a variable-like."))
430 ;;; Need to implement views, i.e. dataframe-view-like,
431 ;;; observation-view-like, variable-view-like.
435 ;;; Need to consider read-only variants, leveraging the xref
436 ;;; strategy.
440 ;;; Dataframe <-> Listoflist support
441 ;; the following will be handy to help out folks adjust. It should
442 ;; provide a means to write code faster and better.
444 ;; leverages listoflist support in our version of xarray
445 (defun listoflist->dataframe (lol) ; &key (type :row-major))
446 "Create a cases-by-variables data frame consisting of numeric data,
447 from a ROW-MAJOR list-of-lists representation. A COLUMN-MAJOR
448 representation should be handled using the transpose-listoflists
449 function."
450 (check-type lol list) ; imperfect -- must verify all list elements are also lists.
451 (if (listoflist:sublists-of-same-size-p lol)
452 (make-dataframe (listoflist:listoflist->array lol))
453 (error "make-data-set-from-lists: no combining different length lists"))
454 (error "make-data-set-from-lists: proposed name exists"))
457 ;;;;;;;; from dataframe-xarray experiment
460 (defmethod xref ((obj dataframe-like) &rest subscripts)
461 "For data-frame-like, dispatch on storage object."
462 (xref (dataset obj) subscripts))
464 (defmethod (setf xref) (value (obj dataframe-like) &rest subscripts)
465 (setf (xref (dataset obj) subscripts) value))
467 (defmethod xref ((obj matrix-like) &rest indices))
469 (defmethod xtype ((obj dataframe-like))
470 "Unlike the standard xtype, here we need to return a vector of the
471 types. Vectors can have single types, but arrays have single type.
472 Dataframe-like have multiple types, variable-like single type,
473 case-like has multiple types, and matrix-like has single type.")
475 (defmethod xdims ((obj dataframe-like))
476 (dataframe-dimensions obj))
478 ;; use default methods at this point, except for potentially weird DFs
479 (defmethod xdims* ())
481 (defmethod xdim ((obj dataframe-like) index)
482 (dataframe-dimension index))
485 (defmethod xrank ())
487 (defmethod slice ())
489 (defmethod take ())
491 (defmethod carray ())
493 (defmacro with-dataframe (env &rest progn)
494 "Compute using variable names with with.data.frame type semantics.")
496 (defmacro with-data (body)
497 "Stream-handling, maintaining I/O through object typing.")