forked from gringer/bioinfscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
get_sequences.pl
executable file
·279 lines (248 loc) · 7.93 KB
/
get_sequences.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#!/usr/bin/perl
# get_sequences.pl -- retrieves sequences from NCBI, using a file list
# Author: David Eccles (gringer) 2011 <david.eccles@mpi-muenster.mpg.de>
# use like this:
# ./get_sequences.pl names.txt nuccore > out.fasta
use warnings;
use strict;
use LWP::Simple;
use LWP::UserAgent;
use XML::Parser;
use XML::Simple;
use Cwd;
sub usage(){
print "usage : get_sequences.pl <accession file> <database>\n";
print "output: a fasta file with sequence data\n";
print "\nOther options:\n";
print " -help : Show this screen\n";
print " -v : increase verbosity of output\n";
}
our @processContent = ();
our $indentLevel = 0;
our %currentEntry = ();
our $currentName = "";
our $currentType = "";
our $headersPrinted = 0; # false
our $verbose = 0;
our $resultsReceived = 0;
our $totalReceived = 0;
our @validHeadings = ();
our $xParse = XML::Parser->new('Style' => 'Stream');
$xParse->setHandlers (
Start => \&StartTag,
End => \&EndTag,
Char => \&Characters);
our $xPStream;
sub StartTag {
my ($e, $name, %lookup) = @_;
if($name eq 'DocSum'){
%currentEntry = ();
}
if($name eq 'Id'){
$currentName = 'Id';
} elsif(($name eq 'Item') && $lookup{'Name'}){
if(($lookup{'Type'}) && ($lookup{'Type'} eq 'String')){
$currentType = 'String';
} else {
$currentType = '';
}
$currentName = $lookup{'Name'};
} else {
$currentName = '';
}
if($verbose > 1){
printf(STDERR "%sStarting %s... ", (' ' x $indentLevel), $name);
foreach my $key (keys(%lookup)){
printf(STDERR "%s=%s;", $key, $lookup{$key});
}
print(STDERR "\n");
}
$indentLevel++;
}
sub EndTag {
my ($e, $name) = @_;
# do something with end tags
$indentLevel--;
if($name eq 'DocSum'){
$resultsReceived++;
# foreach my $key (keys(%currentEntry)){
# print(STDERR "$key=".$currentEntry{$key}.":");
# }
# print(STDERR "\n");
my @headings = ();
my @values = ();
if(!@validHeadings){
@headings = ('Id', 'Gi','NomenclatureSymbol',
'NomenclatureName', 'TaxId',
'ChrAccVer', 'Chromosome', 'ChrStart', 'ChrStop',
'Caption', 'Title', 'Extra');
@validHeadings =
grep {defined($currentEntry{$_})?$_:0} @headings;
# print column headers
print(join(',',@validHeadings)."\n");
print("# ".join(',',keys(%currentEntry))."\n");
$headersPrinted = 1; # true
}
@values = map{
defined($currentEntry{$_})?$currentEntry{$_}:"";
} @validHeadings;
printf("%s\n", join(',', @values));
printf(STDERR "%s\n", join(";", %currentEntry)) if ($verbose > 1);
if(($verbose > 0) && ($resultsReceived % 1000 == 0)){
print(STDERR ".");
}
}
if(($name eq 'Item') || ($name eq 'Id')){
$currentType = '';
$currentName = '';
}
if($verbose > 1){
printf(STDERR "%sEnding %s\n", (' ' x $indentLevel), $name);
}
}
sub Characters {
my ($e, $data) = @_;
if($verbose > 1){
if($data !~ /^\s*$/){
printf(STDERR "%sData: %s\n", (' ' x $indentLevel), $data);
}
}
if($currentName eq 'Id'){
$currentEntry{'Id'} = $data;
printf(STDERR "%sAdding Id=%s\n", (' ' x $indentLevel),
$data) if ($verbose > 1);
} elsif($currentName){
# remove trailing spaces
$data =~ s/\s+$//;
if(($currentType eq 'String') && ($data)){
# surround string values with quotes
$data = "\"$data\"";
}
printf(STDERR "%sAdding %s=%s\n", (' ' x $indentLevel),
$currentName, $data) if ($verbose > 1);
$currentEntry{$currentName} = $data;
}
}
sub parseText {
my ($data, $resp, @other) = @_;
$xPStream->parse_more($data);
}
my $esearchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
my $efetchURL = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
my $searchParams = 'usehistory=y&tool=get_sequences.pl';
my $fetchParams = 'retmode=fasta&rettype=text&tool=get_sequences.pl';
my $dbName = 'nuccore';
my $fileExtension = "_$dbName.fa";
my $fetchFasta = 1;
my @files = ();
my @queryNames = ();
my $database = "";
while(@ARGV){
my $argument = shift(@ARGV);
if(-f $argument){ # argument is a file that exists
push(@files, $argument);
} elsif ($argument eq "-help"){
usage();
exit(0);
} elsif ($argument eq "-v"){
$verbose++;
print(STDERR "increasing verbosity\n");
} else {
if(($argument =~ /^([a-z_]+)$/i) && !$database){
$database = $argument;
} else {
print(STDERR "Error: unknown option '$argument'\n");
usage();
exit(2);
}
}
}
@ARGV = @files;
if(!$database){
print(STDERR "Error: necessary options were not specified. ".
"Please indicate the database that names are from\n");
usage();
exit(2);
}
my $dbquery = 'db='.$database;
while(<>){
chomp;
if(!(/^\s*$/)){
push(@queryNames, $_);
}
}
if(!@queryNames){
print(STDERR "Error: no query terms provided\n");
usage();
exit(2);
}
# convert to Entrez query
my @formattedTerms = map{$_.'[Accession]'} @queryNames;
while(@formattedTerms){
## search for (at most) 200 accessions at a time
my @formattedSub = splice(@formattedTerms, 0, 200);
my $query = 'term='.join (" OR ", @formattedSub);
$totalReceived = 0;
my $ua = LWP::UserAgent->new;
# use equery to get list of IDs
my $shortenedQuery = $query;
$shortenedQuery =~ s/^(.{50}).*(.{50})$/$1...$2/;
printf(STDERR "querying IDs for '%s' in database '%s'... ",
$shortenedQuery, $database);
my $searchURL = $esearchURL.join("&",$dbquery,$query,$searchParams);
printf(STDERR "URL[%s]... ", $searchURL) if ($verbose > 1);
my $res = $ua->post($searchURL);
if (!$res->is_success) {
printf(STDERR "Error: failed to fetch results\n");
printf(STDERR "%s\n", $res->status_line);
exit(3);
}
my %searchResult = %{XMLin($res->content)};
my %fetchResult = ();
if (exists($searchResult{'WebEnv'})) {
printf(STDERR "done\n");
# retrieve environment/query for easier retrieval of results
my $webEnv = 'WebEnv='.$searchResult{'WebEnv'};
my $queryKey = 'query_key='.$searchResult{'QueryKey'};
while ($totalReceived < $searchResult{'Count'}) {
# use efetch to get actual results
printf(STDERR "retrieving %d results for '%s' in database '%s' ...",
($searchResult{'Count'} - $totalReceived), $shortenedQuery,
$database);
my $resultStart = sprintf("retstart=%d",$totalReceived);
my $fetchURL = $efetchURL.join("&",$dbquery,$webEnv,$queryKey,
$fetchParams,$resultStart);
printf(STDERR "URL[%s]...", $fetchURL) if ($verbose > 1);
my $res = $ua->get($fetchURL);
if ($res->is_success) {
my $content = $res->content;
if ($content =~ />/) {
for (split /^/, $content) {
if (/^>/) {
$resultsReceived++;
}
if (!/^\s*$/) {
print;
}
}
}
printf(STDERR " done (%d results received)\n", $resultsReceived);
} else {
printf(STDERR "Error: failed to fetch results\n");
exit(3);
}
if ($resultsReceived == 0) {
printf(STDERR "Warning: no more results received, ".
"but more expected\n");
$totalReceived = $searchResult{'Count'};
}
$totalReceived += $resultsReceived;
$resultsReceived = 0;
}
} elsif (exists($searchResult{'ERROR'})) {
printf(STDERR "failed to find any results [%s]\n",
$searchResult{'ERROR'});
} else {
printf(STDERR "failed to find any results\n");
}
}