82c0abd29853886039f35ec269410cffe8b5a4f8
[pubmed.git] / src.lisp
1 ;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*-
2 ;;;; *************************************************************************
3 ;;;; FILE IDENTIFICATION
4 ;;;;
5 ;;;; Name:          pubmed.lisp
6 ;;;; Purpose:       Library to access PubMed web application
7 ;;;; Programmer:    Kevin M. Rosenberg
8 ;;;; Date Started:  Jun 2001
9 ;;;;
10 ;;;; $Id: src.lisp,v 1.2 2003/06/06 21:59:30 kevin Exp $
11 ;;;;
12 ;;;; This file, part of cl-pubmed, is Copyright (c) 2002 by Kevin M. Rosenberg
13 ;;;;
14 ;;;; cl-pubmed users are granted the rights to distribute and use this software
15 ;;;; as governed by the terms of the GNU Lesser General Public License 
16 ;;;; (http://www.gnu.org/licenses/lgpl.html)
17 ;;;; *************************************************************************
18
19 (in-package #:cl-user)
20
21 (defpackage #:pubmed
22   (:use #:common-lisp #:kmrcl)
23   (:export
24
25    ;; Conditions
26    #:pubmed-condition
27    #:pubmed-query-error
28    #:pubmed-server-error
29    
30    ;; Query functions
31    #:pm-query
32    #:pm-fetch-ids
33
34    ;; Print functions
35    #:print-article
36    #:print-article-set
37
38    ; Classes
39    #:pm-article
40    #:pm-article-set
41
42    ;; pm-article-set accessors 
43    #:articles
44    #:articles-query
45    #:articles-total
46    #:articles-count
47    #:articles-start
48
49    ;; article accessors
50    #:article-pmid
51    #:article-title
52    #:article-authors
53    #:article-affiliation
54    #:article-journal
55    #:article-date
56    #:article-volume
57    #:article-issue
58    #:article-pages
59    #:article-abstract
60    #:article-mesh-headings
61    ))
62
63 (in-package #:pubmed)
64
65
66 (defparameter +pubmed-host+ "www.ncbi.nlm.nih.gov")
67 (defparameter +pubmed-query-url+ "/entrez/utils/pmqty.fcgi")
68 (defparameter +pubmed-fetch-url+ "/entrez/utils/pmfetch.fcgi")
69
70
71 (define-condition pubmed-condition ()
72   ())
73
74   
75 (define-condition pubmed-server-error (error pubmed-condition)
76   ((response :initarg :response
77              :initform nil
78              :reader pubmed-server-error-response))
79   (:report (lambda (c stream)
80              (format stream "A PubMed server error occurred.")
81              (awhen (pubmed-server-error-response c)
82                     (format stream " The server response was:~&~S" it)))))
83
84 (define-condition pubmed-query-error (error pubmed-condition)
85   ((response :initarg :response
86              :initform nil
87              :reader pubmed-query-error-response))
88   (:report (lambda (c stream)
89              (format stream "A PubMed server error occurred.")
90              (awhen (pubmed-query-error-response c)
91                     (format stream " The server response was:~&~S" it)))))
92   
93 ;;; Article-Set and Article Classes
94
95 (defclass pm-article-set ()
96   ((query :type string :initarg :query :accessor articles-query)
97    (articles :type list :initarg :articles :accessor articles)
98    (total :type fixnum :initarg :total :accessor articles-total)
99    (count :type fixnum :initarg :count :accessor articles-count)
100    (start :type fixnum :initarg :start :accessor articles-start))
101   (:documentation "Pubmed Article Set Class")
102   (:default-initargs :total 0 :start 0 :count 0
103                      :query nil :articles nil))
104
105 (defclass pm-article ()
106   (
107    (pmid :type integer :accessor article-pmid)
108    (title :type string :accessor article-title)
109    (authors :type list :accessor article-authors)
110    (affiliation :type string :accessor article-affiliation)
111    (journal :type string :accessor article-journal)
112    (date :type string :accessor article-date)
113    (volume :type string :accessor article-volume)
114    (issue :type string :accessor article-issue)
115    (pages :type string :accessor article-pages)
116    (abstract :type string :accessor article-abstract)
117    (mesh-headings :type list :accessor article-mesh-headings))
118   (:documentation "Pubmed Article Class"))
119
120 (defmethod print-object ((obj pm-article-set) (s stream))
121   (print-unreadable-object (obj s :type t :identity t)
122     (format s "~d total articles, ~d articles starting at #~d" 
123             (articles-total obj)
124             (articles-count obj)
125             (articles-start obj)
126             )))
127
128 (defmethod print-object ((obj pm-article) (s stream))
129   (print-unreadable-object (obj s :type t :identity t)
130     (format s "pmid:~d, title:~S" (article-pmid obj)
131             (article-title obj))))
132
133 (defun article-equal-p (a b)
134   (check-type a pm-article)
135   (check-type b pm-article)
136   (eql (article-pmid a) (article-pmid b)))
137
138 (defun article-ref (art)
139   "Return a string of publication data for an article"
140   (let ((ref ""))
141     (awhen (article-date art)
142            (string-append ref (format nil "~a; " it)))
143     (awhen (article-volume art)
144            (string-append ref it))
145     (awhen (article-issue art)
146            (string-append ref (format nil "(~a)" it)))
147     (awhen (article-pages art)
148            (string-append ref (format nil ":~a" it)))
149     ref))
150
151 (defmethod print-article-set ((artset pm-article-set) &key (os *standard-output*) (format :text)
152                                                        (complete nil) (print-link t))
153   "Display an article set to specified stream in specified format"
154   (dotimes (i (articles-count artset))
155     (print-article (nth i (articles artset)) :os os :format format 
156                    :complete complete :print-link print-link))
157   artset)
158
159 (defmethod print-article ((art pm-article) &key (os *standard-output*)
160                           (format :text) (complete nil) (print-link t))
161   "Display an article"
162   (ecase format
163     (:text
164      (format os "~a~%~a~%~a~a ~a~%~a~%" 
165              (article-title art)
166              (list-to-delimited-string (article-authors art) ", ")
167              (aif (article-affiliation art)
168                   (format nil "~a~%" it) "")
169              (article-journal art) (article-ref art)
170              (aif (article-abstract art) 
171                   (if complete
172                       it
173                     "Abstract available") 
174                   "No abstract available")
175              (when complete
176                (format os "~a~%" (article-mesh-headings art)))))
177      (:html
178       (let ((has-link (or (article-abstract art) (article-mesh-headings art))))
179         (when (and print-link has-link)
180           (format os "<a href=\"~a?key=~a\">" (make-url "print-article") (article-pmid art)))
181         (format os "<div class=\"article-title\">~a</div>~%" (article-title art))
182         (when (and print-link has-link)
183           (format os "</a>"))
184         (format os "<div class=\"article-authors\">~a</div>~%"
185                 (list-to-delimited-string (article-authors art) ", "))
186         (format os "<div class=\"article-reference\">~a ~a</div>~%" 
187                 (article-journal art) (article-ref art))
188         (when (and complete (article-abstract art))
189           (format os "<div class=\"article-abstract\">~a</div>~%" 
190                   (article-abstract art)))
191         (when (and complete (article-mesh-headings art))
192           (format os "<div class=\"mesh-heading-title\">Mesh Headings:</div>")
193           (dolist (mh (article-mesh-headings art))
194             (format os "<div class=\"mesh-heading\">~a</div>~%" mh)))
195         (format os "<p/>~%"))))
196   art)
197
198
199 ;;; PubMed Query Functions
200
201 (defun pm-query (searchstr &key maximum start)
202   "Performs PubMed query and fetch and returns article-set structure"
203     (multiple-value-bind 
204         (results status) 
205         (pubmed-search-xml searchstr :maximum maximum :start start)
206       (when (xml-tag-contents "Count" status)
207            (let ((as (make-instance 'pm-article-set)))
208              (setf 
209                  (articles-total as) (parse-integer (xml-tag-contents "Count" status))
210                  (articles-query as) searchstr
211                  (articles-start as) (parse-integer (xml-tag-contents "DispStart" status))
212                  (articles-count as) (parse-integer (xml-tag-contents "DispMax" status))
213                  (articles as) (extract-article-set results))
214              as))))
215
216 (defun pm-fetch-ids (pmids)
217   "Fetchs list of Pubmed ID's and returns pm-article-set class"
218   (setq pmids (mklist pmids))
219   (let ((results (pubmed-fetch-pmids-xml pmids)))
220     (unless (xml-tag-contents "Error" results)
221       (let ((as (make-instance 'pm-article-set)))
222         (setf 
223             (articles-total as) (length pmids)
224             (articles-query as) (list-to-delimited-string pmids #\,)
225             (articles-start as) 0
226             (articles-count as) (length pmids)
227             (articles as) (extract-article-set results))
228         as))))
229
230 #+ignore
231 (defun pubmed-search-tree (searchstr &key maximum start)
232   "Performs a pubmed search and returns two values: 
233 tree of PubMed search results and tree of PubMed search status"
234   (multiple-value-bind
235       (xml-search-results xml-search-status)
236       (pubmed-search-xml searchstr :maximum maximum :start start)
237     (if xml-search-results
238         (values (parse-xml-no-ws xml-search-results) 
239                 (parse-xml-no-ws xml-search-status))
240       (values nil (parse-xml-no-ws xml-search-status)))))
241
242 (defun pubmed-search-xml (searchstr &key maximum start)
243   "Performs a Pubmed search and returns two values: 
244 XML string of PubMed search results and XML search status"
245   (multiple-value-bind 
246       (pmids search-status)
247       (pubmed-query-xml searchstr :maximum maximum :start start)
248     (values (pubmed-fetch-pmids-xml pmids) search-status)))
249
250 (defun pubmed-query-xml (searchstr &key maximum start)
251   "Performs a Pubmed search and returns two values:
252  list of PubMed ID's that match search string and XML search status"
253   (let ((search-results (pubmed-query-status searchstr :maximum maximum :start start)))
254     (values (extract-pmid-list search-results) search-results)))
255
256 (defun pubmed-query-status (searchstr &key start maximum)
257   "Performs a Pubmed search and returns XML results of PubMed search
258  which contains PubMed ID's and status results"
259   (let ((query-alist `(("db" . "m") ("term" . ,searchstr) ("mode" . "xml"))))
260     (when maximum (push (cons "dispmax" maximum) query-alist))
261     (when start (push (cons "dispstart" start) query-alist))
262     (net.aserve.client:do-http-request
263      (format nil "http://~a~a" +pubmed-host+ +pubmed-query-url+)
264      :method :get
265      :query query-alist)))
266
267 (defun pubmed-fetch-pmids-xml (pmids)
268   "Fetch articles for a list of PubMed ID's and return XML string"
269   (setq pmids (mklist pmids)) ;; Ensure list
270   (when pmids
271       (net.aserve.client:do-http-request
272        (format nil "http://~a~a" +pubmed-host+ +pubmed-fetch-url+)
273        :method :get
274        :query 
275        `(("db" . "PubMed") ("report" . "xml") ("mode" . "text")
276          ("id" . ,(list-to-delimited-string pmids #\,))))))
277
278 ;;; XML Extraction Routines
279
280 (defun extract-article-set (results)
281   "Extract article set from PubMed XML string, return results in pm-article-set class"
282   (multiple-value-bind (as-start as-end as-next) 
283       (positions-xml-tag-contents "PubmedArticleSet" results)
284     (declare (ignore as-end as-next))
285     (when as-start
286       (let ((done nil)
287             (articles '())
288             (pos as-start))
289         (until done
290                (multiple-value-bind
291                    (a-start a-end a-next)
292                    (positions-xml-tag-contents "PubmedArticle" results pos)
293                  (if a-start
294                      (progn
295                        (push (extract-article results a-start a-end) articles)
296                        (setq pos a-next)
297                        )
298                    (setq done t))))
299         (nreverse articles)))))
300
301 (defun extract-article (xmlstr a-start a-end)
302   "Extract article contents from PubMed XML string and return results in pm-article class"
303   (let ((article (make-instance 'pm-article)))
304     (setf 
305         (article-pmid article) (parse-integer (xml-tag-contents "PMID" xmlstr a-start a-end))
306         (article-title article) (xml-tag-contents "ArticleTitle" xmlstr a-start a-end)
307         (article-journal article) (xml-tag-contents "MedlineTA" xmlstr a-start a-end)
308         (article-pages article) (xml-tag-contents "MedlinePgn" xmlstr a-start a-end)
309         (article-affiliation article) (xml-tag-contents "Affiliation" xmlstr a-start a-end)
310         (article-abstract article) (xml-tag-contents "AbstractText" xmlstr a-start a-end))
311     (multiple-value-bind (ji-start ji-end ji-next)
312         (positions-xml-tag-contents "JournalIssue" xmlstr a-start a-end)
313       (declare (ignore ji-next))
314       (setf
315           (article-volume article) (xml-tag-contents "Volume" xmlstr ji-start ji-end)
316           (article-issue article) (xml-tag-contents "Issue" xmlstr ji-start ji-end))
317       (aif (xml-tag-contents "MedlineDate" xmlstr ji-start ji-end)
318            (setf (article-date article) it)
319            (setf (article-date article)
320              (concatenate 'string (xml-tag-contents "Year" xmlstr ji-start ji-end)
321                           (aif (xml-tag-contents "Month" xmlstr ji-start ji-end)
322                                (format nil " ~a" it)
323                                "")))))
324           
325     (multiple-value-bind (al-start al-end al-next)
326         (positions-xml-tag-contents "AuthorList" xmlstr a-start a-end)
327       (declare (ignore al-next))
328       (setf (article-authors article)
329         (when al-start
330             (let ((done nil)
331                   (authors '())
332                   (pos al-start))
333               (until done
334                      (multiple-value-bind
335                          (au-start au-end au-next)
336                          (positions-xml-tag-contents "Author" xmlstr pos al-end)
337                        (if au-start
338                            (progn
339                              (push (extract-author xmlstr au-start au-end) authors)
340                              (setq pos au-next))
341                          (setq done t))))
342               (nreverse authors)))))
343
344     (multiple-value-bind (mhl-start mhl-end mhl-next)
345         (positions-xml-tag-contents "MeshHeadingList" xmlstr a-start a-end)
346       (declare (ignore mhl-next))
347       (setf (article-mesh-headings article)
348         (when mhl-start
349             (let ((done nil)
350                   (mesh-headings '())
351                   (pos mhl-start))
352               (until done
353                      (multiple-value-bind
354                          (mh-start mh-end mh-next)
355                          (positions-xml-tag-contents "MeshHeading" xmlstr pos mhl-end)
356                        (if mh-start
357                            (progn
358                              (push (extract-mesh-heading xmlstr mh-start mh-end) mesh-headings)
359                              (setq pos mh-next)
360                              )
361                          (setq done t))))
362               (nreverse mesh-headings)))))
363
364     article))
365
366 (defun extract-author (xmlstr start end)
367   "Extract author name from XML string"
368   (let ((last-name (xml-tag-contents "LastName" xmlstr start end))
369         (initials  (xml-tag-contents "Initials" xmlstr start end)))
370     (concatenate 'string last-name " " initials)))
371
372 (defun extract-mesh-heading (xmlstr start end)
373   "Extract and format mesh headings from XML string"
374   (let ((desc (xml-tag-contents "DescriptorName" xmlstr start end))
375         (sh  (xml-tag-contents "SubHeading" xmlstr start end)))
376     (if sh
377         (format nil "~a(~a)" desc sh)
378       desc)))
379
380 (defun extract-pmid-list (results)
381   "Returns list of PubMed ID's from XML result string"
382   (cond
383    ((search "<ERROR>" results)
384     (error 'pubmed-query-error :response results))
385    ((search "<H1>Server Error</H1>" results)
386     (error 'pubmed-server-error :response results))
387    (t
388     (awhen (xml-tag-contents "Id" results)
389            (delimited-string-to-list it #\space)))))
390
391
392