moving store and store-class around.
[CommonLispStat.git] / src / data / dataframe.lisp
blob30e889b4270bea238bc537aeb8b2ec34a114853b
1 ;;; -*- mode: lisp -*-
3 ;;; Time-stamp: <2010-01-22 07:53:16 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)
207 (defun ncase-store (store)
208 "Return number of cases (rows) in dataframe storage. Doesn't test
209 that that list is a valid listoflist dataframe structure."
210 (etypecase store
211 (array (array-dimension store 0))
212 (matrix-like (nrows store))
213 (list (length store))))
216 ;; Testing consistency/coherency.
218 (defgeneric consistent-dataframe-p (df)
219 (:documentation "methods to check for consistency. Mostly of
220 internal interest, since ideally we'd have to use standard
221 constructs to ensure that we do not get the dataframe structure
222 misaligned.")
223 (:method (object) "General objects are not consistent dataframes!" nil)
224 (:method ((df dataframe-like))
225 "At minimum, must dispatch on virtual-class."
226 (and
227 ;; ensure dimensionality
228 (= (length (var-labels df)) (ncols df)) ; array-dimensions (dataset df))
229 (= (length (case-labels df)) (nrows df))
230 ;; ensure claimed STORE-CLASS
231 ;; when dims are sane, ensure variable-typing is consistent
232 (progn
233 (dotimes (i (nrows df))
234 (dotimes (j (ncols df))
235 ;; xref bombs if not a df-like subclass so we don't worry
236 ;; about specialization. Need to ensure xref throws a
237 ;; condition we can recover from.
238 ;; (check-type (aref dt i j) (elt lot j)))))) ???
239 (typep (xref df i j) (nth j (var-types df)))))
240 t))))
243 ;;; FUNCTIONS WHICH DISPATCH ON INTERNAL METHODS OR ARGS
245 ;;; Q: change the following to generic functions and dispatch on
246 ;;; array, matrix, and dataframe? Others?
247 (defun make-labels (initstr num)
248 "generate a list of strings which can be used as labels, i.e. something like
249 (make-labels \"a\" 3) => '(\"a1\" \"a2\" \"a3\")."
250 (check-type initstr string)
251 (mapcar #'(lambda (x y) (concatenate 'string x y))
252 (repeat-seq num initstr)
253 (mapcar #'(lambda (x) (format nil "~A" x)) (gen-seq num))))
257 (defun make-dataframe (newdata
258 &key (vartypes nil)
259 (caselabels nil) (varlabels nil)
260 (doc "no docs"))
261 "Helper function to use instead of make-instance to assure
262 construction of proper DF-array."
263 (check-type newdata (or matrix-like array list))
264 (check-type caselabels sequence)
265 (check-type varlabels sequence)
266 (check-type doc string)
267 (let ((ncases (ncases newdata))
268 (nvars (nvars newdata)))
269 (if caselabels (assert (= ncases (length caselabels))))
270 (if varlabels (assert (= nvars (length varlabels))))
271 (let ((newcaselabels (if caselabels
272 caselabels
273 (make-labels "C" ncases)))
274 (newvarlabels (if varlabels
275 varlabels
276 (make-labels "V" nvars))))
277 (etypecase newdata
278 (list
279 (make-instance 'dataframe-listoflist
280 :storage newdata
281 :nrows (length newcaselabels)
282 :ncols (length newvarlabels)
283 :case-labels newcaselabels
284 :var-labels newvarlabels
285 :var-types vartypes))
286 (array
287 (make-instance 'dataframe-array
288 :storage newdata
289 :nrows (length newcaselabels)
290 :ncols (length newvarlabels)
291 :case-labels newcaselabels
292 :var-labels newvarlabels
293 :var-types vartypes))
294 (matrix-like
295 (make-instance 'dataframe-matrixlike
296 :storage newdata
297 :nrows (length newcaselabels)
298 :ncols (length newvarlabels)
299 :case-labels newcaselabels
300 :var-labels newvarlabels
301 :var-types vartypes))
303 ))))
306 (make-dataframe #2A((1.2d0 1.3d0) (2.0d0 4.0d0)))
307 (make-dataframe #2A(('a 1) ('b 2)))
308 (xref (make-dataframe #2A(('a 1) ('b 2))) 0 1)
309 (xref (make-dataframe #2A(('a 1) ('b 2))) 1 0)
310 (make-dataframe 4) ; ERROR, should we allow?
311 (make-dataframe #2A((4)))
312 (make-dataframe (rand 10 5)) ;; ERROR, but should work!
316 (defun row-order-as-list (ary)
317 "Pull out data in row order into a list."
318 (let ((result (list))
319 (nrows (nth 0 (array-dimensions ary)))
320 (ncols (nth 1 (array-dimensions ary))))
321 (dotimes (i ncols)
322 (dotimes (j nrows)
323 (append result (aref ary i j))))))
325 (defun col-order-as-list (ary)
326 "Pull out data in row order into a list."
327 (let ((result (list))
328 (nrows (nth 0 (array-dimensions ary)))
329 (ncols (nth 1 (array-dimensions ary))))
330 (dotimes (i nrows)
331 (dotimes (j ncols)
332 (append result (aref ary i j))))))
334 (defun transpose-array (ary)
335 "map NxM to MxN."
336 (make-array (reverse (array-dimensions ary))
337 :initial-contents (col-order-as-list ary)))
339 ;;; THE FOLLOWING 2 dual-sets done to provide error checking
340 ;;; possibilities on top of the generic function structure. Not
341 ;;; intended as make-work!
343 (defun varlabels (df)
344 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
345 (var-labels df))
347 (defun set-varlabels (df vl)
348 "Variable-name handling for DATAFRAME-LIKE. Needs error checking."
349 (if (= (length (var-labels df))
350 (length vl))
351 (setf (var-labels df) vl)
352 (error "wrong size.")))
354 (defsetf varlabels set-varlabels)
356 ;;; Case-name handling for Tables. Needs error checking.
357 (defun caselabels (df)
358 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
359 (case-labels df))
361 (defun set-caselabels (df cl)
362 "Case-name handling for DATAFRAME-LIKE. Needs error checking."
363 (if (= (length (case-labels df))
364 (length cl))
365 (setf (case-labels df) cl)
366 (error "wrong size.")))
368 (defsetf caselabels set-caselabels)
370 ;;;;;;;;;;;; IMPLEMENTATIONS, with appropriate methods.
371 ;; See also:
372 ;; (documentation 'dataframe-like 'type)
377 ;;; Do we establish methods for dataframe-like, which specialize to
378 ;;; particular instances of storage?
380 (defmethod print-object ((object dataframe-like) stream)
381 (print-unreadable-object (object stream :type t)
382 (format stream " ~d x ~d" (nrows object) (ncols object))
383 (terpri stream)
384 ;; (format stream "~T ~{~S ~T~}" (var-labels object))
385 (dotimes (j (ncols object)) ; print labels
386 (write-char #\tab stream)
387 (write-char #\tab stream)
388 (format stream "~T~A~T" (nth j (var-labels object))))
389 (dotimes (i (nrows object)) ; print obs row
390 (terpri stream)
391 (format stream "~A:~T" (nth i (case-labels object)))
392 (dotimes (j (ncols object))
393 (write-char #\tab stream) ; (write-char #\space stream)
394 ;; (write (xref object i j) :stream stream)
395 (format stream "~7,3E" (xref object i j)) ; if works, need to include a general output mechanism control
396 ))))
399 (defun print-structure-relational (ds)
400 "example of what we want the methods to look like. Should be sort
401 of like a graph of spreadsheets if the storage is a relational
402 structure."
403 (dolist (k (relations ds))
404 (let ((currentRelationSet (getRelation ds k)))
405 (print-as-row (var-labels currentRelationSet))
406 (let ((j -1))
407 (dolist (i (case-labels currentRelationSet))
408 (print-as-row
409 (append (list i)
410 (xref-obsn (dataset currentRelationSet)
411 (incf j)))))))))
413 (defun testecase (s)
414 (ecase s
415 ((scalar) 1)
416 ((asd asdf) 2)))
418 (testecase 'scalar)
419 (testecase 'asd)
420 (testecase 'asdf)
421 (testecase 'as)
425 ;;; Vector-like generalizations: we consider observation-like and
426 ;;; variable-like to be abstract classes which provide row and column
427 ;;; access to dataframe structures. These will be specialized, in
428 ;;; that rows correspond to an observation (or case?) which are
429 ;;; multitype, while columns correspond to a variable, which must be
430 ;;; singularly typed.
432 (defclass observation-like (dataframe-like)
434 (:documentation "dataframe-like with only 1 row, is an observation-like."))
436 (defclass variable-like (dataframe-like)
438 (:documentation "dataframe-like with only 1 column is a variable-like."))
440 ;;; Need to implement views, i.e. dataframe-view-like,
441 ;;; observation-view-like, variable-view-like.
445 ;;; Need to consider read-only variants, leveraging the xref
446 ;;; strategy.
450 ;;; Dataframe <-> Listoflist support
451 ;; the following will be handy to help out folks adjust. It should
452 ;; provide a means to write code faster and better.
454 ;; leverages listoflist support in our version of xarray
455 (defun listoflist->dataframe (lol) ; &key (type :row-major))
456 "Create a cases-by-variables data frame consisting of numeric data,
457 from a ROW-MAJOR list-of-lists representation. A COLUMN-MAJOR
458 representation should be handled using the transpose-listoflists
459 function."
460 (check-type lol list) ; imperfect -- must verify all list elements are also lists.
461 (if (listoflist:sublists-of-same-size-p lol)
462 (make-dataframe (listoflist:listoflist->array lol))
463 (error "make-data-set-from-lists: no combining different length lists"))
464 (error "make-data-set-from-lists: proposed name exists"))
467 ;;;;;;;; from dataframe-xarray experiment
470 (defmethod xref ((obj dataframe-like) &rest subscripts)
471 "For data-frame-like, dispatch on storage object."
472 (xref (dataset obj) subscripts))
474 (defmethod (setf xref) (value (obj dataframe-like) &rest subscripts)
475 (setf (xref (dataset obj) subscripts) value))
477 (defmethod xref ((obj matrix-like) &rest indices))
479 (defmethod xtype ((obj dataframe-like))
480 "Unlike the standard xtype, here we need to return a vector of the
481 types. Vectors can have single types, but arrays have single type.
482 Dataframe-like have multiple types, variable-like single type,
483 case-like has multiple types, and matrix-like has single type.")
485 (defmethod xdims ((obj dataframe-like))
486 (dataframe-dimensions obj))
488 ;; use default methods at this point, except for potentially weird DFs
489 (defmethod xdims* ())
491 (defmethod xdim ((obj dataframe-like) index)
492 (dataframe-dimension index))
495 (defmethod xrank ())
497 (defmethod slice ())
499 (defmethod take ())
501 (defmethod carray ())
503 (defmacro with-dataframe (env &rest progn)
504 "Compute using variable names with with.data.frame type semantics.")
506 (defmacro with-data (body)
507 "Stream-handling, maintaining I/O through object typing.")