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