compiles without errors, using nop message.
[CommonLispStat.git] / data-clos.lisp
blobd9558182d1e153bfba3e87e0275c553d8539b36e
1 ;;; -*- mode: lisp -*-
3 ;;; File: data-clos.lisp
4 ;;; Author: AJ Rossini <blindglobe@gmail.com>
5 ;;; Copyright: (c)2008, AJ Rossini. BSD, LLGPL, or GPLv2, depending
6 ;;; on how it arrives.
7 ;;; Purpose: data package for lispstat
8 ;;; Time-stamp: <2008-03-12 17:18:42 user>
9 ;;; Creation: <2008-03-12 17:18:42 user>
11 ;;; What is this talk of 'release'? Klingons do not make software
12 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
13 ;;; designers and quality assurance people in its wake.
15 ;;; This organization and structure is new to the 21st Century
16 ;;; version.
18 ;;; data-clos.lisp
19 ;;;
20 ;;; redoing data structures in a CLOS based framework.
21 ;;;
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
25 ;;; vectors,for example. "column" vectors are related observations
26 ;;; (by measure/recording) while "row" vectors are related readings
27 ;;; (by case)
28 ;;;
30 ;;; Relational structure -- can we capture a completely unnormalized
31 ;;; data strucutre to propose possible modeling approaches, and
32 ;;; propose appropriate models and inferential strategies?
33 ;;;
35 ;; verb-driven schema for data collection. Should encode independence
36 ;; or lack of when possible.
38 #+nil(progn
39 (def-statschema MyDB
40 :tables (list (list t1 )
41 (list t2 )
42 (list t4 ))
43 :unique-key key
44 :stat-relation '(t1 (:nest-within t2) (:nest-within t3))
45 :))
49 (in-package :cl-user)
51 (defpackage :lisp-stat-data-clos
52 (:use :common-lisp
53 ;;:clem
55 (:export statistical-dataset ;; primary class for working.
57 modifyData ;; metadata mods
58 importData ;; get it in
59 reshapeData ;; data mods
61 consistent-statistical-dataset-p
62 varNames caseNames ;; metadata explicit modifiers
64 extract
65 ;; and later, we remove the following, exposing only
66 ;; through the above method.
67 extract-1 extract-row extract-col extract-idx
70 (in-package :lisp-stat-data-clos)
72 ;; Need to figure out typed vectors. We then map a series of typed
73 ;; vectors over to tables where columns are equal typed. In a sense,
74 ;; this is a relation (1-1) of equal-typed arrays. For the most part,
75 ;; this ends up making the R data.frame into a relational building
76 ;; block (considering 1-1 mappings using row ID as a relation).
77 ;; Is this a worthwhile generalization?
79 (defclass statistical-dataset ()
80 ((store :initform nil
81 :initarg :storage
82 :accessor dataset
83 :documentation "Data storage slot. Should be an array or a
84 relation,")
85 (documentation-string :initform nil
86 :initarg :doc
87 :accessor doc-string
88 :documentation "Information about statistical-dataset.")
89 (case-labels :initform nil
90 :initarg :case-labels
91 :accessor case-labels
92 :documentation "labels used for describing cases (doc
93 metadata), possibly used for merging.")
94 (var-labels :initform nil
95 :initarg :var-labels
96 :accessor var-labels
97 :documentation "Variable names."))
98 (:documentation "Standard Cases by Variables Statistical-Dataset."))
101 ;; statistical-dataset is the basic cases by variables framework.
102 ;; Need to embed this within other structures which allow for
103 ;; generalized relations. Goal is to ensure that relations imply and
104 ;; drive the potential for statistical relativeness such as
105 ;; correlation, interference, and similar concepts.
107 ;; Actions on a statistical data structure.
110 (defgeneric consistent-statistical-dataset-p (ds)
111 (:documentation "methods to check for consistency."))
113 (defmethod consistent-statistical-dataset-p ((ds statistical-dataset))
114 "Test that statistical-dataset is internally consistent with metadata.
115 Ensure that dims of stored data are same as case and var labels."
116 (equal (array-dimensions (dataset ds))
117 (list (length (var-labels ds))
118 (length (case-labels ds)))))
120 ;;; Extraction
122 (defun extract-1 (sds idx1 idx2)
123 "Returns a scalar."
124 (aref (dataset sds) idx1 idx2))
126 (defun extract-1-as-sds (sds idx1 idx2)
127 "Need a version which returns a dataset."
128 (make-instance 'statistical-dataset
129 :storage (make-array
130 (list 1 1)
131 :initial-contents (extract-1 sds idx1 idx2))
132 ;; ensure copy for this and following
133 :doc (doc-string sds)
134 :case-labels (caseNames sds)
135 :var-labels (varNames sds)))
137 (defun gen-seq (n &optional (start 1))
138 "There has to be a better way -- I'm sure of it! Always count from 1."
139 (if (>= n start)
140 (append (gen-seq (- n 1) start) (list n))))
141 ;; (gen-seq 4)
142 ;; => (1 2 3 4)
143 ;; (gen-seq 0)
144 ;; => nil
145 ;; (gen-seq 5 3)
146 ;; => 3 4 5
149 (defun extract-col (sds index)
150 "Returns data as sequence."
151 (map 'sequence
152 #'(lambda (x) (extract-1 sds index x))
153 (gen-seq (nth 2 (array-dimensions (dataset sds))))))
155 (defun extract-col-as-sds (sds index)
156 "Returns data as SDS, copied."
157 (map 'sequence
158 #'(lambda (x) (extract-1 sds index x))
159 (gen-seq (nth 2 (array-dimensions (dataset sds))))))
161 (defun extract-row (sds index)
162 "Returns row as sequence."
163 (map 'sequence
164 #'(lambda (x) (extract-1 sds x index))
165 (gen-seq (nth 1 (array-dimensions (dataset sds))))))
167 (defun extract-idx (sds idx1Lst idx2Lst)
168 "return an array, row X col dims. FIXME TESTME"
169 (let ((my-pre-array (list)))
170 (dolist (x idx1Lst)
171 (dolist (y idx2Lst)
172 (append my-pre-array (extract-1 sds x y))))
173 (make-array (list (length idx1Lst) (length idx2Lst))
174 :initial-contents my-pre-array)))
177 (defun extract-idx-sds (sds idx1Lst idx2Lst)
178 "return a dataset encapsulated version of extract-idx."
179 (make-instance 'statistical-dataset
180 :storage (make-array
181 (list (length idx1Lst) (length idx2Lst))
182 :initial-contents (dataset sds))
183 ;; ensure copy for this and following
184 :doc (doc-string sds)
185 :case-labels (caseNames sds)
186 :var-labels (varNames sds)))
188 (defgeneric extract (sds whatAndRange)
189 (:documentation "data extraction approach"))
191 ;;; Printing methods and support.
193 (defun print-as-row (seq)
194 "Print a sequence formated as a row in a table."
195 (format t "~{~D~T~}" seq))
197 ;; (print-as-row (list 1 2 3))
199 (defun print-structure-table (ds)
200 "example of what we want the methods to look like. Should be sort
201 of like a spreadsheet if the storage is a table."
202 (print-as-row (var-labels ds))
203 (let ((j -1))
204 (dolist (i (case-labels ds))
205 (print-as-row (append (list i)
206 (extract-row (dataset ds) (incf j)))))))
209 (defun print-structure-relational (ds)
210 "example of what we want the methods to look like. Should be sort
211 of like a graph of spreadsheets if the storage is a relational
212 structure."
213 (dolist (k (relations ds))
214 (let ((currentRelationSet (getRelation ds k)))
215 (print-as-row (var-labels currentRelationSet))
216 (let ((j -1))
217 (dolist (i (case-labels currentRelationSet))
218 (print-as-row
219 (append (list i)
220 (extract-row (dataset currentRelationSet)
221 (incf j)))))))))
225 ;;; Shaping for computation
227 (defgeneric reshapeData (dataform into-form as-copy)
228 (:documentation "pulling data into a new form"))
230 (defmethod reshapeData ((sds statistical-dataset) what into-form))
232 (defmethod reshapeData ((ds array) (sp list) copy-p)
233 "Array via specList specialization: similar to the common R
234 approaches to redistribution.")
236 (defclass data-format () ())
238 (defun row-order-as-list (ary)
239 "Pull out data in row order into a list."
240 (let ((result (list))
241 (nrows (nth 0 (array-dimensions ary)))
242 (ncols (nth 1 (array-dimensions ary))))
243 (dotimes (i ncols)
244 (dotimes (j nrows)
245 (nappend result (aref ary i j))))))
247 (defun col-order-as-list (ary)
248 "Pull out data in row order into a list."
249 (let ((result (list))
250 (nrows (nth 0 (array-dimensions ary)))
251 (ncols (nth 1 (array-dimensions ary))))
252 (dotimes (i nrows)
253 (dotimes (j ncols)
254 (nappend result (aref ary i j))))))
256 (defun transpose (ary)
257 "map NxM to MxN."
258 (make-array (reverse (array-dimensions ary))
259 :initial-contents (col-order-as-list ary)))
262 ;;; verbs vs semantics for dt conversion -- consider the possibily of
263 ;;; how adverbs and verbs relate, where to put which semantically to
264 ;;; allow for general approach.
266 ;;; eg. Kasper's talk on the FUSION collection of parsers.
273 ;;; Need to consider modification APIs
274 ;;; actions are:
275 ;;; - import
276 ;;; - get/set row names (case names)
277 ;;; - column names (variable names)
278 ;;; - dataset values
279 ;;; - annotation/metadata
280 ;;; - make sure that we do coherency checking in the exported
281 ;;; - functions.
282 ;;; - ...
283 ;;; - reshapeData/reformat/reshapr a reformed version of the dataset (no
284 ;;; additional input).
285 ;;; - either overwriting or not, i.e. with or without copy.
286 ;;; - check consistency of resulting data with metadata and related
287 ;;; data information.
288 ;;; -
290 ;;; Variable-name handling for Tables. Needs error checking.
291 (defun varNames (ds)
292 (var-labels ds))
294 (defun set-varNames (ds vN)
295 (if (= (length (var-labels ds))
296 (length vN))
297 (setf (var-labels ds) vN)
298 (error "wrong size.")))
300 (defsetf varNames set-varNames)
302 ;;; Case-name handling for Tables. Needs error checking.
303 (defun caseNames (ds)
304 (case-labels ds))
306 (defun set-caseNames (ds vN)
307 (if (= (length (case-labels ds))
308 (length vN))
309 (setf (case-labels ds) vN)
310 (error "wrong size.")))
312 (defsetf caseNames set-caseNames)
314 ;;; General modification approaches.
316 (defgeneric importData (source featureList)
317 (:documentation "command to get data into CLS. Specific methods
318 will need to handle pathnames, internal data structures, and
319 external services such as DBMS's. We would like to be able to do
320 thinks like:
321 (importData MyPathName '(:formattype 'csvString))
322 (importData '(sqlConnection :server host.domain.net :port 666)
323 '(:formattype 'table
324 and so on."))
327 (defun pathname-example (name)
328 (let ((my-path (parse-namestring name)))
329 (values (pathname-name my-path :case :common)
330 (pathname-name my-path :case :local))))
332 (defvar sourceTypes (list 'csv 'lisp 'tsv 'special)
333 "list of possible symbols.
335 Thsees are used to specify source formats that might be supported for
336 input. CSV and TSV are standard, LISP refers to forms, and SPECIAL
337 refers to a FUNCTION which parses as appropriately.")
339 ;;; WRONG LOGIC.
340 (defmethod importData ((fileHandle pathname)
341 (fmt list)) ;sourceTypes))
342 "File-based input for data.
343 Usually used by:
344 (importData (parse-namestring 'path/to/file')
345 (list :format 'csv))
347 (importData myPathName (list :format 'lisp))
349 (let* ((fmtType (getf fmt :format))
350 (newData (getDataAsLists fileHandle fmtType)))
351 (case fmtType
352 ('csv ( ))
353 ('tsv ( ))
354 ('lisp ( ))
355 ('special (let ((parserFcn (getf fmt :special-parser)))))
356 (:default (error "no standard default importData format")))))
358 (defmethod importData ((ds array) (fmt list))
359 "mapping arrays into CLS data.")
361 (defmethod importData ((dsSpec DBMSandSQLextract)
362 (fmt mappingTypes))
363 "mapping DBMS into CLS data.")
367 ;;(defmacro with-dataframe (env &rest progn)
368 ;; "Compute using variable names with with.data.frame type semantics.")