whitespace and a missing paren in dataframe.lisp
[CommonLispStat.git] / src / data / dataframe.lisp
blob4427c59452693ee9c099de67a2b5d593dd891c25
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2010-01-25 10:54:44 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)
114 (store :initform nil
115 :accessor store
116 :documentation "not useful in the -like virtual class case,
117 contains actual data")
118 (store-class :initform nil
119 :accessor store-class
120 :documentation "Lisp class used for the dataframe storage.")
122 (case-labels :initform nil
123 :initarg :case-labels
124 :type list
125 :accessor case-labels
126 :documentation "labels used for describing cases (doc
127 metadata), possibly used for merging.")
128 (var-labels :initform nil
129 :initarg :var-labels
130 :type list
131 :accessor var-labels
132 :documentation "Variable names. List order matches
133 order in STORE.")
134 (var-types :initform nil
135 :initarg :var-types
136 :type list
137 :accessor var-types
138 :documentation "List of symbols representing classes
139 which describe the range of contents for a particular
140 variable. Symbols must be valid types for check-type.
141 List order matches order in STORE.")
142 (doc-string :initform nil
143 :initarg :doc
144 :accessor doc-string
145 :documentation "additional information, potentially
146 uncomputable, possibly metadata, about dataframe-like
147 instance."))
148 (:documentation "Abstract class for standard statistical analysis
149 dataset for (possible conditionally, externally) independent
150 data. Rows are considered to be independent, matching
151 observations. Columns are considered to be type-consistent,
152 match a variable with distribution. inherits from lisp-matrix
153 base MATRIX-LIKE class. MATRIX-LIKE (from lisp-matrix) is
154 basically a rectangular table without storage. We emulate that,
155 and add storage, row/column labels, and within-column-typing.
157 DATAFRAME-LIKE is the basic cases by variables framework. Need
158 to embed this within other structures which allow for generalized
159 relations. Goal is to ensure that relations imply and drive the
160 potential for statistical relativeness such as correlation,
161 interference, and similar concepts.
163 STORE is the storage component. We ignore this in the
164 DATAFRAME-LIKE class, as it is the primary differentiator,
165 spec'ing the structure used for storing the actual data. We
166 create methods which depend on STORE for access. The only
167 critical component is that STORE be a class which is
168 xarray-compliant. Examples of such mixins are DATAFRAME-ARRAY
169 and DATAFRAME-MATRIXLIKE. The rest of this structure is
170 metadata."))
172 ;;; Specializing on superclasses...
174 ;;; Access and Extraction: implementations needed for any storage
175 ;;; type. But here, just to point out that we've got a specializing
176 ;;; virtual subclass (DATAFRAME-LIKE specializing MATRIX-LIKE).
178 (defgeneric nvars (df)
179 (:documentation "number of variables represented in storage type.")
180 (:method ((df dataframe-like))
181 (xdim (store df) 0)))
184 (defun nvars-store (store)
185 "Return number of variables (columns) in dataframe storage. Doesn't
186 test that that list is a valid listoflist dataframe structure."
187 (etypecase store
188 (array (array-dimension store 1))
189 (matrix-like (ncols store))
190 (list (length (elt store 0)))))
193 (defgeneric ncases (df)
194 (:documentation "number of cases (indep, or indep within context,
195 observantions) within DF storage form.")
196 (:method ((df matrix-like))
197 (nrows df))
198 (:method ((df list))
199 (xdim df)) ;; probably should do a valid LISTOFLIST structure test but this would be inefficient
200 (:method ((df array))
201 (xdim df)))
204 (defun ncase-store (store)
205 "Return number of cases (rows) in dataframe storage. Doesn't test
206 that that list is a valid listoflist dataframe structure."
207 (etypecase store
208 (array (array-dimension store 0))
209 (matrix-like (nrows store))
210 (list (length store))))
213 ;; Testing consistency/coherency.
215 (defgeneric consistent-dataframe-p (df)
216 (:documentation "methods to check for consistency. Mostly of
217 internal interest, since ideally we'd have to use standard
218 constructs to ensure that we do not get the dataframe structure
219 misaligned.")
220 (:method (object) "General objects are not consistent dataframes!" nil)
221 (:method ((df dataframe-like))
222 "At minimum, must dispatch on virtual-class."
223 (and
224 ;; ensure dimensionality
225 (= (length (var-labels df)) (ncols df)) ; array-dimensions (dataset df))
226 (= (length (case-labels df)) (nrows df))
227 ;; ensure claimed STORE-CLASS
228 ;; when dims are sane, ensure variable-typing is consistent
229 (progn
230 (dotimes (i (nrows df))
231 (dotimes (j (ncols df))
232 ;; xref bombs if not a df-like subclass so we don't worry
233 ;; about specialization. Need to ensure xref throws a
234 ;; condition we can recover from.
235 ;; (check-type (aref dt i j) (elt lot j)))))) ???
236 (typep (xref df i j) (nth j (var-types df)))))
237 t))))
240 ;;; FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
242 ;;; Q: change the following to generic functions and dispatch on
243 ;;; array, matrix, and dataframe? Others?
244 (defun make-labels (initstr num)
245 "generate a list of strings which can be used as labels, i.e. something like
246 (make-labels \"a\" 3) => '(\"a1\" \"a2\" \"a3\")."
247 (check-type initstr string)
248 (mapcar #'(lambda (x y) (concatenate 'string x y))
249 (repeat-seq num initstr)
250 (mapcar #'(lambda (x) (format nil "~A" x)) (gen-seq num))))
254 (defun make-dataframe (newdata
255 &key (vartypes nil)
256 (caselabels nil) (varlabels nil)
257 (doc "no docs"))
258 "Helper function to use instead of make-instance to assure
259 construction of proper DF-array."
260 (check-type newdata (or matrix-like array list))
261 (check-type caselabels sequence)
262 (check-type varlabels sequence)
263 (check-type doc string)
264 (let ((ncases (ncases newdata))
265 (nvars (nvars newdata)))
266 (if caselabels (assert (= ncases (length caselabels))))
267 (if varlabels (assert (= nvars (length varlabels))))
268 (let ((newcaselabels (if caselabels
269 caselabels
270 (make-labels "C" ncases)))
271 (newvarlabels (if varlabels
272 varlabels
273 (make-labels "V" nvars))))
274 (etypecase newdata
275 (list
276 (make-instance 'dataframe-listoflist
277 :storage newdata
278 :nrows (length newcaselabels)
279 :ncols (length newvarlabels)
280 :case-labels newcaselabels
281 :var-labels newvarlabels
282 :var-types vartypes))
283 (array
284 (make-instance 'dataframe-array
285 :storage newdata
286 :nrows (length newcaselabels)
287 :ncols (length newvarlabels)
288 :case-labels newcaselabels
289 :var-labels newvarlabels
290 :var-types vartypes))
291 (matrix-like
292 (make-instance 'dataframe-matrixlike
293 :storage newdata
294 :nrows (length newcaselabels)
295 :ncols (length newvarlabels)
296 :case-labels newcaselabels
297 :var-labels newvarlabels
298 :var-types vartypes))
300 ))))
303 (make-dataframe #2A((1.2d0 1.3d0) (2.0d0 4.0d0)))
304 (make-dataframe #2A(('a 1) ('b 2)))
305 (xref (make-dataframe #2A(('a 1) ('b 2))) 0 1)
306 (xref (make-dataframe #2A(('a 1) ('b 2))) 1 0)
307 (make-dataframe 4) ; ERROR, should we allow?
308 (make-dataframe #2A((4)))
309 (make-dataframe (rand 10 5)) ;; ERROR, but should work!
313 (defun row-order-as-list (ary)
314 "Pull out data in row order into a list."
315 (let ((result (list))
316 (nrows (nth 0 (array-dimensions ary)))
317 (ncols (nth 1 (array-dimensions ary))))
318 (dotimes (i ncols)
319 (dotimes (j nrows)
320 (append result (aref ary i j))))))
322 (defun col-order-as-list (ary)
323 "Pull out data in row order into a list."
324 (let ((result (list))
325 (nrows (nth 0 (array-dimensions ary)))
326 (ncols (nth 1 (array-dimensions ary))))
327 (dotimes (i nrows)
328 (dotimes (j ncols)
329 (append result (aref ary i j))))))
331 (defun transpose-array (ary)
332 "map NxM to MxN."
333 (make-array (reverse (array-dimensions ary))
334 :initial-contents (col-order-as-list ary)))
336 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
337 ;;; possibilities on top of the generic function structure. Not
338 ;;; intended as make-work!
340 (defun varlabels (df)
341 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
342 (var-labels df))
344 (defun set-varlabels (df vl)
345 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
346 (if (= (length (var-labels df))
347 (length vl))
348 (setf (var-labels df) vl)
349 (error "wrong size.")))
351 (defsetf varlabels set-varlabels)
353 ;;; Case-name handling for Tables. Needs error checking.
354 (defun caselabels (df)
355 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
356 (case-labels df))
358 (defun set-caselabels (df cl)
359 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
360 (if (= (length (case-labels df))
361 (length cl))
362 (setf (case-labels df) cl)
363 (error "wrong size.")))
365 (defsetf caselabels set-caselabels)
367 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
368 ;; See also:
369 ;; (documentation 'dataframe-like 'type)
374 ;;; Do we establish methods for dataframe-like, which specialize to
375 ;;; particular instances of storage?
377 (defmethod print-object ((object dataframe-like) stream)
378 (print-unreadable-object (object stream :type t)
379 (format stream " ~d x ~d" (nrows object) (ncols object))
380 (terpri stream)
381 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
382 (dotimes (j (ncols object)) ; print labels
383 (write-char #\tab stream)
384 (write-char #\tab stream)
385 (format stream "~T~A~T" (nth j (var-labels object))))
386 (dotimes (i (nrows object)) ; print obs row
387 (terpri stream)
388 (format stream "~A:~T" (nth i (case-labels object)))
389 (dotimes (j (ncols object))
390 (write-char #\tab stream) ; (write-char #\space stream)
391 ;; (write (xref object i j) :stream stream)
392 (format stream "~7,3E" (xref object i j)) ; if works, need to include a general output mechanism control
393 ))))
396 (defun print-structure-relational (ds)
397 "example of what we want the methods to look like. Should be sort
398 of like a graph of spreadsheets if the storage is a relational
399 structure."
400 (dolist (k (relations ds))
401 (let ((currentRelationSet (getRelation ds k)))
402 (print-as-row (var-labels currentRelationSet))
403 (let ((j -1))
404 (dolist (i (case-labels currentRelationSet))
405 (print-as-row
406 (append (list i)
407 (xref-obsn (dataset currentRelationSet)
408 (incf j)))))))))
410 (defun testecase (s)
411 (ecase s
412 ((scalar) 1)
413 ((asd asdf) 2)))
415 (testecase 'scalar)
416 (testecase 'asd)
417 (testecase 'asdf)
418 (testecase 'as)
422 ;;; Vector-like generalizations: we consider observation-like and
423 ;;; variable-like to be abstract classes which provide row and column
424 ;;; access to dataframe structures. These will be specialized, in
425 ;;; that rows correspond to an observation (or case?) which are
426 ;;; multitype, while columns correspond to a variable, which must be
427 ;;; singularly typed.
429 (defclass observation-like (dataframe-like)
431 (:documentation "dataframe-like with only 1 row, is an observation-like."))
433 (defclass variable-like (dataframe-like)
435 (:documentation "dataframe-like with only 1 column is a variable-like."))
437 ;;; Need to implement views, i.e. dataframe-view-like,
438 ;;; observation-view-like, variable-view-like.
442 ;;; Need to consider read-only variants, leveraging the xref
443 ;;; strategy.
447 ;;; Dataframe <-> Listoflist support
448 ;; the following will be handy to help out folks adjust. It should
449 ;; provide a means to write code faster and better.
451 ;; leverages listoflist support in our version of xarray
452 (defun listoflist->dataframe (lol) ; &key (type :row-major))
453 "Create a cases-by-variables data frame consisting of numeric data,
454 from a ROW-MAJOR list-of-lists representation. A COLUMN-MAJOR
455 representation should be handled using the transpose-listoflists
456 function."
457 (check-type lol list) ; imperfect -- must verify all list elements are also lists.
458 (if (listoflist:sublists-of-same-size-p lol)
459 (make-dataframe (listoflist:listoflist->array lol))
460 (error "make-data-set-from-lists: no combining different length lists"))
461 (error "make-data-set-from-lists: proposed name exists"))
464 ;;;;;;;; from dataframe-xarray experiment
467 (defmethod xref ((obj dataframe-like) &rest subscripts)
468 "For data-frame-like, dispatch on storage object."
469 (xref (dataset obj) subscripts))
471 (defmethod (setf xref) (value (obj dataframe-like) &rest subscripts)
472 (setf (xref (dataset obj) subscripts) value))
474 (defmethod xref ((obj matrix-like) &rest indices))
476 (defmethod xtype ((obj dataframe-like))
477 "Unlike the standard xtype, here we need to return a vector of the
478 types. Vectors can have single types, but arrays have single type.
479 Dataframe-like have multiple types, variable-like single type,
480 case-like has multiple types, and matrix-like has single type.")
482 (defmethod xdims ((obj dataframe-like))
483 (dataframe-dimensions obj))
485 ;; use default methods at this point, except for potentially weird DFs
486 (defmethod xdims* ())
488 (defmethod xdim ((obj dataframe-like) index)
489 (dataframe-dimension index))
492 (defmethod xrank ())
494 (defmethod slice ())
496 (defmethod take ())
498 (defmethod carray ())
500 (defmacro with-dataframe (env &rest progn)
501 "Compute using variable names with with.data.frame type semantics.")
503 (defmacro with-data (body)
504 "Stream-handling, maintaining I/O through object typing.")