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