r3263: *** empty log message ***
[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.5 2002/10/31 21:07:04 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   artset)
150
151 (defmethod print-article ((art pm-article) &key (os *standard-output*) (format :text)
152                                               (complete nil) (print-link t))
153   "Display an article"
154   (ecase format
155     (:text
156      (format os "~a~%~a~%~a~a ~a~%~a~%" 
157              (article-title art)
158              (list-to-delimited-string (article-authors art) ", ")
159              (aif (article-affiliation art)
160                   (format nil "~a~%" it) "")
161              (article-journal art) (article-ref art)
162              (aif (article-abstract art) 
163                   (if complete
164                       it
165                     "Abstract available") 
166                   "No abstract available")
167              (when complete
168                (format os "~a~%" (article-mesh-headings art)))))
169      (:html
170       (let ((has-link (or (article-abstract art) (article-mesh-headings art))))
171         (when (and print-link has-link)
172           (format os "<a href=\"~a?key=~a\">" (make-url "print-article") (article-pmid art)))
173         (format os "<div class=\"article-title\">~a</div>~%" (article-title art))
174         (when (and print-link has-link)
175           (format os "</a>"))
176         (format os "<div class=\"article-authors\">~a</div>~%"
177                 (list-to-delimited-string (article-authors art) ", "))
178         (format os "<div class=\"article-reference\">~a ~a</div>~%" 
179                 (article-journal art) (article-ref art))
180         (when (and complete (article-abstract art))
181           (format os "<div class=\"article-abstract\">~a</div>~%" 
182                   (article-abstract art)))
183         (when (and complete (article-mesh-headings art))
184           (format os "<div class=\"mesh-heading-title\">Mesh Headings:</div>")
185           (dolist (mh (article-mesh-headings art))
186             (format os "<div class=\"mesh-heading\">~a</div>~%" mh)))
187         (format os "<p/>~%"))))
188   art)
189
190
191 ;;; PubMed Query Functions
192
193 (defun pm-query (searchstr &key maximum start)
194   "Performs PubMed query and fetch and returns article-set structure"
195     (multiple-value-bind 
196         (results status) 
197         (pubmed-search-xml searchstr :maximum maximum :start start)
198       (when (xml-tag-contents "Count" status)
199            (let ((as (make-instance 'pm-article-set)))
200              (setf 
201                  (articles-total as) (parse-integer (xml-tag-contents "Count" status))
202                  (articles-query as) searchstr
203                  (articles-start as) (parse-integer (xml-tag-contents "DispStart" status))
204                  (articles-count as) (parse-integer (xml-tag-contents "DispMax" status))
205                  (articles as) (extract-article-set results))
206              as))))
207
208 (defun pm-fetch-ids (pmids)
209   "Fetchs list of Pubmed ID's and returns pm-article-set class"
210   (setq pmids (mklist pmids))
211   (let ((results (pubmed-fetch-pmids-xml pmids)))
212     (unless (xml-tag-contents "Error" results)
213       (let ((as (make-instance 'pm-article-set)))
214         (setf 
215             (articles-total as) (length pmids)
216             (articles-query as) (list-to-delimited-string pmids #\,)
217             (articles-start as) 0
218             (articles-count as) (length pmids)
219             (articles as) (extract-article-set results))
220         as))))
221
222 #+ignore
223 (defun pubmed-search-tree (searchstr &key maximum start)
224   "Performs a pubmed search and returns two values: 
225 tree of PubMed search results and tree of PubMed search status"
226   (multiple-value-bind
227       (xml-search-results xml-search-status)
228       (pubmed-search-xml searchstr :maximum maximum :start start)
229     (if xml-search-results
230         (values (parse-xml-no-ws xml-search-results) 
231                 (parse-xml-no-ws xml-search-status))
232       (values nil (parse-xml-no-ws xml-search-status)))))
233
234 (defun pubmed-search-xml (searchstr &key maximum start)
235   "Performs a Pubmed search and returns two values: 
236 XML string of PubMed search results and XML search status"
237   (multiple-value-bind 
238       (pmids search-status)
239       (pubmed-query-xml searchstr :maximum maximum :start start)
240     (values (pubmed-fetch-pmids-xml pmids) search-status)))
241
242 (defun pubmed-query-xml (searchstr &key maximum start)
243   "Performs a Pubmed search and returns two values:
244  list of PubMed ID's that match search string and XML search status"
245   (let ((search-results (pubmed-query-status searchstr :maximum maximum :start start)))
246     (values (extract-pmid-list search-results) search-results)))
247
248 (defun pubmed-query-status (searchstr &key start maximum)
249   "Performs a Pubmed search and returns XML results of PubMed search
250  which contains PubMed ID's and status results"
251   (let ((query-alist `(("db" . "m") ("term" . ,searchstr) ("mode" . "xml"))))
252     (when maximum (push (cons "dispmax" maximum) query-alist))
253     (when start (push (cons "dispstart" start) query-alist))
254     (net.aserve.client:do-http-request
255      (format nil "http://~a~a" +pubmed-host+ +pubmed-query-url+)
256      :method :get
257      :query query-alist)))
258
259 (defun pubmed-fetch-pmids-xml (pmids)
260   "Fetch articles for a list of PubMed ID's and return XML string"
261   (setq pmids (mklist pmids)) ;; Ensure list
262   (when pmids
263       (net.aserve.client:do-http-request
264        (format nil "http://~a~a" +pubmed-host+ +pubmed-fetch-url+)
265        :method :get
266        :query 
267        `(("db" . "PubMed") ("report" . "xml") ("mode" . "text")
268          ("id" . ,(list-to-delimited-string pmids #\,))))))
269
270 ;;; XML Extraction Routines
271
272 (defun extract-article-set (results)
273   "Extract article set from PubMed XML string, return results in pm-article-set class"
274   (multiple-value-bind (as-start as-end as-next) 
275       (positions-xml-tag-contents "PubmedArticleSet" results)
276     (declare (ignore as-end as-next))
277     (when as-start
278       (let ((done nil)
279             (articles '())
280             (pos as-start))
281         (until done
282                (multiple-value-bind
283                    (a-start a-end a-next)
284                    (positions-xml-tag-contents "PubmedArticle" results pos)
285                  (if a-start
286                      (progn
287                        (push (extract-article results a-start a-end) articles)
288                        (setq pos a-next)
289                        )
290                    (setq done t))))
291         (nreverse articles)))))
292
293 (defun extract-article (xmlstr a-start a-end)
294   "Extract article contents from PubMed XML string and return results in pm-article class"
295   (let ((article (make-instance 'pm-article)))
296     (setf 
297         (article-pmid article) (parse-integer (xml-tag-contents "PMID" xmlstr a-start a-end))
298         (article-title article) (xml-tag-contents "ArticleTitle" xmlstr a-start a-end)
299         (article-journal article) (xml-tag-contents "MedlineTA" xmlstr a-start a-end)
300         (article-pages article) (xml-tag-contents "MedlinePgn" xmlstr a-start a-end)
301         (article-affiliation article) (xml-tag-contents "Affiliation" xmlstr a-start a-end)
302         (article-abstract article) (xml-tag-contents "AbstractText" xmlstr a-start a-end))
303     (multiple-value-bind (ji-start ji-end ji-next)
304         (positions-xml-tag-contents "JournalIssue" xmlstr a-start a-end)
305       (declare (ignore ji-next))
306       (setf
307           (article-volume article) (xml-tag-contents "Volume" xmlstr ji-start ji-end)
308           (article-issue article) (xml-tag-contents "Issue" xmlstr ji-start ji-end))
309       (aif (xml-tag-contents "MedlineDate" xmlstr ji-start ji-end)
310            (setf (article-date article) it)
311            (setf (article-date article)
312              (concatenate 'string (xml-tag-contents "Year" xmlstr ji-start ji-end)
313                           (aif (xml-tag-contents "Month" xmlstr ji-start ji-end)
314                                (format nil " ~a" it)
315                                "")))))
316           
317     (multiple-value-bind (al-start al-end al-next)
318         (positions-xml-tag-contents "AuthorList" xmlstr a-start a-end)
319       (declare (ignore al-next))
320       (setf (article-authors article)
321         (when al-start
322             (let ((done nil)
323                   (authors '())
324                   (pos al-start))
325               (until done
326                      (multiple-value-bind
327                          (au-start au-end au-next)
328                          (positions-xml-tag-contents "Author" xmlstr pos al-end)
329                        (if au-start
330                            (progn
331                              (push (extract-author xmlstr au-start au-end) authors)
332                              (setq pos au-next))
333                          (setq done t))))
334               (nreverse authors)))))
335
336     (multiple-value-bind (mhl-start mhl-end mhl-next)
337         (positions-xml-tag-contents "MeshHeadingList" xmlstr a-start a-end)
338       (declare (ignore mhl-next))
339       (setf (article-mesh-headings article)
340         (when mhl-start
341             (let ((done nil)
342                   (mesh-headings '())
343                   (pos mhl-start))
344               (until done
345                      (multiple-value-bind
346                          (mh-start mh-end mh-next)
347                          (positions-xml-tag-contents "MeshHeading" xmlstr pos mhl-end)
348                        (if mh-start
349                            (progn
350                              (push (extract-mesh-heading xmlstr mh-start mh-end) mesh-headings)
351                              (setq pos mh-next)
352                              )
353                          (setq done t))))
354               (nreverse mesh-headings)))))
355
356     article))
357
358 (defun extract-author (xmlstr start end)
359   "Extract author name from XML string"
360   (let ((last-name (xml-tag-contents "LastName" xmlstr start end))
361         (initials  (xml-tag-contents "Initials" xmlstr start end)))
362     (concatenate 'string last-name " " initials)))
363
364 (defun extract-mesh-heading (xmlstr start end)
365   "Extract and format mesh headings from XML string"
366   (let ((desc (xml-tag-contents "DescriptorName" xmlstr start end))
367         (sh  (xml-tag-contents "SubHeading" xmlstr start end)))
368     (if sh
369         (format nil "~a(~a)" desc sh)
370       desc)))
371
372 (defun extract-pmid-list (results)
373   "Returns list of PubMed ID's from XML result string"
374   (if (or (search "<ERROR>" results)
375           (search "<H1>Server Error</H1>" results))
376       (error 'pubmed-server-error :response results)
377     (awhen (xml-tag-contents "Id" results)
378            (delimited-string-to-list it #\space))))
379
380
381