r11167: added cdist fn
[umlisp.git] / class-support.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10; Package: umlisp -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:     classes-support.lisp
6 ;;;; Purpose:  Support for UMLisp classes
7 ;;;; Author:   Kevin M. Rosenberg
8 ;;;; Created:  Apr 2000
9 ;;;;
10 ;;;; $Id$
11 ;;;;
12 ;;;; This file, part of UMLisp, is
13 ;;;;    Copyright (c) 2000-2006 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)
20
21 ;;; Formatting routines
22
23 (defgeneric fmt-cui (c))
24 (defmethod fmt-cui ((c ucon))
25   (fmt-cui (cui c)))
26
27 (when *has-fixnum-class*
28   (defmethod fmt-cui ((c fixnum))
29     (prefixed-fixnum-string c #\C 7)))
30
31 (defmethod fmt-cui ((c integer))
32     (prefixed-integer-string c #\C 7))
33
34 (defmethod fmt-cui ((c string))
35   (if (eql (aref c 0) #\C)
36       c
37       (fmt-cui (parse-integer c))))
38
39 (defmethod fmt-cui ((c null))
40   (format nil "nil"))
41
42 (defgeneric fmt-lui (c))
43 (defmethod fmt-lui ((l uterm))
44   (fmt-lui (lui l)))
45
46 (when *has-fixnum-class*
47   (defmethod fmt-lui ((l fixnum))
48     (prefixed-fixnum-string l #\L 7)))
49
50 (defmethod fmt-lui ((l integer))
51   (prefixed-integer-string l #\L 7))
52
53 (defmethod fmt-lui ((l string))
54   (if (eql (aref l 0) #\L)
55       l
56       (fmt-lui (parse-integer l))))
57
58 (defgeneric fmt-sui (s))
59 (defmethod fmt-sui ((s ustr))
60   (fmt-sui (sui s)))
61
62 (when *has-fixnum-class*
63   (defmethod fmt-sui ((s fixnum))
64     (prefixed-fixnum-string s #\S 7)))
65
66 (defmethod fmt-sui ((s integer))
67   (prefixed-integer-string s #\S 7))
68
69 (defmethod fmt-sui ((s string))
70   (if (eql (aref s 0) #\S)
71       s
72       (fmt-sui (parse-integer s))))
73
74 (defgeneric fmt-tui (tui))
75 (when *has-fixnum-class*
76   (defmethod fmt-tui ((tui fixnum))
77     (prefixed-fixnum-string tui #\T 3)))
78
79 (defmethod fmt-tui ((tui integer))
80   (prefixed-integer-string tui #\T 3))
81
82 (defmethod fmt-tui ((tui string))
83   (if (eql (aref tui 0) #\T)
84       tui
85     (fmt-tui (parse-integer tui))))
86
87 (defgeneric fmt-aui (aui))
88 (when *has-fixnum-class*
89   (defmethod fmt-aui ((aui fixnum))
90     (if (>= aui 10000000)
91       (prefixed-fixnum-string aui #\A 8)
92       (prefixed-fixnum-string aui #\A 7))))
93
94 (defmethod fmt-aui ((aui integer))
95   (if (>= aui 10000000)
96     (prefixed-integer-string aui #\A 8)
97     (prefixed-integer-string aui #\A 7)))
98
99 (defmethod fmt-aui ((aui string))
100   (if (eql (aref aui 0) #\A)
101       aui
102       (fmt-aui (parse-integer aui))))
103
104 (defgeneric fmt-rui (rui))
105 (when *has-fixnum-class*
106   (defmethod fmt-rui ((rui fixnum))
107     (prefixed-fixnum-string rui #\A 8)))
108
109 (defmethod fmt-rui ((rui integer))
110   (prefixed-integer-string rui #\A 8))
111
112 (defmethod fmt-rui ((rui string))
113   (if (eql (aref rui 0) #\R)
114       rui
115     (fmt-rui (parse-integer rui))))
116
117 (defgeneric fmt-eui (e))
118 (when *has-fixnum-class*
119   (defmethod fmt-eui ((e fixnum))
120     (prefixed-fixnum-string e #\E 7)))
121
122 (defmethod fmt-eui ((e integer))
123   (prefixed-integer-string e #\E 7))
124
125 (defmethod fmt-eui ((e string))
126   (if (eql (aref e 0) #\E)
127       e
128       (fmt-eui (parse-integer e))))
129
130 (defmethod fmt-eui ((e null))
131   (format nil "nil"))
132
133 (defun cui-p (ui)
134   "Check if a string is a CUI"
135   (check-ui ui #\C 7))
136
137 (defun lui-p (ui)
138   "Check if a string is a LUI"
139   (check-ui ui #\L 7))
140
141 (defun sui-p (ui)
142   "Check if a string is a SUI"
143   (check-ui ui #\S 7))
144
145 (defun tui-p (ui)
146   (check-ui ui #\T 3))
147
148 (defun eui-p (ui)
149   (check-ui ui #\E 7))
150
151 (defun check-ui (ui start-char len)
152   (when (and (stringp ui)
153              (= (length ui) (1+ len))
154              (char-equal start-char (schar ui 0))
155              (ignore-errors (parse-integer ui :start 1)))
156     t))
157
158
159 ;;; Generic display functions
160
161 (eval-when (:compile-toplevel :load-toplevel :execute)
162 (defun english-term-p (obj)
163   "Returns two values: T/NIL if term is english and T/NIL if obj is a TERM"
164   (if (eq (hyperobject::class-name (hyperobject::class-of obj)) 'uterm)
165       (values (string-equal (lat obj) "ENG") t)
166     (values nil nil))))
167
168 (defun english-term-filter (obj)
169   "Retrns NIL if object is a term and not english"
170   (multiple-value-bind (is-english is-term) (english-term-p obj)
171       (or (not is-term) is-english)))
172
173 (defun print-umlsclass (obj &key (stream *standard-output*)
174                         (vid :compact-text)
175                         (file-wrapper nil) (english-only t) (subobjects nil)
176                         (refvars nil) (link-printer nil))
177   (view obj :stream stream :vid vid :subobjects subobjects
178         :file-wrapper file-wrapper
179         :filter (if english-only nil #'english-term-filter)
180         :link-printer link-printer
181         :refvars refvars))
182
183 (defmacro define-lookup-display (newfuncname lookup-func)
184   "Defines functions for looking up and displaying objects"
185   `(defun ,newfuncname  (keyval &key (stream *standard-output*) (vid :compact-text)
186                          (file-wrapper t) (english-only nil) (subobjects nil))
187      (let ((obj (funcall ,lookup-func keyval)))
188        (print-umlsclass obj :stream stream :vid vid
189                         :file-wrapper file-wrapper :english-only english-only
190                         :subobjects subobjects)
191        obj)))
192
193 (define-lookup-display display-con #'find-ucon-cui)
194 (define-lookup-display display-term #'find-uterm-lui)
195 (define-lookup-display display-str #'find-ustr-sui)
196
197 (defun ucon-has-tui (ucon tui)
198   "Returns T if UCON has a semantic type of TUI."
199   (some #'(lambda (usty) (= tui (tui usty))) (s#sty ucon)))
200
201 (defgeneric suistr (lo))
202 (defmethod suistr ((lo ulo))
203   "Return the string for a ulo object"
204   (find-string-sui (sui lo)))
205
206 (defgeneric pf-ustr (obj))
207 (defmethod pf-ustr ((ucon ucon))
208   "Return the preferred ustr for a ucon"
209   (pf-ustr
210    (find-if (lambda (uterm) (string= "P" (ts uterm))) (s#term ucon))))
211
212 (defmethod pf-ustr ((uterm uterm))
213   "Return the preferred ustr for a uterm"
214   (find-if (lambda (ustr) (string= "PF" (stt ustr))) (s#str uterm)))
215
216 (defgeneric mesh-number (obj))
217 (defmethod mesh-number ((con ucon))
218   (mesh-number (pf-ustr con)))
219
220 (defmethod mesh-number ((ustr ustr))
221   (let ((codes
222          (map-and-remove-nils
223           (lambda (sat)
224             (when (and (string-equal "MSH" (sab sat))
225                        (string-equal "MN" (atn sat)))
226               (atv sat)))
227           (s#sat ustr))))
228     (if (= 1 (length codes))
229         (car codes)
230       codes)))
231
232 (defun ucon-ustrs (ucon)
233   "Return lists of strings for a concept"
234   (let (res)
235     (dolist (term (s#term ucon) (nreverse res))
236       (dolist (str (s#str term))
237         (push str res)))))
238
239
240 (defmethod pfstr ((uterm uterm))
241   "Return the preferred string for a uterm"
242   (dolist (ustr (s#str uterm))
243     (when (string= "PF" (stt ustr))
244       (return-from pfstr (str ustr)))))
245
246 (defmethod pfstr ((ustr ustr))
247   "Return the preferred string for a ustr, which is the string itself"
248   (str ustr))
249
250 (defun remove-non-english-terms (uterms)
251   (remove-if-not #'english-term-p uterms))
252
253 (defun remove-english-terms (uterms)
254   (remove-if #'english-term-p uterms))
255
256
257 (defvar +relationship-abbreviations+
258   '(("RB" "Broader" "has a broader relationship")
259     ("RN" "Narrower" "has a narrower relationship")
260     ("RO" "Other related" "has relationship other than synonymous, narrower, or broader")
261     ("RL" "Like" "the two concepts are similar or 'alike'.  In the current edition of the Metathesaurus, most relationships with this attribute are mappings provided by a source")
262     ("RQ" "Unspecified" "unspecified source asserted relatedness, possibly synonymous")
263     ("SY" "Source Synonymy" "source asserted synonymy")
264     ("PAR" "Parent" "has parent relationship in a Metathesaurus source vocabulary")
265     ("CHD" "Child" "has child relationship in a Metathesaurus source vocabulary")
266     ("SIB" "Sibling" "has sibling relationship in a Metathesaurus source vocabulary")
267     ("AQ" "Allowed" "is an allowed qualifier for a concept in a Metathesaurus source vocabulary")
268     ("QB" "Qualified" "can be qualified by a concept in a Metathesaurus source vocabulary")))
269
270 (defvar *rel-info-table* (make-hash-table :size 30 :test 'equal))
271 (defvar *is-rel-table-init* nil)
272 (unless *is-rel-table-init*
273   (dolist (relinfo +relationship-abbreviations+)
274     (setf (gethash (string-downcase (car relinfo)) *rel-info-table*)
275       (cdr relinfo)))
276   (setq *is-rel-table-init* t))
277
278 (defun rel-abbr-info (rel)
279   (nth-value 0 (gethash (string-downcase rel) *rel-info-table*)))
280
281 (defun filter-urels-by-rel (urels rel)
282   (remove-if-not (lambda (urel) (string-equal rel (rel urel))) urels))
283
284
285 (defvar +language-abbreviations+
286     '(("BAQ" . "Basque")
287       ("CZE" . "Chech")
288       ("DAN" . "Danish")
289       ("DUT" . "Dutch")
290       ("ENG" . "English")
291       ("FIN" . "Finnish")
292       ("FRE" . "French")
293       ("GER" . "German")
294       ("HEB" . "Hebrew")
295       ("HUN" . "Hungarian")
296       ("ITA" . "Italian")
297       ("JPN" . "Japanese")
298       ("NOR" . "Norwegian")
299       ("POR" . "Portuguese")
300       ("RUS" . "Russian")
301       ("SPA" . "Spanish")
302       ("SWE" . "Swedish")))
303
304 (defvar *lat-info-table* (make-hash-table :size 30 :test 'equal))
305 (defvar *is-lat-table-init* nil)
306 (unless *is-lat-table-init*
307   (dolist (latinfo +language-abbreviations+)
308     (setf (gethash (string-downcase (car latinfo)) *lat-info-table*)
309       (cdr latinfo)))
310   (setq *is-lat-table-init* t))
311
312 (defun lat-abbr-info (lat)
313   (aif (nth-value 0 (gethash (string-downcase lat) *lat-info-table*))
314        it
315        lat))
316
317
318
319 (defun stt-abbr-info (stt)
320   (when (string-equal "PF" stt)
321     (return-from stt-abbr-info "Preferred"))
322   (when (char-equal #\V (schar stt 0))
323     (setq stt (subseq stt 1)))
324   (loop for c across stt
325       collect
326         (cond
327          ((char-equal #\C c)
328           "Upper/lower case")
329          ((char-equal #\W c)
330           "Word order")
331          ((char-equal #\S c)
332           "Singular")
333          ((char-equal #\P c)
334           "Plural")
335          ((char-equal #\O c)
336           "Other"))))
337
338
339 (defun ucon-parents (ucon &key sab include-rb)
340   (ucon-ancestors ucon :sab sab :include-rb include-rb
341                   :ancestors nil))
342
343 (defun is-ucon-in-ancestors (ucon ancestors)
344   (cond
345    ((null ancestors) nil)
346    ((atom ancestors) (eql (cui ucon) (cui ancestors)))
347    ((listp (car ancestors))
348     (or (is-ucon-in-ancestors ucon (car ancestors))
349         (is-ucon-in-ancestors ucon (cdr ancestors))))
350    (t
351     (or (eql (cui ucon) (cui (car ancestors)))
352         (is-ucon-in-ancestors ucon (cdr ancestors))))))
353
354
355 (defun sorted-ancestor-cuis (anc)
356   (sort (remove-duplicates (map 'list 'cui (flatten anc))) #'<))
357
358 (defun shared-cuis (a1 a2)
359   (let ((cl1 (sorted-ancestor-cuis a1))
360         (cl2 (sorted-ancestor-cuis a2))
361         (shared nil))
362     (dolist (c1 cl1 (nreverse shared))
363       (dolist (c2 cl2)
364         (cond
365          ((eql c1 c2)
366           (push c1 shared))
367          ((> c2 c1)
368           (return)))))))
369
370 (defun cdist-ancestors (anc1 anc2)
371   (let ((shareds (shared-cuis anc1 anc2)))
372     (let ((min most-positive-fixnum)
373           (cui-min nil))
374       (declare (fixnum min))
375       (dolist (shared shareds)
376         (let* ((d1 (ancestor-distance shared anc1))
377                (d2 (ancestor-distance shared anc2))
378                (dtotal (+ d1 d2)))
379           (declare (fixnum d1 d2 dtotal))
380           (when (< dtotal min)
381             (setq min dtotal
382                   cui-min shared))))
383       (values min cui-min))))
384
385 (defun cdist (c1 c2 &key sab include-rb)
386   (let* ((anc1 (ucon-ancestors c1 :sab sab :include-rb include-rb))
387          (anc2 (ucon-ancestors c2 :sab sab :include-rb include-rb)))
388     (multiple-value-bind (min cui)
389         (cdist-ancestors anc1 anc2)
390       (if cui
391           (values min cui)
392         (values nil nil)))))
393                
394
395 (defun ancestor-distance (cui ancestors &key (distance 0))
396   (cond
397    ((null ancestors)
398     nil)
399    ((atom ancestors)
400     (when (eql cui (cui ancestors))
401       distance))
402    ((atom (car ancestors))
403     (if (eql cui (cui (car ancestors)))
404         distance
405       (ancestor-distance cui (cdr ancestors) :distance distance)))
406    (t
407     (let ((min most-positive-fixnum))
408       (dolist (a ancestors)
409         (let ((d (ancestor-distance cui a :distance (1+ distance))))
410           (when (and d (< d min))
411             (setq min d))))
412       (when (< min most-positive-fixnum)
413         min)))))
414
415     
416         
417 (defun ucon-ancestors (ucon &key sab include-rb ancestors)
418   "Returns a list of ancestor lists for a concept"
419   (let* ((parent-rels (append (filter-urels-by-rel (s#rel ucon) "par")
420                               (when include-rb
421                                 (filter-urels-by-rel (s#rel ucon) "rb"))))
422          (parents nil))
423     (when sab
424       (setq parent-rels (delete-if-not
425                          (lambda (rel) (string-equal sab (sab rel)))
426                          parent-rels)))
427     (dolist (rel parent-rels)
428       (let ((parent (find-ucon-cui (cui2 rel))))
429         ;;(format t "~S ~S ~S ~S~%" rel ucon parent ancestors)
430         (unless (is-ucon-in-ancestors parent ancestors)
431           (push
432            (list*
433             parent
434             (ucon-ancestors parent :sab (sab rel) :ancestors (append (list parent) ancestors)))
435            parents))))
436     (nreverse parents)))
437
438
439 (defgeneric cxt-ancestors (obj))
440 (defmethod cxt-ancestors ((con ucon))
441   (loop for term in (s#term con)
442       append (cxt-ancestors term)))
443
444
445 (defmethod cxt-ancestors ((term uterm))
446   (loop for str in (s#str term)
447       append (cxt-ancestors str)))
448
449 (defmethod cxt-ancestors ((str ustr))
450   "Return the ancestory contexts of a ustr"
451   (let* ((anc (remove-if-not
452                (lambda (cxt) (string-equal "ANC" (cxl cxt)))
453                (s#cxt str)))
454          (num-contexts (if anc
455                            (apply #'max (mapcar (lambda (cxt) (cxn cxt)) anc))
456                          0))
457          (anc-lists '()))
458     (dotimes (i num-contexts (nreverse anc-lists))
459       (let* ((anc-this-cxn (remove-if-not
460                             (lambda (cxt) (= (1+ i) (cxn cxt))) anc)))
461         (push
462          (sort anc-this-cxn (lambda (a b) (< (rank a) (rank b))))
463          anc-lists)))))
464
465 (defun uso-unique-codes (usos)
466   (let ((sab-codes (make-hash-table :test 'equal)))
467     (dolist (uso usos)
468       (setf (gethash (sab uso) sab-codes) (code uso)))
469     (loop for key being the hash-key in sab-codes
470         collect (list key (gethash key sab-codes)))))
471
472
473 (defun ucon-has-sab (ucon sab)
474   (and (find-if (lambda (uso) (string-equal sab (sab uso))) (s#so ucon)) t))
475
476
477 #+scl
478 (dolist (c '(urank udef usat uso ucxt ustr ulo uterm usty urel ucoc uatx ucon uxw uxnw uxns lexterm labr lagr lcmp lmod lnom lprn lprp lspl ltrm ltyp lwd sdef sstr sstre1 sstre2 usrl))
479     (let ((cl (find-class c)))
480       (clos:finalize-inheritance cl)))
481
482