Automated commit for upstream build of version 3.3.1
[umlisp-orf.git] / parse-common.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     parse-common.lisp
6 ;;;; Purpose:  Common, stable parsing routines for UMLisp
7 ;;;; Author:   Kevin M. Rosenberg
8 ;;;; Created:  Apr 2000
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UMLisp, is
13 ;;;;    Copyright (c) 2000-2004 by Kevin M. Rosenberg, M.D.
14 ;;;;
15 ;;;; UMLisp users are granted the rights to distribute and use this software
16 ;;;; as governed by the terms of the GNU General Public License.
17 ;;;; *************************************************************************
18
19 (in-package #:umlisp-orf)
20
21 (defun ensure-ucols+ufiles (&optional (alwaysclear nil))
22 "Initialize all UMLS file and column structures if not already initialized"
23   (when (or alwaysclear (null *umls-files*))
24     (gen-ucols)
25     (gen-ufiles)
26     (ensure-field-lengths)))
27
28 (defun add-ucols (ucols)
29   "Adds a ucol or list of ucols to *umls-cols*. Returns input value."
30   (setq *umls-cols* (append (mklist ucols) *umls-cols*))
31   ucols)
32
33 (defun add-ufiles (ufiles)
34   "Adds a ufile or list of ufiles to *umls-filess*. Returns input value."
35   (setq *umls-files* (append (mklist ufiles) *umls-files*))
36   ufiles)
37
38 (defun umls-pathname (filename &optional (extension ""))
39 "Return pathname for a umls filename with an optional extension"
40   (etypecase filename
41     (string
42      (merge-pathnames
43       (make-pathname :name (concatenate 'string filename extension))
44       (case (schar filename 0)
45         ((#\M #\m)
46          *meta-path*)
47         ((#\L #\l)
48          *lex-path*)
49         ((#\S #\s)
50          *net-path*)
51         (t
52          *umls-path*))))
53     (pathname
54       filename)))
55
56 (defun read-umls-line (strm &optional (eof 'eof))
57   "Read a line from a UMLS stream, split into fields"
58   (let ((line (read-line strm nil eof)))
59     (if (eq line eof)
60         eof
61         (delimited-string-to-list line #\| t))))
62
63 ;;; Find field lengths for LEX and NET files
64
65 (defun ensure-field-lengths ()
66   "Initial colstruct field lengths for files that don't have a measurement.
67 Currently, these are the LEX and NET files."
68   (dolist (length-list (ufiles-field-lengths (ufiles-to-measure)))
69     (destructuring-bind (filename fields-max fields-av) length-list
70       (let ((file (find-ufile filename)))
71         (unless file
72           (error "Can't find ~A filename in ufiles" filename))
73         (unless (= (length fields-max) (length (fields file)))
74           (error
75            "Number of file fields ~A not equal to field count in ufile ~S"
76            fields-max file))
77         (dotimes (i (length (fields file)))
78           (declare (fixnum i))
79           (let* ((field (nth i (fields file)))
80                  (col (find-ucol field filename)))
81             (unless col
82                 (error "can't find column ~A" field))
83             (setf (cmax col) (aref fields-max i))
84             (setf (av col) (aref fields-av i))
85             (ensure-ucol-datatype col (datatype-for-colname (col col)))))))))
86
87 (defun ufiles-to-measure ()
88   "Returns a list of ufiles to measure"
89   (loop for ufile in *umls-files*
90         unless (or (char= #\M (schar (fil ufile) 0))
91                    (char= #\m (schar (fil ufile) 0)))
92         collect ufile))
93
94
95 (defun ufiles-field-lengths (ufiles)
96   "Returns a list of lists of containing (FILE MAX AV)"
97   (loop for ufile in ufiles collect (file-field-lengths (fil ufile))))
98
99 (defun file-field-lengths (filename)
100   "Returns a list of FILENAME MAX AV"
101   (declare (optimize (speed 3) (safety 0)))
102   (let (fields-max fields-av num-fields (count-lines 0))
103     (with-umls-file (line filename)
104       (unless num-fields
105         (setq num-fields (length line))
106         (setq fields-max (make-array num-fields :element-type 'fixnum
107                                      :initial-element 0))
108         (setq fields-av (make-array num-fields :element-type 'number
109                                     :initial-element 0)))
110       (dotimes (i num-fields)
111         (declare (fixnum i))
112         (let ((len (length (nth i line))))
113           (incf (aref fields-av i) len)
114           (when (> len (aref fields-max i))
115             (setf (aref fields-max i) len))))
116       (incf count-lines))
117     (dotimes (i num-fields)
118       (setf (aref fields-av i) (float (/ (aref fields-av i) count-lines))))
119     (list filename fields-max fields-av)))
120
121 ;;; UMLS column/file functions
122
123 (defun find-ucol-of-colname (colname filename ucols)
124 "Returns list of umls-col structure for a column name and a filename"
125   (dolist (ucol ucols nil)
126     (when (and (string-equal filename (fil ucol))
127                (string-equal colname (col ucol)))
128       (return-from find-ucol-of-colname ucol))))
129
130 (defun ensure-col-in-columns (colname filename ucols)
131   (aif (find-ucol-of-colname colname filename ucols)
132        it
133        (add-ucols (make-ucol-for-column colname filename ucols))))
134
135 (defun make-ucol-for-column (colname filename ucols)
136   ;; try to find column name without a terminal digit
137   (let* ((len (length colname))
138          (last-digit? (digit-char-p (schar colname (1- len))))
139          (base-colname (if last-digit?
140                            (subseq colname 0 (1- len))
141                            colname))
142          (ucol (when last-digit?
143                  (find-ucol-of-colname base-colname filename ucols))))
144     (when (and last-digit? (null ucol))
145       (error "Couldn't find a base column for col ~A in file ~A"
146              colname filename))
147     (copy-or-new-ucol colname filename ucol)))
148
149 (defun copy-or-new-ucol (colname filename ucol)
150   (if ucol
151       (make-instance
152        'ucol
153        :col (copy-seq colname) :des (copy-seq (des ucol)) :ref (copy-seq (ref ucol))
154        :min (cmin ucol) :max (cmax ucol) :fil (copy-seq (fil ucol))
155        :sqltype (copy-seq (sqltype ucol)) :dty (copy-seq (dty ucol))
156        :parse-fun (parse-fun ucol) :quote-str (copy-seq (quote-str ucol))
157        :datatype (datatype ucol) :custom-value-fun (custom-value-fun ucol))
158       (make-empty-ucol colname filename)))
159
160 (defun ensure-compiled-fun (fun)
161   "Ensure that a function is compiled"
162   (etypecase fun
163     (null
164      nil)
165     (function
166      (if (compiled-function-p fun)
167          fun
168          (compile nil fun)))
169     (list
170      (compile nil fun))))
171
172 (defun make-ucol (col des ref min av max fil dty
173                   &key (sqltype "VARCHAR") (parse-fun #'add-sql-quotes)
174                   (quote-str "'") (custom-value-fun))
175   (let ((ucol (make-instance
176                'ucol
177                :col col :des des :ref ref :min min :av av
178                :max (if (eql max 0) 1 max) ;; ensure at least one char wide
179                :fil fil
180                :dty dty :sqltype sqltype :quote-str quote-str
181                :parse-fun (ensure-compiled-fun parse-fun)
182                :custom-value-fun (ensure-compiled-fun custom-value-fun))))
183     (ensure-ucol-datatype ucol (datatype-for-colname col))
184     ucol))
185
186 (defun make-empty-ucol (colname filename)
187   ;;(format "call in make-empty-ucol: ~A/~A" colname filename)
188   (make-ucol (copy-seq colname) "Unknown" "" nil nil nil filename nil))
189
190 (defun find-ucol (colname filename)
191   "Returns list of umls-col structure for a column name and a filename"
192   (ensure-col-in-columns colname filename *umls-cols*))
193
194 (defun find-ufile (filename)
195   "Returns umls-file structure for a filename"
196   (find-if #'(lambda (f) (string-equal filename (fil f))) *umls-files*))
197
198 (defun find-ucols-for-ufile (ufile)
199   "Returns list of umls-cols for a file structure"
200   (loop for colname in (fields ufile)
201         collect (find-ucol colname (fil ufile))))
202
203 (defun umls-field-string-to-list (fmt)
204   "Converts a comma delimited list of fields into a list of field names. Will
205 append a unique number (starting at 2) onto a column name that is repeated in the list"
206   (let ((col-counts (make-hash-table :test 'equal)))
207     (loop for colname in (delimited-string-to-list (escape-column-name fmt) #\,)
208           collect
209           (multiple-value-bind (value found) (gethash colname col-counts)
210             (cond
211               (found
212                 (incf (gethash colname col-counts))
213                 (concatenate 'string colname (write-to-string (1+ value))))
214               (t
215                (setf (gethash colname col-counts) 1)
216                colname))))))
217
218 (defun make-ufile (fil des table cls rws bts fields)
219   (let ((ufile (make-instance 'ufile :fil fil :des des :table table :cls cls
220                               :rws rws :bts bts :fields fields)))
221     (setf (ucols ufile) (find-ucols-for-ufile ufile))
222     ufile))
223
224 (defun datatype-for-colname (colname)
225 "Return datatype for column name"
226   (second (find colname +col-datatypes+ :key #'car :test #'string-equal)))
227
228 (defun ensure-ucol-datatype (col datatype)
229 "Add data type information to column"
230   (setf (datatype col) datatype)
231   (case datatype
232     (sql-u (setf (sqltype col) "INTEGER"
233                  (parse-fun col) #'parse-ui
234                  (quote-str col) ""))
235     (sql-s (setf (sqltype col) "SMALLINT"
236                  (parse-fun col) #'parse-integer
237                  (quote-str col) ""))
238     (sql-l (setf (sqltype col) "BIGINT"
239                  (parse-fun col) #'parse-integer
240                  (quote-str col) ""))
241     (sql-i (setf (sqltype col) "INTEGER"
242                  (parse-fun col) #'parse-integer
243                  (quote-str col) ""))
244     (sql-f (setf (sqltype col) "NUMERIC"
245                  (parse-fun col) #'read-from-string
246                  (quote-str col) ""))
247     (t                       ; Default column type, optimized text storage
248      (setf (parse-fun col) #'add-sql-quotes
249            (quote-str col) "'")
250      (when (and (cmax col) (av col))
251        (if (> (cmax col) 255)
252            (setf (sqltype col) "TEXT")
253            (setf (sqltype col) "VARCHAR"))))))
254
255 (defun escape-column-name (name)
256   (substitute #\_ #\/ name))