]> git.donarmstrong.com Git - reference.git/blob - .svn/pristine/40/4087eb7177bb14e94e5e1535ecbcbced384e458c.svn-base
Import original source of Reference 0-Reference
[reference.git] / .svn / pristine / 40 / 4087eb7177bb14e94e5e1535ecbcbced384e458c.svn-base
1 # This module is part of Refence, and is released under the terms of
2 # the GPL version 2, or any later version. See the file README and
3 # COPYING for more information.
4 # Copyright 2003 by Don Armstrong <don@donarmstrong.com>.
5 # $Id$
6
7 package Reference::Retrieve::PubMed;
8
9 =head1 NAME
10
11 Reference::Retrieve::PubMed -- Reference Retrieval from PubMed
12
13 =head1 SYNOPSIS
14
15      my $reference = Reference::Retrieve::PubMed::get_reference(-pmid=>123456);
16      my @references = Reference::Retrieve::PubMed::get_reference(-query=>'John Smith[AUTHOR] AND 230[Pages]',limit=>50);
17
18
19 =head1 DESCRIPTION
20
21 Uh. Retreives references from pubmed. Yeah.
22
23 =head1 BUGS
24
25 None known.
26
27 =cut
28
29
30 use strict;
31 use vars qw($REVISION $DEBUG);
32 use Carp;
33
34 use LWP::UserAgent;
35 use XML::Simple qw(:strict);
36 use Reference;
37
38 use HTML::Entities;
39
40 use Params::Validate qw(:types validate_with);
41
42 BEGIN{
43      ($REVISION) = q$LastChangedRevision$ =~ /\$LastChangedRevision:\s+([^\s+])/;
44      $DEBUG = 0 unless defined $DEBUG;
45 }
46
47
48 =head2 get_reference
49
50 =head3 Usage
51
52      my $reference = Reference::Retrieve::PubMed::get_reference(-pmid=>123456);
53      my @references = Reference::Retrieve::PubMed::get_reference(-query=>'John Smith[AUTHOR] AND 230[Pages]',-limit=>50);
54      my @references = Reference::Retrieve::PubMed::get_reference(-query=>{author=>'John Smith', pages=>'230'},-limit=>50)
55
56 =head3 Function
57
58 Retrives a reference from pubmed
59
60 =head3 Returns
61
62 In scalar context, effectively assumes -limit=>1 and returns the
63 highest listed reference according to the order, etc. [Probably only
64 usefull with -pmid.] In list context, returns all results (or until it
65 hits the -limit.)
66
67 =head3 Args
68
69 list of arguments to select a reference or collection of references from.
70
71
72 =cut
73
74 sub get_reference{
75      my %options = validate_with(params => @_,
76                                  spec   => {pubmed_site  => {default => 'http://www.ncbi.nlm.nih.gov'},
77                                             pmid_query   => {default => '/entrez/query.fcgi?cmd=Text&db=PubMed&dopt=XML&uid='},
78                                             search_query => {default => '/htbin-post/Entrez/query?db=m&form=4&dispmax=100&html=no&dopt=u&term='},
79                                             ua_agent     => {default => "DA Reference::Retreive::PubMed/$REVISION"},
80                                             email        => {default => "don+referenceretrieve$REVISION\@donarmstrong.com"},
81                                            },
82                                  allow_extra => 1,
83                                 );
84      my $ua = new LWP::UserAgent(agent => $options{ua_agent});
85 }
86
87 sub get_reference_by_pmid($;@){
88      my %options = validate_with(params => \@_,
89                                  spec   => {pmid => {type => SCALAR|ARRAYREF,
90                                                      #regex => qr/^\d+$/,
91                                                     },
92                                             pubmed_site  => {default => 'http://www.ncbi.nlm.nih.gov'},
93                                             pmid_query   => {default => '/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=full&id='},
94                                             search_query => {default => '/htbin-post/Entrez/query?db=m&form=4&dispmax=100&html=no&dopt=u&term='},
95                                             ua_agent     => {default => "DA Reference::Retreive::PubMed/$REVISION"},
96                                             email        => {default => "don+referenceretrieve$REVISION\@donarmstrong.com"},
97                                             useragent    => {optional => 1},
98                                            },
99                                  allow_extra => 1,
100                                 );
101      my $pmid = $options{pmid};
102
103      my $ua;
104      if ($options{useragent}) {
105           $ua = $options{useragent};
106      }
107      else {
108           $ua = new LWP::UserAgent(agent=>$options{ua_agent});
109      }
110      my $url = "$options{pubmed_site}$options{pmid_query}" . (ref($pmid) ? (join('&id=',@{$pmid})) : $pmid);
111      print STDERR "url: $url" if $DEBUG;
112      my $request = HTTP::Request->new('GET', $url);
113      my $response = $ua->request($request);
114      $response = $response->content;
115      print STDERR "response: $response" if $DEBUG;
116
117      # For some dumb reason, they send us xml with html
118      # entities. Ditch them.
119      #$response = decode_entities($response);
120      # It's even more freaking broken; they don't double encode them.
121      #$response =~ s/\&gt;(\s|$)/>$1/gso;
122      #$response =~ s/(?:(\s)\&lt;|&lt;(\/))/$1<$2/gso;
123      $response =~ s/&quot;/"/gso;
124
125      # Ditch any doctype
126      $response =~ s/^\s*<\?xml[^>]+>\s*//gso;
127      $response =~ s/^\s*<\!DOCTYPE[^>]+>\s*//gso;
128      # There is also a Pubmedarticleset
129      $response =~ s/^\s*<PubmedArticleSet>\s*//gso;
130      $response =~ s#</PubmedArticleSet>\s*$##gso;
131
132      # Add the opt so we get an array of PubMedArticle
133      $response = "<opt>$response</opt>";
134
135      print STDERR $response if $DEBUG;
136
137      # Figure out if there was an error in the search.
138
139      # Response should be in XML. Parse it.
140      my $xa = new XML::Simple;
141
142      my $ref_struct = $xa->XMLin($response, ForceArray => [ 'PubmedArticle' ],KeyAttr=>[]);
143
144      use Data::Dumper;
145      print STDERR Dumper($ref_struct) if $DEBUG;
146      # Handle the XML structure
147      my @references;
148      foreach my $ref (@{$ref_struct->{PubmedArticle}}) {
149           my $reference =  _create_reference_from_xml($ref,$ua);
150           if (not defined $reference) {
151                warn "Unable to create reference for $ref->{MedlineCitation}->{PMID}\n";
152           }
153           push @references, $reference;
154      }
155      if (wantarray) {
156           return @references;
157      }
158      return $references[0];
159 }
160
161 sub _create_reference_from_xml($$){
162      my ($ref,$ua) = @_;
163
164      # Figure out what type of reference this is. We only support
165      # Journal Articles right now.
166      my $types = {'journal article'=>'article',
167                   'letter'         =>'article',
168                  };
169      my $ref_type = undef;
170      my $reference = undef;
171      foreach my $type (keys %{$types}) {
172           if (ref($ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType}) eq 'ARRAY'){
173                my $pubtypes;
174                @{$pubtypes}{map {lc} @{$ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType}}} =
175                     (1) x @{$ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType}};
176                if ($pubtypes->{$type}) {
177                     $ref_type = $types->{$type};
178                     last;
179                }
180                else {
181                     next;
182                }
183           }
184           elsif (lc($ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType}) eq lc($type)) {
185                $ref_type = $types->{$type};
186                last;
187           }
188      }
189      if (not defined $ref_type) {
190           warn "Unsupported PublicationType: ".(ref($ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType})?
191                                                 join(',',@{$ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType}}):
192                                                 $ref->{MedlineCitation}->{Article}->{PublicationTypeList}->{PublicationType});
193           print STDERR Dumper($ref);
194           $ref_type = 'article';
195      }
196      local $_ = $ref_type;
197      if (/article/) {
198           use Reference::Type::Article;
199           $reference = new Reference::Type::Article;
200           my $xml_mapping = {author     => [ _fix_medline_authors($ref->{MedlineCitation}->{Article}->{AuthorList}) ],
201                              title      => [_fix_medline_title($ref->{MedlineCitation}->{Article}->{ArticleTitle})],
202                              abstract   => _fix_medline_abstract($ref->{MedlineCitation}->{Article}->{Abstract}->{AbstractText}),
203                              journal    => [_fix_medline_journal($ref->{MedlineCitation}->{Article}->{Journal},
204                                                                  $ref->{MedlineCitation}->{Article}->{MedlineJournalInfo},
205                                                                  $ua,
206                                                                  #@_, # configuration
207                                                                 )],
208                              _fix_ids($ref),
209                              # pmid       => $ref->{MedlineCitation}->{PMID},
210                              # medline_id => $ref->{MedlineCitation}->{MedlineID},
211                              volume     => [_fix_medline_ditch_empty($ref->{MedlineCitation}->{Article}->{Journal}->{JournalIssue}->{Volume})],
212                              date       => [_fix_medline_pubdate($ref->{MedlineCitation}->{Article}->{Journal}->{JournalIssue}->{PubDate})],
213                              number     => [_fix_medline_ditch_empty($ref->{MedlineCitation}->{Article}->{Journal}->{JournalIssue}->{Issue})],
214                              pages      => [_fix_medline_pages($ref->{MedlineCitation}->{Article}->{Pagination}->{MedlinePgn})],
215 #                            keywords   => [_fix_medline_keywords($ref->{MedlineCitation}->{MeshHeadingList},
216 #                                                                 $ref->{MedlineCitation}->{ChemicalList},
217 #                                                                )],
218 #                            &_find_pubmed_links($ref->{MedlineCitation}->{PMID},$ua),
219                             };
220           # Deal with author
221
222           foreach my $reference_key (keys %{$xml_mapping}) {
223                my $method = $reference->can($reference_key);
224                die "Reference::Type::Article was unable to handle $reference_key" if not $method;
225                if (defined $xml_mapping->{$reference_key} and $method) {
226                     if (ref($xml_mapping->{$reference_key})) {
227                          &{$method}($reference,@{$xml_mapping->{$reference_key}});
228                     }
229                     else {
230                          &{$method}($reference,$xml_mapping->{$reference_key});
231                     }
232                }
233                else {
234                     warn "Reference_key $reference_key was not defined or unable to handle type of key."
235                          if not defined $xml_mapping->{$reference_key} and $DEBUG;
236                }
237           }
238           return $reference;
239      }
240 }
241
242 sub _fix_medline_title($){
243      my $title = shift;
244
245      $title =~ s/\.$//;
246      return $title;
247 }
248
249 sub _fix_medline_abstract{
250     my $abstract = shift;
251     my $ret = '';
252     if (ref($abstract) and ref($abstract) eq 'ARRAY') {
253         for my $element (@{$abstract}) {
254             $ret .= "\n" if length $ret;
255             $ret .= $element->{Label}.': '.$element->{content};
256         }
257         return $ret;
258     } else {
259         return $abstract;
260     }
261 }
262
263
264 sub _fix_medline_authors($){
265      my $author_list = shift;
266      $author_list = $author_list->{Author};
267      my @authors;
268      $author_list = [$author_list] if ref($author_list) ne 'ARRAY';
269      foreach my $author (@{$author_list}) {
270           my %au;
271           $au{first} = $author->{ForeName} if exists $author->{ForeName};
272           $au{last}  = $author->{LastName} if exists $author->{LastName};
273           $au{initials} = $author->{Initials} if exists $author->{Initials};
274           $au{full};
275           push @authors,\%au;
276      }
277      return (author=>\@authors);
278 }
279
280 =head2 _fix_medline_journal
281
282 =head3 Usage
283
284      $reference->journal(_fix_medline_journal($ref->{MedlineCitation}->{Article}->{Journal},
285                                               $ref->{MedlineCitation}->{Article}->{MedlineJournalInfo},
286                                               $ua,));
287
288 =head3 Function
289
290 From the medline citation informatino returns a properly formatted
291 list of information for the journal reference listing.
292
293 =head3 Args
294
295 Journal information hashref
296
297 medline journal information hashref
298
299 user agent
300
301 =cut
302
303 sub _fix_medline_journal($$$;){
304      my ($journal,$medline_journal,$ua) = @_;
305      # journal takes fullname, issn, medlineabbr, pmid, and nlmuid
306      # Try to supply as much as possible.
307      # Use esearch to get pmjournalid
308      # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=journals&term=0021-9258
309      # use esummary to retreive the journalid
310      # <?xml version="1.0"?>
311      # <!DOCTYPE eSearchResult PUBLIC "-//NLM//DTD eSearchResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eSearch_020511.dtd">
312      # <eSearchResult>
313      #  <Count>1</Count>
314      #  <RetMax>1</RetMax>
315      #  <RetStart>0</RetStart>
316      #  <IdList>
317      #          <Id>4559</Id>
318      #
319      #  </IdList>
320      #  <TranslationSet>
321      #  </TranslationSet>
322      #  <TranslationStack>
323      #          <TermSet>
324      #                  <Term>0021-9258[All Fields]</Term>
325      #                  <Field>All Fields</Field>
326      #                  <Count>1</Count>
327      #
328      #                  <Explode>Y</Explode>
329      #          </TermSet>
330      #  </TranslationStack>
331      # </eSearchResult>
332
333      my $ISSN = $journal->{ISSN};
334      if (ref $ISSN) {
335           $ISSN = $ISSN->{content};
336      }
337      my $url = qq(http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=journals&term=$ISSN);
338      print STDERR "url: $url" if $DEBUG;
339      my $request = HTTP::Request->new('GET', $url);
340      my $response = $ua->request($request);
341      $response = $response->content;
342      print STDERR "response: $response" if $DEBUG;
343
344      my ($journal_id) = $response =~ m#<Id>\s*(\d+)\s*</Id>#i;
345
346      # http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=journals&id=4559
347      #      <?xml version="1.0"?>
348      # <!DOCTYPE eSummaryResult PUBLIC "-//NLM//DTD eSummaryResult, 11 May 2002//EN" "http://www.ncbi.nlm.nih.gov/entrez/query/DTD/eSummary_020511.dtd">
349      # <eSummaryResult>
350      # <DocSum>
351      #  <Id>4559</Id>
352      #  <Item Name="Title" Type="String">The Journal of biological chemistry.</Item>
353      #  <Item Name="MedAbbr" Type="String">J Biol Chem</Item>
354      #  <Item Name="IsoAbbr" Type="String">J. Biol. Chem.</Item>
355      #  <Item Name="NlmId" Type="String">2985121R</Item>
356      #
357      #  <Item Name="pISSN" Type="String">0021-9258</Item>
358      #  <Item Name="eISSN" Type="String">1083-351X</Item>
359      #  <Item Name="PublicationStartYear" Type="String">1905</Item>
360      #  <Item Name="PublicationEndYear" Type="String"></Item>
361      #  <Item Name="Publisher" Type="String">American Society for Biochemistry and Molecular Biology</Item>
362      #  <Item Name="Language" Type="String">eng</Item>
363      #
364      #  <Item Name="Country" Type="String">United States</Item>
365      # </DocSum>
366      #
367      # </eSummaryResult>
368      $url = qq(http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=journals&id=$journal_id);
369      print STDERR "url: $url" if $DEBUG;
370      $request = HTTP::Request->new('GET', $url);
371      $response = $ua->request($request);
372      $response = $response->content;
373      print STDERR "response: $response" if $DEBUG;
374
375      my %journal;
376      while ($response =~ m{^\s*(?:(?:<id>\s*(\d+)</id>)| # Match ids
377                            (?:<item\s+name=\"([^\"]+)\"\s+Type=\"String\">\s*([^<]+?)</item>))\s* # Match item Name clauses
378                            $}ixmg) {
379           if (not defined $2) {
380                $journal{id} = $1;
381           }
382           else {
383                $journal{lc($2)} = $3;
384           }
385      }
386      my %journal_mapping = (title       => q(title),
387                             medlineabbr => q(medabbr),
388                             isoabbr     => q(isoabbr),
389                             nlmid       => q(nlmid),
390                             issn        => q(pissn),
391                             eissn       => q(eissn),
392                             publisher   => q(publisher),
393                             pmid    => q(id)
394                            );
395      my @journal_entry;
396      foreach my $key (keys %journal_mapping) {
397           push @journal_entry,($key=>$journal{$journal_mapping{$key}});
398      }
399      return @journal_entry;
400 }
401
402 =head2 
403
404 =head3 Usage
405
406      $reference->date(_fix_medline_pubdate($ref->{MedlineCitation}->{Article}->{Journal}->{JournalIssue}->{PubDate}));
407
408 =head3 Function
409
410 =head3 Returns
411
412 =head3 Args
413
414 =cut
415
416 sub _fix_medline_pubdate($){
417      my ($date) = shift;
418      return (year=>$date->{Year},month=>$date->{Month},day=>$date->{Day}) if exists $date->{Year};
419      # Ok... punt.
420      if (exists $date->{MedlineDate}) {
421           my ($year,$month,$day) = split /\s+/,$date->{MedlineDate};
422           return (year=>$year,month=>$month,day=>$day)
423      }
424 }
425
426 =head2 _fix_medline_pages
427
428 =head3 Usage
429
430      pages      => [_fix_medline_pages($ref->{MedlineCitation}->{Article}->{Pagination}->{MedlinePgn})],
431
432 =head3 Function
433
434 Returns output with a list of pages appropriate for an Article type of
435 reference.
436
437 =cut
438
439 sub _fix_medline_pages($){
440      my ($pagination) = @_;
441      my ($start,$stop) = $pagination =~ /(\d*)\s*\-\s*(\d*)/;
442      if ($start > $stop) {
443          # this must be a reduced page listing; fix it up
444          $stop+=$start - $start % 10 ** (int(log($stop)/log(10))+1);
445      }
446      my @return;
447      push @return, (start=>$start) if defined $start and $start ne '';
448      push @return, (stop=>$stop) if defined $stop and $stop ne '';
449      return @return;
450 }
451
452 sub _find_pubmed_links($$){
453      my ($pmid,$ua) = @_;
454      return ();
455      #http://eutils.ncbi.nlm.nih.gov/entrez/query/static/elink_help.html
456      my $url = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi?dbfrom=pubmed&cmd=llinks&id=" . (ref($pmid) ? (join('&id=',@{$pmid})) : $pmid);
457      print STDERR "url: $url" if $DEBUG;
458      my $request = HTTP::Request->new('GET', $url);
459      my $response = $ua->request($request);
460      $response = $response->content;
461      print STDERR "response: $response" if $DEBUG;
462
463      # Response should be in XML. Parse it.
464      my $xa = new XML::Simple;
465
466      my $ref_struct = $xa->XMLin($response, ForceArray => ['IdUrlSet'], KeyAttr=>[]);
467
468      use Data::Dumper;
469      print STDERR Dumper($ref_struct);# if $DEBUG;
470      # Rearange data around Id.
471      my $links = {};
472      map {$links->{$_->{Id}}=$_->{ObjUrl}} @{$ref_struct->{LinkSet}->{IdUrlList}->{IdUrlSet}};
473      foreach my $obj_url (@{$links->{$pmid}->{ObjUrl}}) {
474           next unless $obj_url->{SubjectType} = 'publishers/providers';
475           #@links = _find_links_from_url($obj_url->{Url},$ua);
476      }
477      # Find publisher link
478      # If no publisher link, use the first aggregator link.
479 }
480
481 =head2 _fix_ids
482
483      _fix_ids
484
485
486
487 =cut
488
489 sub _fix_ids {
490      my ($ref) = @_;
491
492      my %ids_known = (medline => 'medline_id',
493                       pubmed  => 'pmid',
494                       doi     => 'doi',
495                      );
496      my %ids;
497      if (exists $ref->{PubmedData}{ArticleIdList}{ArticleId}) {
498           for my $art_id (ref($ref->{PubmedData}{ArticleIdList}{ArticleId}) eq 'ARRAY' ?
499                @{$ref->{PubmedData}{ArticleIdList}{ArticleId}}:
500                     ($ref->{PubmedData}{ArticleIdList}{ArticleId})) {
501                if (exists $ids_known{$art_id->{IdType}}) {
502                     $ids{$ids_known{$art_id->{IdType}}} = $art_id->{content};
503                }
504           }
505      }
506      if (not exists $ids{pmid}) {
507           $ids{pmid} = $ref->{MedlineCitation}->{PMID} if defined $ref->{MedlineCitation}->{PMID};
508      }
509      if (not exists $ids{medline_id}) {
510           $ids{medline_id} = $ref->{MedlineCitation}->{MedlineID} if defined $ref->{MedlineCitation}->{MedlineID};
511      }
512      return %ids;
513 }
514
515
516 =head2 _find_links_from_url
517
518 =head3 Usage
519
520 =head3 Function
521
522 =head3 Returns
523
524 =head3 Args
525
526 =cut
527
528 sub _find_links_from_url($$){
529      my ($link,$ua) = @_;
530
531      
532      
533 }
534
535 sub _fix_medline_ditch_empty($){
536      my ($value) = @_;
537
538      if (ref($value)) {
539           if (ref($value) eq 'HASH') {
540                if (scalar keys %{$value} > 0) {
541                     return $value;
542                }
543                else {
544                     return '';
545                }
546           }
547           elsif (ref($value) eq 'ARRAY') {
548                if (scalar @{$value} > 0) {
549                     return $value;
550                }
551                else {
552                     return '';
553                }
554           }
555           else {
556                return '';
557           }
558      }
559      else {
560           return $value if defined $value;
561           return '';
562      }
563 }
564
565
566 1;
567
568
569 __END__
570
571
572
573
574
575