remove dependencies. documentation cleanup.
[CommonLispStat.git] / data.lisp
blob7962d53c4caf4d8c47326e839cf6a4ba18286b03
1 ;;; -*- mode: lisp -*-
2 ;;; Copyright (c) 2005--2007, by A.J. Rossini <blindglobe@gmail.com>
3 ;;; See COPYRIGHT file for any additional restrictions (BSD license).
4 ;;; Since 1991, ANSI was finally finished. Edited for ANSI Common Lisp.
6 ;;; File: data.lisp
7 ;;; Author: AJ Rossini <blindglobe@gmail.com>
8 ;;; Copyright: (c)2007, AJ Rossini. BSD, LLGPL, or GPLv2, depending on how it arrives.
9 ;;; Purpose: data package for lispstat
10 ;;; Time-stamp: <2006-05-19 12:33:41 rossini>
11 ;;; Creation: <2006-05-17 21:34:07 rossini>
13 ;;; What is this talk of 'release'? Klingons do not make software
14 ;;; 'releases'. Our software 'escapes', leaving a bloody trail of
15 ;;; designers and quality assurance people in its wake.
17 ;;; This organization and structure is new to the 21st Century
18 ;;; version.
20 ;;; conside that dataa has 3 genotypic chracteristrics. The first
21 ;;; would be form -- scalar, vector, array. second would be
22 ;;; datarep type. in particular integer, real, string, symbol. The last
23 ;;; would be statistical type. augmenting datarep type with use in a
24 ;;; statistical context, i.e. that would include nominal, ordinal,
25 ;;; integer, continous, interval (orderable subtypes)
27 (in-package :cl-user)
29 (defpackage :lisp-stat-data
30 (:documentation "Data I/O, management, other data technologies.")
31 (:nicknames :ls-data)
32 (:use :common-lisp
33 ;;:cxml
34 :lisp-stat-config
35 :lisp-stat-object-system
36 :lisp-stat-types
37 :lisp-stat-compound-data
38 :lisp-stat-matrix
39 :lisp-stat-linalg)
40 (:shadowing-import-from :lisp-stat-object-system
41 slot-value call-method call-next-method)
42 (:export
43 ;;; from statistics.lsp
44 open-file-dialog read-data-file read-data-columns load-data
45 load-example *variables* *ask-on-redefine* def variables savevar
46 undef split-list ))
48 (in-package :lisp-stat-data)
50 ;; (deftype dataformtype (list scalar vector sequence list array relation))
51 ;; (deftype datareptype (list integer rational real complex string symbol=
52 ;; (deftype stattzpe (list
57 ;;; The purpose of this package is to manage data which will be
58 ;;; processed by LispStat. In particular, it willbe importnat to
59 ;;; register variables, datasets, relational structures, and other
60 ;;; objects which could be the target for statistical modeling and
61 ;;; inference.
63 (defvar *lisp-stat-data-table* (make-hash-table)
64 "Marks up the data the could be used by.")
66 (defvar *lisp-stat-data-count* 0
67 "number of items currently recorded.")
70 ;;; Data Types:
71 ;;;
72 ;;; Data types are the representation of data from a computer-science
73 ;;; perspective, i.e. what it is that they contain. These types
74 ;;; include particular forms of compound types (i.e. dataframe,
75 ;;; relationdata are compounds of arrays of different types where the
76 ;;; difference is row-wise, while array is a compound of elements of
77 ;;; the same type.
79 ;;Examples:
80 ;; (defun equidimensional (a)
81 ;; (or (< (array-rank a) 2)
82 ;; (apply #'= (array-dimensions a)))) => EQUIDIMENSIONAL
83 ;; (deftype square-matrix (&optional type size)
84 ;; `(and (array ,type (,size ,size))
85 ;; (satisfies equidimensional))) => SQUARE-MATRIX
87 (deftype dt-scalar (&optional type)
88 `(or integer double complex))
90 (deftype dt-array (&optional type)
91 `(satisfies array-of-equal-type))
93 (deftype dt-dataframe ()
94 `(satisfies array-of-equal-type-within-column))
96 (deftype dt-relationaldata ()
97 `(satisfies (foreach unit in relationalUnit
98 (typep unit 'dt-dataframe))))
103 ;;; Statistical Variable Classes
106 (deftype sv-nominal (&optional length)
109 (deftype sv-ordinal (ordering &optional length)
112 (deftype sv-categorical ()
113 `(satisfies (or sv-nominal sv-ordinal)))
114 ;;(deftype sv-integer )
115 ;;(deftype sv-real )
116 ;;(deftype sv-rational )
117 ;;(deftype sv-complex )
118 ;;(deftype sv-continuous (or 'sv-integer 'sv-real 'sv-rational 'sv-complex))
123 ;;; Data I/O
125 ;; We can read 2 types of data -- those which are pure data, and those
126 ;; which are imprue (lisp-enables).
128 (defparameter *lisp-stat-data-formats*
129 '(csv tsv))
131 ;; (defgeneric data-read (srce frmt)
132 ;; "read data from stream srce, in format frmt.")
134 ;; (defgeneric data-write (srce frmt)
135 ;; "read data from stream srce, in format frmt.")
137 ;; (defmacro with-data (body)
138 ;; "Stream-handling, maintaining I/O through object typing.")
140 ;; design-wise should these be replaced with a "with-data" form?
143 ;; DSV processing
145 ;; XML processing
147 ;;; Data Management
149 ;; the goal is to have 2 operations which can be used to create new
150 ;; data formats out of old ones.
152 ;; (defgeneric data-subset (ds description)
153 ;; "Take a dataset and make it smaller.")
155 ;; (defgeneric data-relate (ds description)
156 ;; "Take 2 or more datasets, and grow them into a bigger one through
157 ;; relating them (i.e. merge is one example).")
159 ;;; Data tools from "statistics.lsp"
161 ;;;;
162 ;;;; Data File Reading
163 ;;;;
165 (defun count-file-columns (fname)
166 "Args: (fname)
167 Returns the number of lisp items on the first nonblank line of file FNAME."
168 (with-open-file (f fname)
169 (if f
170 (let ((line (do ((line (read-line f) (read-line f)))
171 ((or (null line) (< 0 (length line))) line))))
172 (if line
173 (with-input-from-string (s line)
174 (do ((n 0 (+ n 1)) (eof (gensym)))
175 ((eq eof (read s nil eof)) n))))))))
177 #+xlisp (defvar *xlisptable* *readtable*)
179 (if (not (fboundp 'open-file-dialog))
180 #+dialogs
181 (defun open-file-dialog () ;; why?(&optional set)
182 (get-string-dialog "Enter a data file name:"))
183 #-dialogs
184 (defun open-file-dialog () ;; why? (&optional set)
185 (error "You must provide a file name explicitly")))
187 (defun read-data-file (&optional (file (open-file-dialog t)))
188 "Args: (file)
189 Returns a list of all lisp objects in FILE. FILE can be a string or a symbol,
190 in which case the symbol'f print name is used."
191 (if file
192 (let ((eof (gensym)))
193 (with-open-file (f file)
194 (if f
195 (do* ((r (read f nil eof) (read f nil eof))
196 (x (list nil))
197 (tail x (cdr tail)))
198 ((eq r eof) (cdr x))
199 (setf (cdr tail) (list r))))))))
201 ;;; New definition to avoid stack size limit in apply
202 (defun read-data-columns (&optional (file (open-file-dialog t))
203 (cols (if file
204 (count-file-columns file))))
205 "Args: (&optional file cols)
206 Reads the data in FILE as COLS columns and returns a list of lists representing the columns."
207 (if (and file cols)
208 (transpose (split-list (read-data-file file) cols))))
211 ;;; FIXME:AJR: ALL THE FOLLOWING NEED TO BE SOLVED BY PLATFORM-INDEP PATHNAME WORK!
212 ;;; FIXME:AJR: use either string or pathname.
214 (defun path-string-to-path (p s)
215 (pathname (concatenate 'string (namestring p) s)))
217 (defun load-data (file)
218 "Args: (file) as string
219 Read in data file from the data examples library."
220 (if (load (path-string-to-path *lispstat-data-dir* file))
222 (load (path-string-to-path *lispstat-examples-dir* file))))
224 (defun load-example (file)
225 "Args: (file) as string
226 Read in lisp example file from the examples library."
227 (if (load (path-string-to-path *lispstat-examples-dir* file))
229 (load (path-string-to-path *lispstat-data-dir* file))))
231 ;;;;
232 ;;;; Listing and Saving Variables and Functions
233 ;;;;
235 (defvar *variables* nil)
236 (defvar *ask-on-redefine* nil)
238 (defmacro def (symbol value)
239 "Syntax: (def var form)
240 VAR is not evaluated and must be a symbol. Assigns the value of FORM to
241 VAR and adds VAR to the list *VARIABLES* of def'ed variables. Returns VAR.
242 If VAR is already bound and the global variable *ASK-ON-REDEFINE*
243 is not nil then you are asked if you want to redefine the variable."
244 `(unless (and *ask-on-redefine*
245 (boundp ',symbol)
246 (not (y-or-n-p "Variable has a value. Redefine?")))
247 (pushnew ',symbol *variables*)
248 (setf ,symbol ,value)
249 ',symbol))
251 (defun variables-list ()
252 (mapcar #'intern (sort-data (mapcar #'string *variables*))))
254 (defun variables ()
255 "Args:()
256 Returns a list of the names of all def'ed variables to STREAM"
257 (if *variables*
258 (mapcar #'intern (sort-data (mapcar #'string *variables*)))))
260 (defun savevar (vars file)
261 "Args: (vars file-name-root)
262 VARS is a symbol or a list of symbols. FILE-NAME-ROOT is a string (or a symbol
263 whose print name is used) not endinf in .lsp. The VARS and their current values
264 are written to the file FILE-NAME-ROOT.lsp in a form suitable for use with the
265 load command."
266 (with-open-file (f (concatenate 'string (namestring file) ".lsp")
267 :direction :output)
268 (let ((vars (if (consp vars) vars (list vars))))
269 (flet ((save-one (x)
270 (let ((v (symbol-value x)))
271 (if (objectp v)
272 (format f "(def ~s ~s)~%" x (send v :save))
273 (format f "(def ~s '~s)~%" x v)))))
274 (mapcar #'save-one vars))
275 vars)))
277 (defun undef (v)
278 "Args: (v)
279 If V is the symbol of a defined variable the variable it is unbound and
280 removed from the list of defined variables. If V is a list of variable
281 names each is unbound and removed. Returns V."
282 (dolist (s (if (listp v) v (list v)))
283 (when (member s *variables*)
284 (setq *variables* (delete s *variables*))
285 (makunbound s)))
288 ;;;;
289 ;;;; Miscellaneous Routines
290 ;;;;
292 (defun split-list (x n)
293 "Args: (list cols)
294 Returns a list of COLS lists of equal length of the elements of LIST.
295 Example: (split-list '(1 2 3 4 5 6) 2) returns ((1 2 3) (4 5 6))"
296 (check-one-fixnum n)
297 (if (/= (rem (length x) n) 0) (error "length not divisible by ~a" n))
298 (flet ((next-split ()
299 (let ((result nil)
300 (end nil))
301 (dotimes (i n result)
302 (declare (fixnum i))
303 (let ((c-elem (list (first x))))
304 (cond ((null result)
305 (setf result c-elem)
306 (setf end result))
308 (setf (rest end) c-elem)
309 (setf end (rest end)))))
310 (setf x (rest x))))))
311 (let ((result nil)
312 (end nil)
313 (k (/ (length x) n)))
314 (declare (fixnum k))
315 (dotimes (i k result)
316 (declare (fixnum i))
317 (let ((c-sub (list (next-split))))
318 (cond ((null result)
319 (setf result c-sub)
320 (setf end result))
322 (setf (rest end) c-sub)
323 (setf end (rest end)))))))))