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