definition order mattered for compile, not sure why.
[CommonLispStat.git] / data.lisp
blob74bf1aa1da9c2f7cc081f3e261fceb5763b341b6
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))))
99 ;;; Statistical Variable Classes
102 (deftype sv-nominal (&optional length)
105 (deftype sv-ordinal (ordering &optional length)
108 (deftype sv-categorical ()
109 `(satisfies (or sv-nominal sv-ordinal)))
110 ;;(deftype sv-integer )
111 ;;(deftype sv-real ) ;; precision could be a secondary component of real, rational, complex.
112 ;;(deftype sv-rational )
113 ;;(deftype sv-complex )
114 ;;(deftype sv-continuous (or 'sv-integer 'sv-real 'sv-rational 'sv-complex)) ;; perhaps, call it "mostly contin..."
119 ;;; Data I/O
121 ;; We can read 2 types of data -- those which are pure data, and those
122 ;; which are impure (lisp-enabled, data as program as data thingy's).
124 (defparameter *lisp-stat-data-formats*
125 '(csv tsv))
127 ;; (defgeneric data-read (srce frmt)
128 ;; "read data from stream srce, in format frmt.")
130 ;; (defgeneric data-write (srce frmt)
131 ;; "read data from stream srce, in format frmt.")
133 ;; (defmacro with-data (body)
134 ;; "Stream-handling, maintaining I/O through object typing.")
136 ;; design-wise should these be replaced with a "with-data" form?
138 ;; DSV processing
140 ;; XML processing
142 ;;; Data Management
144 ;; the goal is to have 2 operations which can be used to create new
145 ;; data formats out of old ones.
147 ;; (defgeneric data-subset (ds description)
148 ;; "Take a dataset and make it smaller.")
150 ;; (defgeneric data-relate (ds description)
151 ;; "Take 2 or more datasets, and grow them into a bigger one through
152 ;; relating them (i.e. merge is one example).")
154 ;;; Data tools from "statistics.lsp"
156 ;;;;
157 ;;;; Data File Reading
158 ;;;;
160 (defun count-file-columns (fname)
161 "Args: (fname)
162 Returns the number of lisp items on the first nonblank line of file FNAME."
163 (with-open-file (f fname)
164 (if f
165 (let ((line (do ((line (read-line f) (read-line f)))
166 ((or (null line) (< 0 (length line))) line))))
167 (if line
168 (with-input-from-string (s line)
169 (do ((n 0 (+ n 1)) (eof (gensym)))
170 ((eq eof (read s nil eof)) n))))))))
172 #+xlisp (defvar *xlisptable* *readtable*)
174 (if (not (fboundp 'open-file-dialog))
175 #+dialogs
176 (defun open-file-dialog () ;; why?(&optional set)
177 (get-string-dialog "Enter a data file name:"))
178 #-dialogs
179 (defun open-file-dialog () ;; why? (&optional set)
180 (error "You must provide a file name explicitly")))
182 (defun read-data-file (&optional (file (open-file-dialog t)))
183 "Args: (file)
184 Returns a list of all lisp objects in FILE. FILE can be a string or a symbol,
185 in which case the symbol'f print name is used."
186 (if file
187 (let ((eof (gensym)))
188 (with-open-file (f file)
189 (if f
190 (do* ((r (read f nil eof) (read f nil eof))
191 (x (list nil))
192 (tail x (cdr tail)))
193 ((eq r eof) (cdr x))
194 (setf (cdr tail) (list r))))))))
196 ;;; New definition to avoid stack size limit in apply
197 (defun read-data-columns (&optional (file (open-file-dialog t))
198 (cols (if file
199 (count-file-columns file))))
200 "Args: (&optional file cols)
201 Reads the data in FILE as COLS columns and returns a list of lists representing the columns."
202 (if (and file cols)
203 (transpose (split-list (read-data-file file) cols))))
206 ;;; FIXME:AJR: ALL THE FOLLOWING NEED TO BE SOLVED BY PLATFORM-INDEP PATHNAME WORK!
207 ;;; FIXME:AJR: use either string or pathname.
209 (defun path-string-to-path (p s)
210 (pathname (concatenate 'string (namestring p) s)))
212 (defun load-data (file)
213 "Args: (file) as string
214 Read in data file from the data examples library."
215 (if (load (path-string-to-path *lispstat-data-dir* file))
217 (load (path-string-to-path *lispstat-examples-dir* file))))
219 (defun load-example (file)
220 "Args: (file) as string
221 Read in lisp example file from the examples library."
222 (if (load (path-string-to-path *lispstat-examples-dir* file))
224 (load (path-string-to-path *lispstat-data-dir* file))))
226 ;;;;
227 ;;;; Listing and Saving Variables and Functions
228 ;;;;
230 (defvar *variables* nil)
231 (defvar *ask-on-redefine* nil)
233 (defmacro def (symbol value)
234 "Syntax: (def var form)
235 VAR is not evaluated and must be a symbol. Assigns the value of FORM to
236 VAR and adds VAR to the list *VARIABLES* of def'ed variables. Returns VAR.
237 If VAR is already bound and the global variable *ASK-ON-REDEFINE*
238 is not nil then you are asked if you want to redefine the variable."
239 `(unless (and *ask-on-redefine*
240 (boundp ',symbol)
241 (not (y-or-n-p "Variable has a value. Redefine?")))
242 (if (boundp ',symbol)
243 (setf ,symbol ,value)
244 (defvar ,symbol ,value))
245 (pushnew ',symbol *variables*)
246 ',symbol))
248 (defun variables-list ()
249 (mapcar #'intern (sort-data (mapcar #'string *variables*))))
251 (defun variables ()
252 "Args:()
253 Returns a list of the names of all def'ed variables to STREAM"
254 (if *variables*
255 (mapcar #'intern (sort-data (mapcar #'string *variables*)))))
257 (defun savevar (vars file)
258 "Args: (vars file-name-root)
259 VARS is a symbol or a list of symbols. FILE-NAME-ROOT is a string (or a symbol
260 whose print name is used) not endinf in .lsp. The VARS and their current values
261 are written to the file FILE-NAME-ROOT.lsp in a form suitable for use with the
262 load command."
263 (with-open-file (f (concatenate 'string (namestring file) ".lsp")
264 :direction :output)
265 (let ((vars (if (consp vars) vars (list vars))))
266 (flet ((save-one (x)
267 (let ((v (symbol-value x)))
268 (if (objectp v)
269 (format f "(def ~s ~s)~%" x (send v :save))
270 (format f "(def ~s '~s)~%" x v)))))
271 (mapcar #'save-one vars))
272 vars)))
274 (defun undef (v)
275 "Args: (v)
276 If V is the symbol of a defined variable the variable it is unbound and
277 removed from the list of defined variables. If V is a list of variable
278 names each is unbound and removed. Returns V."
279 (dolist (s (if (listp v) v (list v)))
280 (when (member s *variables*)
281 (setq *variables* (delete s *variables*))
282 (makunbound s)))