document some tasks in dataframe.lisp that need resolution.
[CommonLispStat.git] / src / data / dataframe.lisp
blobbe156a84d5d1d15478a9a0d35a5c1b00ca255f1e
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2012-10-12 16:40:46 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 or iterator
73 ;; pattern.
74 (defun gen-seq (n &optional (start 1))
75 "Generates an integer sequence of length N starting at START. Used
76 for indexing."
77 (if (>= n start)
78 (append (gen-seq (- n 1) start) (list n))))
80 (defun repeat-seq (n item)
81 "FIXME: There has to be a better way -- I'm sure of it!
82 (repeat-seq 3 \"d\") ; => (\"d\" \"d\" \"d\")
83 (repeat-seq 3 'd) ; => ('d 'd 'd)
84 (repeat-seq 3 (list 1 2))"
85 (if (>= n 1)
86 (append (repeat-seq (1- n) item) (list item))))
88 (defun strsym->indexnum (df strsym)
89 "Returns a number indicating the DF column labelled by STRSYM.
90 Probably should be generic/methods dispatching on DATAFRAME-LIKE type."
91 (position strsym (varlabels df)))
93 (defun string->number (str)
94 "Convert a string <str> representing a number to a number. A second
95 value is returned indicating the success of the conversion. Examples:
96 (string->number \"123\") ; => 123 t
97 (string->number \"1.23\") ; => 1.23 t"
98 (let ((*read-eval* nil))
99 (let ((num (read-from-string str)))
100 (values num (numberp num)))))
103 (equal 'testme 'testme)
104 (defparameter *test-pos* 'testme)
105 (position *test-pos* (list 'a 'b 'testme 'c))
106 (position #'(lambda (x) (equal x "testme")) (list "a" "b" "testme" "c"))
107 (position #'(lambda (x) (equal x 1)) (list 2 1 3 4))
110 ;;; abstract dataframe class
112 (defclass dataframe-like (matrix-like)
115 (store :initform nil
116 :accessor dataset
117 :documentation "not useful in the -like virtual class case,
118 contains actual data")
119 (store-class :initform nil
120 :accessor store-class
121 :documentation "Lisp class used for the dataframe storage.")
123 (case-labels :initform nil
124 :initarg :case-labels
125 :type list
126 :accessor case-labels
127 :documentation "labels used for describing cases (doc
128 metadata), possibly used for merging.")
129 (var-labels :initform nil
130 :initarg :var-labels
131 :type list
132 :accessor var-labels
133 :documentation "Variable names. List order matches
134 order in STORE.")
135 (var-types :initform nil
136 :initarg :var-types
137 :type list
138 :accessor var-types
139 :documentation "List of symbols representing classes
140 which describe the range of contents for a particular
141 variable. Symbols must be valid types for check-type.
142 List order matches order in STORE.")
143 (doc-string :initform nil
144 :initarg :doc
145 :accessor doc-string
146 :documentation "additional information, potentially
147 uncomputable, possibly metadata, about dataframe-like
148 instance."))
149 (:documentation "Abstract class for standard statistical analysis
150 dataset for (possible conditionally, externally) independent
151 data. Rows are considered to be independent, matching
152 observations. Columns are considered to be type-consistent,
153 match a variable with distribution. inherits from lisp-matrix
154 base MATRIX-LIKE class. MATRIX-LIKE (from lisp-matrix) is
155 basically a rectangular table without storage. We emulate that,
156 and add storage, row/column labels, and within-column-typing.
158 DATAFRAME-LIKE is the basic cases by variables framework. Need
159 to embed this within other structures which allow for generalized
160 relations. Goal is to ensure that relations imply and drive the
161 potential for statistical relativeness such as correlation,
162 interference, and similar concepts.
164 STORE is the storage component. We ignore this in the
165 DATAFRAME-LIKE class, as it is the primary differentiator,
166 spec'ing the structure used for storing the actual data. We
167 create methods which depend on STORE for access. The only
168 critical component is that STORE be a class which is
169 xarray-compliant. Examples of such mixins are DATAFRAME-ARRAY
170 and DATAFRAME-MATRIXLIKE. The rest of this structure is
171 metadata."))
173 ;;; Specializing on superclasses...
175 ;;; Access and Extraction: implementations needed for any storage
176 ;;; type. But here, just to point out that we've got a specializing
177 ;;; virtual subclass (DATAFRAME-LIKE specializing MATRIX-LIKE).
179 (defgeneric nvars (df)
180 (:documentation "number of variables represented in storage type.")
181 (:method ((df dataframe-like))
182 (xdim (store df) 1))
183 (:method ((df array))
184 (xdim df 1)))
188 (defun nvars-store (store)
189 "Return number of variables (columns) in dataframe storage. Doesn't
190 test that that list is a valid listoflist dataframe structure."
191 (etypecase store
192 (array (array-dimension store 1))
193 (matrix-like (ncols store))
194 (list (length (elt store 0)))))
197 (defgeneric ncases (df)
198 (:documentation "number of cases (indep, or indep within context,
199 observantions) within DF storage form.")
200 (:method ((df matrix-like))
201 (nrows df))
202 (:method ((df list))
203 (xdim df 0)) ;; probably should do a valid LISTOFLIST structure test but this would be inefficient
204 (:method ((df array))
205 (xdim df 0)))
208 (defun ncase-store (store)
209 "Return number of cases (rows) in dataframe storage. Doesn't test
210 that that list is a valid listoflist dataframe structure."
211 (etypecase store
212 (array (array-dimension store 0))
213 (matrix-like (nrows store))
214 (list (length store))))
217 ;; Testing consistency/coherency.
219 (defgeneric consistent-dataframe-p (df)
220 (:documentation "methods to check for consistency. Mostly of
221 internal interest, since ideally we'd have to use standard
222 constructs to ensure that we do not get the dataframe structure
223 misaligned.")
224 (:method (object) "General objects are not consistent dataframes!" nil)
225 (:method ((df dataframe-like))
226 "At minimum, must dispatch on virtual-class."
227 (and
228 ;; ensure dimensionality
229 (= (length (var-labels df)) (ncols df)) ; array-dimensions (dataset df))
230 (= (length (case-labels df)) (nrows df))
231 ;; ensure claimed STORE-CLASS
232 ;; when dims are sane, ensure variable-typing is consistent
233 (progn
234 (dotimes (i (nrows df))
235 (dotimes (j (ncols df))
236 ;; xref bombs if not a df-like subclass so we don't worry
237 ;; about specialization. Need to ensure xref throws a
238 ;; condition we can recover from.
239 ;; (check-type (aref dt i j) (elt lot j)))))) ???
240 (typep (xref df i j) (nth j (var-types df)))))
241 t))))
244 ;;; FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
246 ;;; Q: change the following to generic functions and dispatch on
247 ;;; array, matrix, and dataframe? Others?
248 (defun make-labels (initstr num)
249 "generate a list of strings which can be used as labels, i.e. something like
250 (make-labels \"a\" 3) => '(\"a1\" \"a2\" \"a3\")."
251 (check-type initstr string)
252 (mapcar #'(lambda (x y) (concatenate 'string x y))
253 (repeat-seq num initstr)
254 (mapcar #'(lambda (x) (format nil "~A" x)) (gen-seq num))))
256 (defun check-dataframe-params (data vartypes varlabels caselabels doc)
257 "This will throw an exception (FIXME: Need to put together a CLS exception system, this could be part of it)"
258 ;; type checking
259 (check-type data (or matrix-like array list))
260 (check-type caselabels sequence)
261 (check-type varlabels sequence)
262 (check-type vartypes sequence)
263 (check-type doc string)
264 ;; dimension checking
265 (if vartypes (assert (= (nvars data) (length vartypes))))
266 (if varlabels (assert (= (nvars data) (length varlabels))))
267 (if caselabels (assert (= (ncases data) (length varlabels)))))
269 (defmacro build-dataframe (type)
270 `(progn
271 (check-dataframe-params data vartypes varlabels caselabels doc)
272 (let ((newcaselabels (if caselabels
273 caselabels
274 (make-labels "C" (ncases data))))
275 (newvarlabels (if varlabels
276 varlabels
277 (make-labels "V" (nvars data))))
278 ;; also should determine most restrictive possible (compsci
279 ;; and/or statistical) variable typing (integer, double,
280 ;; string, symbol, *). FIXME: until we get the mixed typing system in place, we will just leave null
281 (newvartypes (if vartypes
282 vartypes
283 (make-labels "*" (nvars data)))))
284 (make-instance ,type
285 :storage data
286 :nrows (length newcaselabels)
287 :ncols (length newvarlabels)
288 :case-labels newcaselabels
289 :var-labels newvarlabels
290 :var-types newvartypes))))
292 ;; (macroexpand '(build-dataframe 'test)))
294 (defgeneric make-dataframe2 (data &key vartypes varlabels caselabels doc)
295 (:documentation "testing generic dispatch. Data should be in table format desired for use."))
297 (defun make-dataframe (newdata
298 &key (vartypes nil)
299 (caselabels nil) (varlabels nil)
300 (doc "no docs"))
301 "Helper function to use instead of make-instance to assure
302 construction of proper DF-array."
303 (check-type newdata (or matrix-like array list))
304 (check-type caselabels sequence)
305 (check-type varlabels sequence)
306 (check-type doc string)
307 (let ((ncases (ncases newdata))
308 (nvars (nvars newdata)))
309 (if caselabels (assert (= ncases (length caselabels))))
310 (if varlabels (assert (= nvars (length varlabels))))
311 (let ((newcaselabels (if caselabels
312 caselabels
313 (make-labels "C" ncases)))
314 (newvarlabels (if varlabels
315 varlabels
316 (make-labels "V" nvars))))
317 (etypecase newdata
318 (list
319 (make-instance 'dataframe-listoflist
320 :storage newdata
321 :nrows (length newcaselabels)
322 :ncols (length newvarlabels)
323 :case-labels newcaselabels
324 :var-labels newvarlabels
325 :var-types vartypes))
326 (array
327 (make-instance 'dataframe-array
328 :storage newdata
329 :nrows (length newcaselabels)
330 :ncols (length newvarlabels)
331 :case-labels newcaselabels
332 :var-labels newvarlabels
333 :var-types vartypes))
334 (matrix-like
335 (make-instance 'dataframe-matrixlike
336 :storage newdata
337 :nrows (length newcaselabels)
338 :ncols (length newvarlabels)
339 :case-labels newcaselabels
340 :var-labels newvarlabels
341 :var-types vartypes))))))
344 (make-dataframe #2A((1.2d0 1.3d0) (2.0d0 4.0d0)))
345 (make-dataframe #2A(('a 1) ('b 2)))
346 (xref (make-dataframe #2A(('a 1) ('b 2))) 0 1)
347 (xref (make-dataframe #2A(('a 1) ('b 2))) 1 0)
348 (make-dataframe 4) ; ERROR, should we allow?
349 (make-dataframe #2A((4)))
350 (make-dataframe (rand 10 5)) ;; ERROR, but should work!
354 ;;; FIXME: the following two functions hurt the eyes. I think that
356 ;;; array->listoflist :order '(:column :row)
358 ;;; would be a better approach. But don't we already have this in the
359 ;;; listoflist package? and more critically, we should have this as a
360 ;;; generic, so that it would be more like
362 ;;; dataframe->listoflist :order '(:column :row)
365 (defun row-order-as-list (ary)
366 "Pull out data in row order into a list."
367 (let ((result (list))
368 (nrows (nth 0 (array-dimensions ary)))
369 (ncols (nth 1 (array-dimensions ary))))
370 (dotimes (i ncols)
371 (dotimes (j nrows)
372 (append result (aref ary i j))))))
374 (defun col-order-as-list (ary)
375 "Pull out data in column order into a list."
376 (let ((result (list))
377 (nrows (nth 0 (array-dimensions ary)))
378 (ncols (nth 1 (array-dimensions ary))))
379 (dotimes (i nrows)
380 (dotimes (j ncols)
381 (append result (aref ary i j))))))
384 ;;; FIXME: need to have a by-reference and by-copy variant.
385 (defun transpose-array (ary)
386 "map NxM to MxN."
387 (make-array (reverse (array-dimensions ary))
388 :initial-contents (col-order-as-list ary)))
390 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
391 ;;; possibilities on top of the generic function structure. Not
392 ;;; intended as make-work!
394 (defun varlabels (df)
395 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
396 (var-labels df))
398 (defun set-varlabels (df vl)
399 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
400 (if (= (length (var-labels df))
401 (length vl))
402 (setf (var-labels df) vl)
403 (error "wrong size.")))
405 (defsetf varlabels set-varlabels)
407 ;;; Case-name handling for Tables. Needs error checking.
408 (defun caselabels (df)
409 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
410 (case-labels df))
412 (defun set-caselabels (df cl)
413 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
414 (if (= (length (case-labels df))
415 (length cl))
416 (setf (case-labels df) cl)
417 (error "wrong size.")))
419 (defsetf caselabels set-caselabels)
421 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
422 ;; See also:
423 ;; (documentation 'dataframe-like 'type)
428 ;;; Do we establish methods for dataframe-like, which specialize to
429 ;;; particular instances of storage?
432 ;;; FIXME:
433 ;;; - doesn't line up output
434 ;;; - doesn't process large (wide, OR long) objects, efficiently (need
435 ;;; to flag such processing to avoid gigabyte printouts)
436 ;;; - should include options for better printing, or perhaps the
437 ;;; defmethod should be simpler, with a complex method for providing
438 ;;; actual data.
439 (defmethod print-object ((object dataframe-like) stream)
440 (print-unreadable-object (object stream :type t)
441 (format stream " ~d x ~d" (nrows object) (ncols object))
442 (terpri stream)
443 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
444 (dotimes (j (ncols object)) ; print labels
445 (write-char #\tab stream)
446 (write-char #\tab stream)
447 (format stream "~T~A~T" (nth j (var-labels object))))
448 (dotimes (i (nrows object)) ; print obs row
449 (terpri stream)
450 (format stream "~A:~T" (nth i (case-labels object)))
451 (dotimes (j (ncols object))
452 (write-char #\tab stream) ; (write-char #\space stream)
453 ;; (write (xref object i j) :stream stream)
454 (format stream "~7,3E" (xref object i j)) ; if works, need to include a general output mechanism control
455 ))))
458 (defun print-structure-relational (ds)
459 "example of what we want the methods to look like. Should be sort
460 of like a graph of spreadsheets if the storage is a relational
461 structure."
462 (dolist (k (relations ds))
463 (let ((currentRelationSet (getRelation ds k)))
464 (print-as-row (var-labels currentRelationSet))
465 (let ((j -1))
466 (dolist (i (case-labels currentRelationSet))
467 (print-as-row
468 (append (list i)
469 (xref-obsn (dataset currentRelationSet)
470 (incf j)))))))))
472 (defun testecase (s)
473 (ecase s
474 ((scalar) 1)
475 ((asd asdf) 2)))
477 (testecase 'scalar)
478 (testecase 'asd)
479 (testecase 'asdf)
480 (testecase 'as)
484 ;;; Vector-like generalizations: we consider observation-like and
485 ;;; variable-like to be abstract classes which provide row and column
486 ;;; access to dataframe structures. These will be specialized, in
487 ;;; that rows correspond to an observation (or case?) which are
488 ;;; multitype, while columns correspond to a variable, which must be
489 ;;; singularly typed.
491 (defclass observation-like (dataframe-like)
493 (:documentation "dataframe-like with only 1 row, is an observation-like."))
495 (defclass variable-like (dataframe-like)
497 (:documentation "dataframe-like with only 1 column is a variable-like."))
499 ;;; Need to implement views, i.e. dataframe-view-like,
500 ;;; observation-view-like, variable-view-like.
504 ;;; Need to consider read-only variants, leveraging the xref
505 ;;; strategy.
509 ;;; Dataframe <-> Listoflist support
510 ;; the following will be handy to help out folks adjust. It should
511 ;; provide a means to write code faster and better.
513 ;; leverages listoflist support in our version of xarray
514 (defun listoflist->dataframe (lol) ; &key (type :row-major))
515 "Create a cases-by-variables data frame consisting of numeric data,
516 from a ROW-MAJOR list-of-lists representation. A COLUMN-MAJOR
517 representation should be handled using the transpose-listoflists
518 function."
519 (check-type lol list) ; imperfect -- must verify all list elements are also lists.
520 (if (listoflist:sublists-of-same-size-p lol)
521 (make-dataframe (listoflist:listoflist->array lol))
522 (error "make-data-set-from-lists: no combining different length lists"))
523 (error "make-data-set-from-lists: proposed name exists"))
528 ;;; FIXME: THIS COMPLETELY OBSOLETE?
529 ;;; from dataframe-xarray experiment
532 (defmethod xref ((obj dataframe-like) &rest subscripts)
533 "For data-frame-like, dispatch on storage object."
534 (xref (dataset obj) subscripts))
536 (defmethod (setf xref) (value (obj dataframe-like) &rest subscripts)
537 (setf (xref (dataset obj) subscripts) value))
539 (defmethod xref ((obj matrix-like) &rest indices))
541 (defmethod xtype ((obj dataframe-like))
542 "Unlike the standard xtype, here we need to return a vector of the
543 types. Vectors can have single types, but arrays have single type.
544 Dataframe-like have multiple types, variable-like single type,
545 case-like has multiple types, and matrix-like has single type.")
547 (defmethod xdims ((obj dataframe-like))
548 (dataframe-dimensions obj))
550 ;; use default methods at this point, except for potentially weird DFs
551 (defmethod xdims* ())
553 (defmethod xdim ((obj dataframe-like) index)
554 (dataframe-dimension index))
557 (defmethod xrank ())
559 (defmethod slice ())
561 (defmethod take ())
563 (defmethod carray ())
565 (defmacro with-dataframe (env &rest progn)
566 "Compute using variable names with with.data.frame type semantics.")
568 (defmacro with-data (body)
569 "Stream-handling, maintaining I/O through object typing.")