Debian Codegraph @

ecollect

raw
1 #!/bin/bash
2
3 # ===========================================================================
4 #
5 # PUBLIC DOMAIN NOTICE
6 # National Center for Biotechnology Information (NCBI)
7 #
8 # This software/database is a "United States Government Work" under the
9 # terms of the United States Copyright Act. It was written as part of
10 # the author's official duties as a United States Government employee and
11 # thus cannot be copyrighted. This software/database is freely available
12 # to the public for use. The National Library of Medicine and the U.S.
13 # Government do not place any restriction on its use or reproduction.
14 # We would, however, appreciate having the NCBI and the author cited in
15 # any work or product based on this material.
16 #
17 # Although all reasonable efforts have been taken to ensure the accuracy
18 # and reliability of the software and data, the NLM and the U.S.
19 # Government do not and cannot warrant the performance or results that
20 # may be obtained by using this software or data. The NLM and the U.S.
21 # Government disclaim all warranties, express or implied, including
22 # warranties of performance, merchantability or fitness for any particular
23 # purpose.
24 #
25 # ===========================================================================
26 #
27 # File Name: ecollect
28 #
29 # Author: Jonathan Kans, Aaron Ucko
30 #
31 # Version Creation Date: 10/31/2024
32 #
33 # ==========================================================================
34
35 pth=$( dirname "$0" )
36
37 case "$pth" in
38 /* )
39 ;; # already absolute
40 * )
41 pth=$(cd "$pth" && pwd)
42 ;;
43 esac
44
45 case ":$PATH:" in
46 *:"$pth":* )
47 ;;
48 * )
49 PATH="$PATH:$pth"
50 export PATH
51 ;;
52 esac
53
54 # handle common flags - dot command is equivalent of "source"
55
56 if [ ! -f "$pth"/ecommon.sh ]
57 then
58 echo "ERROR: Unable to find '$pth/ecommon.sh' file" >&2
59 exit 1
60 fi
61
62 . "$pth"/ecommon.sh
63
64 # INITIALIZE SPECIFIC FLAGS
65
66 api_key=""
67 base="https://eutils.ncbi.nlm.nih.gov/entrez/eutils/"
68 dbase=""
69 web_env=""
70 qry_key=""
71 qury=""
72 ids=""
73 rest=""
74 input=""
75 num=""
76 solrcount=false
77 solrsubset=false
78 retmax=9999
79 tranquil=false
80 debug=false
81
82 quick=false
83
84 # read API Key from environment variable
85
86 if [ -n "${NCBI_API_KEY}" ]
87 then
88 api_key="${NCBI_API_KEY}"
89 fi
90
91 # READ COMMAND-LINE ARGUMENTS
92
93 while [ $# -gt 0 ]
94 do
95 tag="$1"
96 rem="$#"
97 case "$tag" in
98
99 # server location
100 -base )
101 CheckForArgumentValue "$tag" "$rem"
102 shift
103 base="$1"
104 shift
105 ;;
106 -internal )
107 base="https://eutils-internal.ncbi.nlm.nih.gov/entrez/eutils/"
108 shift
109 ;;
110 -dev )
111 base="https://dev.ncbi.nlm.nih.gov/entrez/eutils/"
112 shift
113 ;;
114
115 # special commands for SOLR workaround
116 -count )
117 CheckForArgumentValue "$tag" "$rem"
118 shift
119 qury="$1"
120 solrcount=true
121 shift
122 ;;
123 -subset )
124 CheckForArgumentValue "$tag" "$rem"
125 shift
126 qury="$1"
127 solrsubset=true
128 shift
129 ;;
130 -retmax )
131 # used by SOLR arguments
132 CheckForArgumentValue "$tag" "$rem"
133 shift
134 retmax="$1"
135 shift
136 ;;
137
138 # source database
139 -db )
140 CheckForArgumentValue "$tag" "$rem"
141 shift
142 dbase="$1"
143 shift
144 ;;
145
146 # arguments for various data sources
147 -web )
148 CheckForArgumentValue "$tag" "$rem"
149 shift
150 web_env="$1"
151 shift
152 ;;
153 -key )
154 CheckForArgumentValue "$tag" "$rem"
155 shift
156 qry_key="$1"
157 shift
158 ;;
159 -query )
160 CheckForArgumentValue "$tag" "$rem"
161 shift
162 qury="$1"
163 shift
164 ;;
165 -id )
166 CheckForArgumentValue "$tag" "$rem"
167 shift
168 ids="$1"
169 shift
170 while [ $# -gt 0 ]
171 do
172 case "$1" in
173 -* )
174 break
175 ;;
176 "" )
177 # skip empty argument from internal call
178 shift
179 break
180 ;;
181 * )
182 # concatenate run of UIDs with commas
183 ids="$ids,$1"
184 shift
185 ;;
186 esac
187 done
188 ;;
189 -rest )
190 CheckForArgumentValue "$tag" "$rem"
191 shift
192 rest="$1"
193 shift
194 ;;
195 -input )
196 CheckForArgumentValue "$tag" "$rem"
197 shift
198 input="$1"
199 shift
200 ;;
201
202 # date restriction
203 -days | -reldate )
204 CheckForArgumentValue "$tag" "$rem"
205 shift
206 reldate="$1"
207 shift
208 ;;
209 -mindate )
210 CheckForArgumentValue "$tag" "$rem"
211 shift
212 mindate="$1"
213 shift
214 ;;
215 -maxdate )
216 CheckForArgumentValue "$tag" "$rem"
217 shift
218 maxdate="$1"
219 shift
220 ;;
221 -datetype )
222 CheckForArgumentValue "$tag" "$rem"
223 shift
224 datetype="$1"
225 shift
226 ;;
227
228 # number of records if known
229 -num )
230 CheckForArgumentValue "$tag" "$rem"
231 shift
232 num="$1"
233 shift
234 ;;
235
236 # -tranquil flag conditionally ignores "No items found" message and automatic retries
237 -tranquil )
238 shift
239 tranquil=true
240 ;;
241
242 # verbose debugging
243 -debug )
244 shift
245 debug=true
246 ;;
247
248 # do not call ParseCommonArgs from ecollect
249
250 # unrecognized argument
251 * )
252 DisplayError "Unrecognized argument $1"
253 shift
254 ;;
255 esac
256 done
257
258 # EXECUTE NETWORK REQUEST WITH AUTOMATIC RETRY
259
260 RunWithCollectArgs() {
261
262 AddIfNotEmpty -reldate "$reldate" \
263 AddIfNotEmpty -mindate "$mindate" \
264 AddIfNotEmpty -maxdate "$maxdate" \
265 AddIfNotEmpty -datetype "$datetype" \
266 AddIfNotEmpty -api_key "$api_key" \
267 RunWithLogging "$@"
268 }
269
270 # INTERNAL UTILITY FUNCTIONS TO WORK AROUND PUBMED SOLR SERVER LIMITATIONS
271
272 GetSOLRCount() {
273
274 if [ -n "$qury" ] && [ "$dbase" = "pubmed" ]
275 then
276 # count is accurate even for PubMed SOLR server
277 res=$( RunWithCollectArgs nquire -url "$base" esearch.fcgi -retmax 0 -db "$dbase" -term "$qury" )
278 if [ -n "$res" ]
279 then
280 echo "$res" | sed -e 's|<TranslationStack>.*</TranslationStack>||' |
281 xtract -pattern eSearchResult -element Count
282 fi
283 else
284 DisplayError "Missing argument describing data source"
285 exit 1
286 fi
287 }
288
289 GetSOLRSubset() {
290
291 if [ -n "$qury" ] && [ "$dbase" = "pubmed" ]
292 then
293 # count is accurate even for PubMed SOLR server
294 res=$( RunWithCollectArgs nquire -url "$base" esearch.fcgi -retmax "$retmax" -db "$dbase" -term "$qury" )
295 if [ -n "$res" ]
296 then
297 echo "$res" |
298 sed -e 's|<QueryTranslation>.*</QueryTranslation>||' |
299 sed -e 's|<TranslationSet>.*</TranslationSet>||' |
300 sed -e 's|<TranslationStack>.*</TranslationStack>||' |
301 grep '.' | sed -e "s|$(printf '\t')| |"
302 fi
303 else
304 DisplayError "Missing argument describing data source"
305 exit 1
306 fi
307 }
308
309 # PUBMED SOLR SERVER WORKAROUND
310
311 SearchSOLR() {
312
313 # break PubMed SOLR server requests into chunks of no more than 9999 PMIDs
314
315 local fr
316 local to
317 local md
318 local nx
319
320 qy="$1"
321 fr="$2"
322 to="$3"
323
324 # -tranquil flag specifically suppresses "No items found" message and automatic retries
325 count=$( ecollect -db pubmed -count "( ${qy} AND ${fr}:${to} [UID])" \
326 -reldate "$reldate" -mindate "$mindate" -maxdate "$maxdate" -datetype "$datetype" \
327 -tranquil < /dev/null )
328 if [ -n "$count" ]
329 then
330 if [ "$count" -eq 0 ]
331 then
332 if [ "$verbose" = true ]
333 then
334 printf " %08d : %08d [UID] . %d\n" "$fr" "$to" "$count" >&2
335 fi
336 elif [ "$count" -le 9999 ]
337 then
338 if [ "$verbose" = true ]
339 then
340 printf " %08d : %08d [UID] * %d\n" "$fr" "$to" "$count" >&2
341 fi
342 ecollect -db pubmed -subset "( ${qy} AND ${fr}:${to} [UID])" \
343 -reldate "$reldate" -mindate "$mindate" -maxdate "$maxdate" -datetype "$datetype" \
344 -tranquil < /dev/null |
345 xtract -pattern eSearchResult -block IdList -sep "\n" -element Id |
346 sort -n | uniq
347 else
348 if [ "$verbose" = true ]
349 then
350 printf " %08d : %08d [UID] - %d\n" "$fr" "$to" "$count" >&2
351 fi
352 # partition half way between the points
353 md=$(( fr / 2 + to / 2 ))
354 nx=$(( md + 1 ))
355 SearchSOLR "$qy" "$fr" "$md"
356 SearchSOLR "$qy" "$nx" "$to"
357 fi
358 else
359 if [ "$verbose" = true ]
360 then
361 printf " %08d : %08d [UID] ~ 0\n" "$fr" "$to" >&2
362 fi
363 fi
364 }
365
366 GenerateFromSOLR() {
367
368 if [ -z "$num" ]
369 then
370 num=$( ecollect -db pubmed -count "$qury" \
371 -reldate "$reldate" -mindate "$mindate" -maxdate "$maxdate" -datetype "$datetype" \
372 -tranquil < /dev/null )
373 fi
374
375 total="$num"
376
377 if [ "$total" -lt 1 ]
378 then
379 exit 0
380 fi
381
382 minPMID=1
383
384 # remove pubmed books inserted at front of list, but still retrieve 1000 PMIDs and take maximum
385 maxPMID=$(
386 ecollect -db pubmed -subset "all [SB] NOT pubmed books [SB]" -retmax 1000 \
387 -reldate "$reldate" -mindate "$mindate" -maxdate "$maxdate" -datetype "$datetype" \
388 -tranquil < /dev/null |
389 xtract -pattern eSearchResult -max Id
390 )
391
392 # reality check for successful creation of maxPMID variable
393 if [ -z "$maxPMID" ]
394 then
395 echo "Unable to get top PMID" >&2
396 exit 0
397 fi
398
399 # occasional older records, newly found and submitted by publishers,
400 # will be lower in the sort order (EDAT is set to its PDAT value), so
401 # increment by 1000 to accommodate this rare situation
402 maxPMID=$(( maxPMID + 1000 ))
403
404 uids=$( SearchSOLR "$qury" "$minPMID" "$maxPMID" | sort -n | uniq )
405
406 if [ -n "$uids" ]
407 then
408 cumulative=$( echo "$uids" | wc -l | tr -d ' ' )
409 if [ "$verbose" = true ]
410 then
411 echo "cumulative: ${cumulative}, total: ${total}" >&2
412 fi
413 fi
414
415 echo "$uids"
416 }
417
418 # return UID list from specified source or Entrez history server
419
420 GenerateUidList() {
421
422 # normalize database to lower-case (e.g., SRA -> sra) and remove whitespace
423 dbase=$( echo "$dbase" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]' )
424
425 # check for empty database argument
426 if [ -z "$dbase" ]
427 then
428 DisplayError "Missing -db argument"
429 exit 1
430 fi
431
432 # first check for UIDs stored in Entrez history server
433
434 if [ -n "$web_env" ] && [ -n "$qry_key" ]
435 then
436 # obtain raw UIDs from history server
437 chunk=25000
438 mxx=0
439 if [ "$dbase" = "pubmed" ]
440 then
441 chunk=10000
442 if [ "$quick" = false ]
443 then
444 mxx=9999
445 fi
446 fi
447 GenerateHistoryChunks "$chunk" 0 "$mxx" |
448 while read fr chnk
449 do
450 RunWithCollectArgs nquire -url "$base" efetch.fcgi \
451 -query_key "$qry_key" -WebEnv "$web_env" -retstart "$fr" -retmax "$chnk" \
452 -db "$dbase" -rettype uilist -retmode text
453 done
454
455 else
456
457 # otherwise EDirect supports several possible sources for input of raw UIDs
458
459 if [ -n "$qury" ] && [ "$dbase" = "pubmed" ]
460 then
461 # workaround for PubMed SOLR server limit of 10K UIDs per query
462 slr=$( GenerateFromSOLR )
463 if [ -n "$slr" ]
464 then
465 nm=$( echo "$slr" | wc -l | tr -d ' ' )
466 if [ -n "$nm" ] && [ -n "$num" ] && [ "$nm" -ne "$num" ]
467 then
468 DisplayWarning "Actual PMID count ${nm} does not match expected total ${num}"
469 fi
470 fi
471 echo "$slr"
472
473 elif [ -n "$ids" ]
474 then
475 # LookupSpecialAccessions instantiates converted accessions into $ids variable,
476 # so -id argument, if populated, must be used before $rest and $input
477 echo "$ids"
478
479 elif [ -n "$rest" ]
480 then
481 # raw UIDs or instantiated UIDs extracted from ENTREZ_DIRECT message
482 echo "$rest"
483
484 elif [ -n "$input" ]
485 then
486 # input file of raw UIDs
487 cat "$input"
488
489 else
490 DisplayError "Missing argument describing data source"
491 exit 1
492
493 fi |
494 # faster version of accn-at-a-time without case transformation
495 tr -cs a-zA-Z0-9_. '\n'
496
497 fi |
498
499 # sort and unique final UID results
500 sort -n | uniq
501 }
502
503 # SPECIALIZED QUERY VARIANTS FOR PUBMED SOLR WORKAROUND
504
505 if [ "$solrcount" = true ]
506 then
507 GetSOLRCount
508 exit 0
509 fi
510
511 if [ "$solrsubset" = true ]
512 then
513 GetSOLRSubset
514 exit 0
515 fi
516
517 # NORMAL QUERY
518
519 GenerateUidList
520
521 exit 0