Prototype and testing examples.
[CommonLispStat.git] / data.lisp
blobad5e194f85f99423da406235f45f7e7555c66fd9
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 open-file-dialog read-data-file read-data-columns load-data
43 load-example *variables* *ask-on-redefine*
44 def variables savevar undef))
46 (in-package :lisp-stat-data)
48 ;; (deftype dataformtype (list scalar vector sequence list array relation))
49 ;; (deftype datareptype (list integer rational real complex string symbol=
50 ;; (deftype stattzpe (list
55 ;;; The purpose of this package is to manage data which will be
56 ;;; processed by LispStat. In particular, it willbe importnat to
57 ;;; register variables, datasets, relational structures, and other
58 ;;; objects which could be the target for statistical modeling and
59 ;;; inference.
61 (defvar *lisp-stat-data-table* (make-hash-table)
62 "Marks up the data the could be used by.")
64 (defvar *lisp-stat-data-count* 0
65 "number of items currently recorded.")
68 ;;; Data Types:
69 ;;;
70 ;;; Data types are the representation of data from a computer-science
71 ;;; perspective, i.e. what it is that they contain. These types
72 ;;; include particular forms of compound types (i.e. dataframe,
73 ;;; relationdata are compounds of arrays of different types where the
74 ;;; difference is row-wise, while array is a compound of elements of
75 ;;; the same type.
77 ;;Examples:
78 ;; (defun equidimensional (a)
79 ;; (or (< (array-rank a) 2)
80 ;; (apply #'= (array-dimensions a)))) => EQUIDIMENSIONAL
81 ;; (deftype square-matrix (&optional type size)
82 ;; `(and (array ,type (,size ,size))
83 ;; (satisfies equidimensional))) => SQUARE-MATRIX
85 (deftype dt-scalar (&optional type)
86 `(or integer double complex))
88 (deftype dt-array (&optional type)
89 `(satisfies array-of-equal-type))
91 (deftype dt-dataframe ()
92 `(satisfies array-of-equal-type-within-column))
94 (deftype dt-relationaldata ()
95 `(satisfies (foreach unit in relationalUnit
96 (typep unit 'dt-dataframe))))
101 ;;; Statistical Variable Classes
104 (deftype sv-nominal (&optional length)
107 (deftype sv-ordinal (ordering &optional length)
110 (deftype sv-categorical ()
111 `(satisfies (or sv-nominal sv-ordinal)))
112 ;;(deftype sv-integer )
113 ;;(deftype sv-real )
114 ;;(deftype sv-rational )
115 ;;(deftype sv-complex )
116 ;;(deftype sv-continuous (or 'sv-integer 'sv-real 'sv-rational 'sv-complex))
121 ;;; Data I/O
123 ;; We can read 2 types of data -- those which are pure data, and those
124 ;; which are imprue (lisp-enables).
126 (defparameter *lisp-stat-data-formats*
127 '(csv tsv))
129 ;; (defgeneric data-read (srce frmt)
130 ;; "read data from stream srce, in format frmt.")
132 ;; (defgeneric data-write (srce frmt)
133 ;; "read data from stream srce, in format frmt.")
135 ;; (defmacro with-data (body)
136 ;; "Stream-handling, maintaining I/O through object typing.")
138 ;; design-wise should these be replaced with a "with-data" form?
141 ;; DSV processing
143 ;; XML processing
145 ;;; Data Management
147 ;; the goal is to have 2 operations which can be used to create new
148 ;; data formats out of old ones.
150 ;; (defgeneric data-subset (ds description)
151 ;; "Take a dataset and make it smaller.")
153 ;; (defgeneric data-relate (ds description)
154 ;; "Take 2 or more datasets, and grow them into a bigger one through
155 ;; relating them (i.e. merge is one example).")
157 ;;; Data tools from "statistics.lsp"
159 ;;;;
160 ;;;; Data File Reading
161 ;;;;
163 (defun count-file-columns (fname)
164 "Args: (fname)
165 Returns the number of lisp items on the first nonblank line of file FNAME."
166 (with-open-file (f fname)
167 (if f
168 (let ((line (do ((line (read-line f) (read-line f)))
169 ((or (null line) (< 0 (length line))) line))))
170 (if line
171 (with-input-from-string (s line)
172 (do ((n 0 (+ n 1)) (eof (gensym)))
173 ((eq eof (read s nil eof)) n))))))))
175 #+xlisp (defvar *xlisptable* *readtable*)
177 (if (not (fboundp 'open-file-dialog))
178 #+dialogs
179 (defun open-file-dialog () ;; why?(&optional set)
180 (get-string-dialog "Enter a data file name:"))
181 #-dialogs
182 (defun open-file-dialog () ;; why? (&optional set)
183 (error "You must provide a file name explicitly")))
185 (defun read-data-file (&optional (file (open-file-dialog t)))
186 "Args: (file)
187 Returns a list of all lisp objects in FILE. FILE can be a string or a symbol,
188 in which case the symbol'f print name is used."
189 (if file
190 (let ((eof (gensym)))
191 (with-open-file (f file)
192 (if f
193 (do* ((r (read f nil eof) (read f nil eof))
194 (x (list nil))
195 (tail x (cdr tail)))
196 ((eq r eof) (cdr x))
197 (setf (cdr tail) (list r))))))))
199 ;;; New definition to avoid stack size limit in apply
200 (defun read-data-columns (&optional (file (open-file-dialog t))
201 (cols (if file
202 (count-file-columns file))))
203 "Args: (&optional file cols)
204 Reads the data in FILE as COLS columns and returns a list of lists representing the columns."
205 (if (and file cols)
206 (transpose (split-list (read-data-file file) cols))))
209 ;;; FIXME:AJR: ALL THE FOLLOWING NEED TO BE SOLVED BY PLATFORM-INDEP PATHNAME WORK!
210 ;;; FIXME:AJR: use either string or pathname.
212 (defun path-string-to-path (p s)
213 (pathname (concatenate 'string (namestring p) s)))
215 (defun load-data (file)
216 "Args: (file) as string
217 Read in data file from the data examples library."
218 (if (load (path-string-to-path *lispstat-data-dir* file))
220 (load (path-string-to-path *lispstat-examples-dir* file))))
222 (defun load-example (file)
223 "Args: (file) as string
224 Read in lisp example file from the examples library."
225 (if (load (path-string-to-path *lispstat-examples-dir* file))
227 (load (path-string-to-path *lispstat-data-dir* file))))
229 ;;;;
230 ;;;; Listing and Saving Variables and Functions
231 ;;;;
233 (defvar *variables* nil)
234 (defvar *ask-on-redefine* nil)
236 (defmacro def (symbol value)
237 "Syntax: (def var form)
238 VAR is not evaluated and must be a symbol. Assigns the value of FORM to
239 VAR and adds VAR to the list *VARIABLES* of def'ed variables. Returns VAR.
240 If VAR is already bound and the global variable *ASK-ON-REDEFINE*
241 is not nil then you are asked if you want to redefine the variable."
242 `(unless (and *ask-on-redefine*
243 (boundp ',symbol)
244 (not (y-or-n-p "Variable has a value. Redefine?")))
245 (pushnew ',symbol *variables*)
246 (setf ,symbol ,value)
247 ',symbol))
249 (defun variables-list ()
250 (mapcar #'intern (sort-data (mapcar #'string *variables*))))
252 (defun variables ()
253 "Args:()
254 Returns a list of the names of all def'ed variables to STREAM"
255 (if *variables*
256 (mapcar #'intern (sort-data (mapcar #'string *variables*)))))
258 (defun savevar (vars file)
259 "Args: (vars file-name-root)
260 VARS is a symbol or a list of symbols. FILE-NAME-ROOT is a string (or a symbol
261 whose print name is used) not endinf in .lsp. The VARS and their current values
262 are written to the file FILE-NAME-ROOT.lsp in a form suitable for use with the
263 load command."
264 (with-open-file (f (concatenate 'string (namestring file) ".lsp")
265 :direction :output)
266 (let ((vars (if (consp vars) vars (list vars))))
267 (flet ((save-one (x)
268 (let ((v (symbol-value x)))
269 (if (objectp v)
270 (format f "(def ~s ~s)~%" x (send v :save))
271 (format f "(def ~s '~s)~%" x v)))))
272 (mapcar #'save-one vars))
273 vars)))
275 (defun undef (v)
276 "Args: (v)
277 If V is the symbol of a defined variable the variable it is unbound and
278 removed from the list of defined variables. If V is a list of variable
279 names each is unbound and removed. Returns V."
280 (dolist (s (if (listp v) v (list v)))
281 (when (member s *variables*)
282 (setq *variables* (delete s *variables*))
283 (makunbound s)))