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