Debian Codegraph @

cmd/edict.go

raw
1 // ===========================================================================
2 //
3 // PUBLIC DOMAIN NOTICE
4 // National Center for Biotechnology Information (NCBI)
5 //
6 // This software/database is a "United States Government Work" under the
7 // terms of the United States Copyright Act. It was written as part of
8 // the author's official duties as a United States Government employee and
9 // thus cannot be copyrighted. This software/database is freely available
10 // to the public for use. The National Library of Medicine and the U.S.
11 // Government do not place any restriction on its use or reproduction.
12 // We would, however, appreciate having the NCBI and the author cited in
13 // any work or product based on this material.
14 //
15 // Although all reasonable efforts have been taken to ensure the accuracy
16 // and reliability of the software and data, the NLM and the U.S.
17 // Government do not and cannot warrant the performance or results that
18 // may be obtained by using this software or data. The NLM and the U.S.
19 // Government disclaim all warranties, express or implied, including
20 // warranties of performance, merchantability or fitness for any particular
21 // purpose.
22 //
23 // ===========================================================================
24 //
25 // File Name: edict.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package main
32
33 import (
34 "eutils"
35 "github.com/gin-gonic/gin"
36 "net/http"
37 "os"
38 "path/filepath"
39 "runtime"
40 "strconv"
41 "strings"
42 )
43
44 // network server for EDirect local PubMed archive and search system
45
46 // run "go run edict.go" to start local server listening on port 8080,
47 // or run "go build edict.go" to generate "edict" binary executable
48
49 // ignore warnings printed when server is started (for now)
50
51 // nquire -edict is a convenience shortcut for -url "localhost:8080"
52
53 // export NQUIRE_EDICT_SERVER to override nquire -edict address when
54 // connecting to a remote server instance
55
56 var edictHelp = `
57 PubMed Local Archive Term Queries
58
59 Query evaluation includes Boolean operations and parenthetical expressions:
60
61 nquire -edict search -query "(literacy AND numeracy) NOT (adolescent OR child)"
62
63 Adjacent words in the query are treated as a contiguous phrase:
64
65 nquire -edict search -query "selective serotonin reuptake inhibitor [TITL]"
66
67 Terms are truncated with trailing asterisks:
68
69 nquire -edict search -query "Cozzarelli N* [AUTH] AND 2000:2005 [YEAR]"
70
71 Each plus sign will replace a single word inside a phrase:
72
73 nquire -edict search -query "vitamin c + + common cold"
74
75 Runs of tildes indicate the maximum distance between sequential phrases:
76
77 nquire -edict search -query "vitamin c ~ ~ common cold"
78
79 PubMed Record Retrieval
80
81 nquire -edict fetch -id 6275390 13970600
82
83 Retrieval of Compressed Records for faster Network Transfer
84
85 nquire -edict stream -id 6275390 13970600 | gunzip -c
86
87 Combined Query and Retrieval
88
89 nquire -edict search -query "PNAS [JOUR]" |
90 join-into-groups-of 1000 |
91 xargs -n 1 nquire -edict fetch -id
92
93 PubmedArticleSet Wrappers
94
95 (
96 nquire -edict fetch head
97 nquire -edict search -query "catabolite repress* [TIAB]" |
98 join-into-groups-of 1000 |
99 xargs -n 1 nquire -edict fetch -id
100 nquire -edict fetch tail
101 )
102
103 (
104 nquire -edict stream head
105 nquire -edict search -query "catabolite repress* [TIAB]" |
106 join-into-groups-of 1000 |
107 xargs -n 1 nquire -edict stream -id
108 nquire -edict stream tail
109 ) | gunzip -c
110
111 Citation Matching
112
113 From Command-Line Arguments:
114
115 nquire -edict match \
116 -author "Kans JA" -author "Casadaban MJ" \
117 -title "nucleotide sequences required for tn3 transposition immunity" \
118 -journal "J Bacteriol" -year 1989 -volume 171 -issue 4 -page 1904-14
119
120 From GenBank Flatfile:
121
122 efetch -db nuccore -id J01714 -format gb |
123 gbf2ref | transmute -format compact | grep CITATION |
124 grep -e published -e inpress | tr '\n' '\0' |
125 xargs -0 -n 50 nquire -edict match -citation |
126 xtract -pattern CITATION -def "-" -element ACCN REF PMID FAUT TITL
127
128 From ASN.1 Sequence Record:
129
130 efetch -db nuccore -id J01714 -format asn |
131 asn2ref | transmute -format compact |
132 grep CITATION | tr '\n' '\0' |
133 xargs -0 -n 50 nquire -edict match -citation
134
135 Journal Name Lookup
136
137 nquire -edict journal -query "biorxiv"
138
139 Documentation
140
141 nquire -edict help
142
143 nquire -edict version
144
145 `
146
147 var pmaSetHead = `<?xml version="1.0" encoding="UTF-8"?>
148 <!DOCTYPE PubmedArticle PUBLIC "-//NLM//DTD PubMedArticle, 1st January 2019//EN" "https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd">
149 <PubmedArticleSet>
150 `
151
152 var pmaSetTail = `</PubmedArticleSet>
153 `
154
155 var streamContentType = "application/octet-stream"
156
157 func main() {
158
159 // skip past executable name
160 args := os.Args[1:]
161
162 // default host and port set up for local test server
163 host := "0.0.0.0"
164 port := "8080"
165
166 // HOST, PORT, AND CONCURRENCY FLAGS
167
168 // performance arguments
169 chanDepth := 0
170 farmSize := 0
171 heapSize := 0
172 numServe := 0
173 goGc := 0
174
175 // processing option arguments
176 doCompress := false
177 doCleanup := false
178 doStrict := false
179 doMixed := false
180 doSelf := false
181 deAccent := false
182 deSymbol := false
183 doASCII := false
184 doStem := false
185 deStop := true
186
187 // do these first because -defcpu and -maxcpu can be sent from wrapper before other arguments
188
189 ncpu := runtime.NumCPU()
190 if ncpu < 1 {
191 ncpu = 1
192 }
193
194 // wrapper can limit maximum number of processors to use (undocumented)
195 maxProcs := ncpu
196 defProcs := 0
197
198 // concurrent performance tuning parameters, can be overridden by -proc and -cons
199 numProcs := 0
200 serverRatio := 4
201
202 // process any arguments on the command line
203 if len(args) > 0 {
204
205 inSwitch := true
206
207 // loop through arguments
208 for {
209 inSwitch = true
210
211 switch args[0] {
212
213 // host and port arguments
214 case "-host":
215 host = eutils.GetStringArg(args, "Host name")
216 args = args[1:]
217 case "-port":
218 port = eutils.GetStringArg(args, "Port number")
219 args = args[1:]
220
221 // concurrency arguments
222 case "-maxcpu":
223 maxProcs = eutils.GetNumericArg(args, "Maximum number of processors", 1, 1, ncpu)
224 args = args[1:]
225 case "-defcpu":
226 defProcs = eutils.GetNumericArg(args, "Default number of processors", ncpu, 1, ncpu)
227 args = args[1:]
228 // performance tuning flags
229 case "-proc":
230 numProcs = eutils.GetNumericArg(args, "Number of processors", ncpu, 1, ncpu)
231 args = args[1:]
232 case "-cons":
233 serverRatio = eutils.GetNumericArg(args, "Parser to processor ratio", 4, 1, 32)
234 args = args[1:]
235 case "-serv":
236 numServe = eutils.GetNumericArg(args, "Concurrent parser count", 0, 1, 128)
237 args = args[1:]
238 case "-chan":
239 chanDepth = eutils.GetNumericArg(args, "Communication channel depth", 0, ncpu, 128)
240 args = args[1:]
241 case "-heap":
242 heapSize = eutils.GetNumericArg(args, "Unshuffler heap size", 8, 8, 64)
243 args = args[1:]
244 case "-farm":
245 farmSize = eutils.GetNumericArg(args, "Node buffer length", 4, 4, 2048)
246 args = args[1:]
247 case "-gogc":
248 goGc = eutils.GetNumericArg(args, "Garbage collection percentage", 0, 50, 1000)
249 args = args[1:]
250
251 default:
252 // set flag to break out of for loop
253 inSwitch = false
254 }
255
256 if !inSwitch {
257 break
258 }
259
260 // skip past argument
261 args = args[1:]
262
263 if len(args) < 1 {
264 break
265 }
266 }
267 }
268
269 if numProcs == 0 {
270 if defProcs > 0 {
271 numProcs = defProcs
272 } else if maxProcs > 0 {
273 numProcs = maxProcs
274 }
275 }
276 if numProcs > ncpu {
277 numProcs = ncpu
278 }
279 if numProcs > maxProcs {
280 numProcs = maxProcs
281 }
282
283 eutils.SetTunings(numProcs, numServe, serverRatio, chanDepth, farmSize, heapSize, goGc, false)
284
285 eutils.SetOptions(doStrict, doMixed, doSelf, deAccent, deSymbol, doASCII, doCompress, doCleanup, doStem, deStop)
286
287 // DATA AVAILABILITY REALITY CHECKS
288
289 // obtain path from environment variable
290
291 archiveBase := eutils.GetLocalArchiveFolder("pubmed", "Archive", false)
292 postingsBase := eutils.GetLocalArchiveFolder("pubmed", "Postings", false)
293 dataBase := eutils.GetLocalArchiveFolder("pubmed", "Data", false)
294
295 // check to make sure local archive and search index directories are mounted
296 _, err := os.Stat(archiveBase)
297 if err != nil && os.IsNotExist(err) {
298 eutils.DisplayError("Local archive is not mounted")
299 os.Exit(1)
300 }
301 _, err = os.Stat(postingsBase)
302 if err != nil && os.IsNotExist(err) {
303 eutils.DisplayError("Local search index is not mounted")
304 os.Exit(1)
305 }
306 _, err = os.Stat(dataBase)
307 if err != nil && os.IsNotExist(err) {
308 eutils.DisplayError("Local mapping data is not mounted")
309 os.Exit(1)
310 }
311
312 // CREATE GIN ROUTER
313
314 // create gin router with default middleware
315 r := gin.Default()
316
317 // PRINT HELP TEXT
318
319 // nquire -get "localhost:8080/help"
320 r.GET("/help", func(c *gin.Context) {
321 c.String(http.StatusOK, edictHelp)
322 })
323 // nquire -url "localhost:8080/help"
324 r.POST("/help", func(c *gin.Context) {
325 c.String(http.StatusOK, edictHelp)
326 })
327
328 // PRINT VERSION NUMBER
329
330 // nquire -get "localhost:8080/version"
331 r.GET("/version", func(c *gin.Context) {
332 c.String(http.StatusOK, eutils.EDirectVersion)
333 })
334 // nquire -url "localhost:8080/version"
335 r.POST("version", func(c *gin.Context) {
336 c.String(http.StatusOK, eutils.EDirectVersion)
337 })
338
339 // FETCH PUBMED ARTICLE SET WRAPPERS
340
341 // nquire -get "localhost:8080/fetch/head"
342 r.GET("/fetch/head", func(c *gin.Context) {
343 c.String(http.StatusOK, pmaSetHead)
344 })
345 // nquire -url "localhost:8080/fetch/head"
346 r.POST("/fetch/head", func(c *gin.Context) {
347 c.String(http.StatusOK, pmaSetHead)
348 })
349
350 // nquire -get "localhost:8080/fetch/tail"
351 r.GET("/fetch/tail", func(c *gin.Context) {
352 c.String(http.StatusOK, pmaSetTail)
353 })
354 // nquire -url "localhost:8080/fetch/tail"
355 r.POST("/fetch/tail", func(c *gin.Context) {
356 c.String(http.StatusOK, pmaSetTail)
357 })
358
359 // STREAM COMPRESSED PUBMED ARTICLE SET WRAPPERS
360
361 // make gzip-compressed byte arrays of pmaSetHead and pmaSetTail
362 gzipHead := eutils.GzipString(pmaSetHead)
363 gzipTail := eutils.GzipString(pmaSetTail)
364
365 // nquire -get "localhost:8080/stream/head"
366 r.GET("/stream/head", func(c *gin.Context) {
367 c.Data(http.StatusOK, streamContentType, gzipHead)
368 })
369 // nquire -url "localhost:8080/stream/head"
370 r.POST("/stream/head", func(c *gin.Context) {
371 c.Data(http.StatusOK, streamContentType, gzipHead)
372 })
373
374 // nquire -get "localhost:8080/stream/tail"
375 r.GET("/stream/tail", func(c *gin.Context) {
376 c.Data(http.StatusOK, streamContentType, gzipTail)
377 })
378 // nquire -url "localhost:8080/stream/tail"
379 r.POST("/stream/tail", func(c *gin.Context) {
380 c.Data(http.StatusOK, streamContentType, gzipTail)
381 })
382
383 // PUBMED XML RECORD RETRIEVAL BY PMID
384
385 // common fetch function
386 pubmedFetch := func(c *gin.Context, uids string, tbo string) {
387
388 // concurrent fetching by multiple goroutines
389 uidq := eutils.ReadsUIDsFromString(uids)
390 strq := eutils.CreateFetchers(archiveBase, "pubmed", "", ".xml", "PubmedArticle", true, uidq)
391 unsq := eutils.CreateXMLUnshuffler(strq)
392
393 if uidq == nil || strq == nil || unsq == nil {
394 eutils.DisplayError("Unable to create archive reader")
395 os.Exit(1)
396 }
397
398 turbo := false
399 // look for "-turbo true" argument
400 if tbo == "true" {
401 turbo = true
402 }
403
404 retlength := len("\n")
405
406 // drain output channel
407 for curr := range unsq {
408
409 str := curr.Text
410
411 if str == "" {
412 continue
413 }
414
415 newln := false
416 if !strings.HasSuffix(str, "\n") {
417 newln = true
418 }
419
420 if turbo {
421 nxt := len(str)
422 if newln {
423 nxt += retlength
424 }
425 val := strconv.Itoa(nxt)
426 c.String(http.StatusOK, "<NEXT_RECORD_SIZE>"+val+"</NEXT_RECORD_SIZE>\n")
427 }
428
429 if newln {
430 c.String(http.StatusOK, str+"\n")
431 } else {
432 c.String(http.StatusOK, str)
433 }
434 }
435 }
436
437 // nquire -get "localhost:8080/fetch" -id "2539356,1937004"
438 r.GET("/fetch", func(c *gin.Context) {
439 uids := c.Query("id")
440 tbo := c.Query("turbo")
441 pubmedFetch(c, uids, tbo)
442 })
443 // nquire -url "localhost:8080/fetch" -id "2539356,1937004"
444 r.POST("/fetch", func(c *gin.Context) {
445 uids := c.PostForm("id")
446 tbo := c.PostForm("turbo")
447 pubmedFetch(c, uids, tbo)
448 })
449
450 // nquire -get "localhost:8080/fetch/2539356,1937004"
451 r.GET("/fetch/:id", func(c *gin.Context) {
452 uids := c.Param("id")
453 tbo := c.Param("turbo")
454 pubmedFetch(c, uids, tbo)
455 })
456 // nquire -url "localhost:8080/fetch/2539356,1937004"
457 r.POST("/fetch/:id", func(c *gin.Context) {
458 uids := c.Param("id")
459 tbo := c.Param("turbo")
460 pubmedFetch(c, uids, tbo)
461 })
462
463 // COMPRESSED PUBMED XML RECORD STREAMING BY PMID
464
465 // common stream function
466 pubmedStream := func(c *gin.Context, uids string) {
467
468 // concurrent fetching by multiple goroutines
469 uidq := eutils.ReadsUIDsFromString(uids)
470 strq := eutils.CreateCacheStreamers(archiveBase, "pubmed", "", ".xml", 0, uidq)
471 unsq := eutils.CreateXMLUnshuffler(strq)
472
473 if uidq == nil || strq == nil || unsq == nil {
474 eutils.DisplayError("Unable to create archive steamer")
475 os.Exit(1)
476 }
477
478 // drain output channel
479 for curr := range unsq {
480
481 data := curr.Data
482
483 if data == nil {
484 continue
485 }
486
487 c.Data(http.StatusOK, streamContentType, data)
488 }
489 }
490
491 // nquire -get "localhost:8080/stream" -id "2539356,1937004"
492 r.GET("/stream", func(c *gin.Context) {
493 uids := c.Query("id")
494 pubmedStream(c, uids)
495 })
496 // nquire -url "localhost:8080/stream" -id "2539356,1937004"
497 r.POST("/stream", func(c *gin.Context) {
498 uids := c.PostForm("id")
499 pubmedStream(c, uids)
500 })
501
502 // nquire -get "localhost:8080/stream/2539356,1937004"
503 r.GET("/stream/:id", func(c *gin.Context) {
504 uids := c.Param("id")
505 pubmedStream(c, uids)
506 })
507 // nquire -url "localhost:8080/stream/2539356,1937004"
508 r.POST("/stream/:id", func(c *gin.Context) {
509 uids := c.Param("id")
510 pubmedStream(c, uids)
511 })
512
513 // PMID LOOKUP FROM PUBMED PHRASE AND INDEXED FIELD SEARCH
514
515 // common search function
516 pubmedSearch := func(c *gin.Context, query string) {
517
518 uids := eutils.ProcessQuery("pubmed", query, false, false, false, deStop)
519
520 // use buffer to speed up uid printing
521 var buffer strings.Builder
522
523 for _, uid := range uids {
524 val := strconv.Itoa(int(uid))
525 buffer.WriteString(val[:])
526 buffer.WriteString("\n")
527 }
528
529 txt := buffer.String()
530 if txt != "" {
531 // print buffer
532 c.String(http.StatusOK, txt)
533 }
534 }
535
536 // nquire -get "localhost:8080/search" -query "tn3 transposition immunity [TIAB] AND 1988:1993 [YEAR]"
537 r.GET("/search", func(c *gin.Context) {
538 query := c.Query("query")
539 pubmedSearch(c, query)
540 })
541 // nquire -url "localhost:8080/search" -query "(literacy AND numeracy) NOT (adolescent OR child)"
542 r.POST("/search", func(c *gin.Context) {
543 query := c.PostForm("query")
544 pubmedSearch(c, query)
545 })
546
547 // POPULATE JOURNAL TITLE LOOKUP MAP
548
549 jtaMap := make(map[string]string)
550
551 jpath := filepath.Join(dataBase, "joursets.txt")
552 eutils.TableToMap(jpath, jtaMap)
553
554 // PMID LOOKUP CACHE
555
556 cache := eutils.NewCitCache(500)
557
558 if cache == nil {
559 eutils.DisplayError("Unable to create citation matcher cache")
560 os.Exit(1)
561 }
562
563 // PMID CACHE PRELOAD
564
565 preloadCache := func(c *gin.Context, fileName string) {
566
567 if fileName == "" {
568 return
569 }
570
571 eutils.PreloadCitCache(fileName, cache)
572
573 c.String(http.StatusOK, "")
574 }
575
576 // nquire -get "localhost:8080/preload" -file ...
577 r.GET("/preload", func(c *gin.Context) {
578 fileName := c.Query("file")
579 preloadCache(c, fileName)
580 })
581 // nquire -url "localhost:8080/preload" -file ...
582 r.POST("/preload", func(c *gin.Context) {
583 fileName := c.PostForm("file")
584 preloadCache(c, fileName)
585 })
586
587 // PMID LOOKUP BY CITATION MATCHING
588
589 // common match function
590 citMatch := func(c *gin.Context, params map[string][]string) {
591
592 if params == nil {
593 return
594 }
595
596 buildCitation := func(params map[string][]string) string {
597
598 var arry []string
599
600 arry = append(arry, "<CITATION>")
601
602 addItems := func(names []string, tags []string) {
603 for _, name := range names {
604 vals, ok := params[name]
605 if ok {
606 for n, tag := range tags {
607 if len(vals) > n {
608 // only keep first page
609 if tag == "PAGE" {
610 vals[n], _ = eutils.SplitInTwoLeft(vals[n], "-")
611 }
612 arry = append(arry, "<"+tag+">"+vals[n]+"</"+tag+">")
613 }
614 }
615 }
616 }
617 }
618
619 // allow flexibility in argument names
620 addItems([]string{"author", "auth"}, []string{"FAUT", "LAUT"})
621 addItems([]string{"faut"}, []string{"FAUT"})
622 addItems([]string{"laut"}, []string{"LAUT"})
623 addItems([]string{"title", "titl"}, []string{"TITL"})
624 addItems([]string{"journal", "jour"}, []string{"JOUR"})
625 addItems([]string{"volume", "vol"}, []string{"VOL"})
626 addItems([]string{"issue", "iss"}, []string{"ISS"})
627 addItems([]string{"pages", "page"}, []string{"PAGE"})
628 addItems([]string{"year"}, []string{"YEAR"})
629
630 arry = append(arry, "</CITATION>")
631
632 cit := strings.Join(arry, "")
633
634 return cit
635 }
636
637 cit := ""
638 isCitationXML := false
639
640 // check for -citation "<CITATION> .. </CITATION>" argument
641 ctn, ok := params["citation"]
642 if ok && len(ctn) > 0 {
643 cit = ctn[0]
644 isCitationXML = true
645 } else {
646 // otherwise read individual -author, -title, -journal, -year, -volume, -issue, and -page arguments
647 cit = buildCitation(params)
648 }
649
650 sgr := strings.NewReader(cit)
651 rdr := eutils.CreateXMLStreamer(sgr, nil)
652 xmlq := eutils.CreateXMLProducer("CITATION", "", false, rdr)
653 ctmq := eutils.CreateCitMatchers(xmlq, []string{"strict,remote,verify"}, deStop, doStem, cache, jtaMap)
654 unsq := eutils.CreateXMLUnshuffler(ctmq)
655
656 if sgr == nil || rdr == nil || xmlq == nil || ctmq == nil || unsq == nil {
657 eutils.DisplayError("Unable to create citation matcher")
658 os.Exit(1)
659 }
660
661 // drain output channel
662 for curr := range unsq {
663
664 mtch := curr.Text
665
666 if mtch == "" {
667 continue
668 }
669
670 // extract value in new <PMID> .. </PMID> object
671 _, after, found := strings.Cut(mtch, "<PMID>")
672 if !found {
673 continue
674 }
675 before, _, found := strings.Cut(after, "</PMID>")
676 if !found {
677 continue
678 }
679 if before == "" {
680 continue
681 }
682
683 // send result to output
684 if isCitationXML {
685 c.String(http.StatusOK, mtch+"\n")
686 } else {
687 c.String(http.StatusOK, before+"\n")
688 }
689 }
690 }
691
692 // nquire -get "localhost:8080/match" -author fst -author lst -title ttl -journal jta -year yr
693 r.GET("/match", func(c *gin.Context) {
694 paramPairs := c.Request.URL.Query()
695 citMatch(c, paramPairs)
696 })
697 // nquire -url "localhost:8080/match" -author fst -author lst -title ttl -journal jta -year yr
698 r.POST("/match", func(c *gin.Context) {
699 c.MultipartForm()
700 citMatch(c, c.Request.PostForm)
701 })
702
703 // JOURNAL LOOKUP FROM JOURNAL TO INDEX MAP
704
705 // journal lookup from jtaMap
706 lookupJournal := func(c *gin.Context, query string) {
707
708 query = eutils.NormalizeJournal(query)
709 if query != "" {
710 query = strings.ToLower(query)
711 jta, ok := jtaMap[query]
712 if ok && jta != "" {
713 c.String(http.StatusOK, jta+"\n")
714 }
715 }
716 }
717
718 // nquire -get "localhost:8080/journal" -query "journal of immunology"
719 r.GET("/journal", func(c *gin.Context) {
720 query := c.Query("query")
721 lookupJournal(c, query)
722 })
723 // nquire -url "localhost:8080/journal" -query "pnas"
724 r.POST("/journal", func(c *gin.Context) {
725 query := c.PostForm("query")
726 lookupJournal(c, query)
727 })
728
729 // START LISTENING ON PORT
730
731 // listen for requests
732 r.Run(host + ":" + port)
733 }