r11168: add cdist-metric
[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           (path-min nil))
375       (declare (fixnum min))
376       (dolist (shared shareds)
377         (multiple-value-bind (d1 p1) (ancestor-distance shared anc1)
378           (multiple-value-bind (d2 p2) (ancestor-distance shared anc2)
379             (let ((dtotal (+ d1 d2)))
380               (declare (fixnum d1 d2 dtotal))
381               (when (< dtotal min)
382                 (format t "~D ~D ~D ~S ~S~%" d1 d2 dtotal p1 p2)
383                 (setq min dtotal
384                       cui-min shared
385                       path-min (append p1 (cdr (reverse p2)))
386                       ))))))
387       (values min cui-min path-min))))
388
389 (defun cdist-metric (c1 c2 &key sab include-rb full-ucon (srl *current-srl*))
390   (let* ((anc1 (ucon-ancestors c1 :sab sab :include-rb include-rb :full-ucon full-ucon :srl srl))
391          (anc2 (ucon-ancestors c2 :sab sab :include-rb include-rb :full-ucon full-ucon :srl srl)))
392     (multiple-value-bind (min cui path)
393         (cdist-ancestors (list* c1 anc1) (list* c2 anc2))
394       (if cui
395           (values min cui (append (list c1) path (unless (eql (cui (car (last path))) (cui c2))
396                                                    (list c2))))
397         (values nil nil nil)))))
398                
399
400 (defun ancestor-distance (cui ancestors &key (distance 0) path)
401   (cond
402    ((null ancestors)
403     nil)
404    ((atom ancestors)
405     (when (eql cui (cui ancestors))
406       (values distance (nreverse (list* ancestors path)))))
407    ((atom (car ancestors))
408     (if (eql cui (cui (car ancestors)))
409         (values distance (nreverse (list* (car ancestors) path)))
410       (ancestor-distance cui (cdr ancestors) :distance distance :path (list* (car ancestors) path))))
411    (t
412     (let ((%min most-positive-fixnum)
413           %path)
414       (dolist (a ancestors)
415         (multiple-value-bind (d p) (ancestor-distance cui a :distance (1+ distance) :path path)
416           (when (and d (< d %min))
417             (setq %min d
418                   %path p))))
419       (when (< %min most-positive-fixnum)
420         (values %min %path))))))
421
422         
423 (defun ucon-ancestors (ucon &key sab include-rb ancestors full-ucon (srl *current-srl*))
424   "Returns a list of ancestor lists for a concept"
425   (unless ucon (return-from ucon-ancestors nil))
426   (let ((parent-rels (find-urel-cui
427                       (cui ucon)
428                       :without-pfstr2 t
429                       :srl srl
430                       :filter (concatenate 'string
431                                 (if sab (format nil "SAB='~A' AND " sab) "")
432                                 (if include-rb
433                                     "(REL='RB' OR REL='PAR')"
434                                   "REL='PAR'"))))
435         (parents nil))
436     (dolist (rel parent-rels)
437       (let ((parent (if full-ucon
438                         (find-ucon-cui (cui2 rel))
439                       (make-ucon-cui (cui2 rel)))))
440         ;; (format t "~S ~S ~S ~S~%" rel ucon parent ancestors)
441         (unless (is-ucon-in-ancestors parent ancestors)
442           (push
443            (list*
444             parent
445             (ucon-ancestors parent :sab (sab rel) :ancestors (append (list parent) ancestors)
446                             :full-ucon full-ucon))
447            parents))))
448     (nreverse parents)))
449
450
451 (defgeneric cxt-ancestors (obj))
452 (defmethod cxt-ancestors ((con ucon))
453   (loop for term in (s#term con)
454       append (cxt-ancestors term)))
455
456
457 (defmethod cxt-ancestors ((term uterm))
458   (loop for str in (s#str term)
459       append (cxt-ancestors str)))
460
461 (defmethod cxt-ancestors ((str ustr))
462   "Return the ancestory contexts of a ustr"
463   (let* ((anc (remove-if-not
464                (lambda (cxt) (string-equal "ANC" (cxl cxt)))
465                (s#cxt str)))
466          (num-contexts (if anc
467                            (apply #'max (mapcar (lambda (cxt) (cxn cxt)) anc))
468                          0))
469          (anc-lists '()))
470     (dotimes (i num-contexts (nreverse anc-lists))
471       (let* ((anc-this-cxn (remove-if-not
472                             (lambda (cxt) (= (1+ i) (cxn cxt))) anc)))
473         (push
474          (sort anc-this-cxn (lambda (a b) (< (rank a) (rank b))))
475          anc-lists)))))
476
477 (defun uso-unique-codes (usos)
478   (let ((sab-codes (make-hash-table :test 'equal)))
479     (dolist (uso usos)
480       (setf (gethash (sab uso) sab-codes) (code uso)))
481     (loop for key being the hash-key in sab-codes
482         collect (list key (gethash key sab-codes)))))
483
484
485 (defun ucon-has-sab (ucon sab)
486   (and (find-if (lambda (uso) (string-equal sab (sab uso))) (s#so ucon)) t))
487
488
489 #+scl
490 (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))
491     (let ((cl (find-class c)))
492       (clos:finalize-inheritance cl)))
493
494