Debian Codegraph @

eutils/phrase.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: phrase.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "cmp"
36 "encoding/binary"
37 "fmt"
38 "github.com/surgebase/porter2"
39 "html"
40 "io"
41 "maps"
42 "os"
43 "path/filepath"
44 "regexp"
45 "runtime"
46 "slices"
47 "strconv"
48 "strings"
49 "sync"
50 "unicode"
51 )
52
53 // GetLocalArchiveFolder returns a specific folder path taken from environment variables
54 func GetLocalArchiveFolder(db, dir string, checkExists bool) string {
55
56 db = strings.TrimSpace(db)
57 db = strings.TrimSuffix(db, "/")
58
59 if db == "" {
60 // if empty string, default to pubmed database
61 db = "pubmed"
62 }
63
64 db = strings.ToLower(db)
65
66 // eventually will require explicit database argument
67 if db == "" {
68 DisplayError("Required database argument not supplied")
69 os.Exit(1)
70 }
71
72 dir = strings.TrimSpace(dir)
73 dir = strings.TrimSuffix(dir, "/")
74
75 fldr := dir
76
77 failOnEmpty := func() string {
78 if checkExists {
79 DisplayError("Unable to get folder %s for database %s", fldr, db)
80 os.Exit(1)
81 }
82 return ""
83 }
84
85 if strings.Index(db, " ") >= 0 {
86 DisplayError("Database '%s' must not contain spaces", db)
87 return failOnEmpty()
88 }
89
90 if dir == "" {
91 return failOnEmpty()
92 }
93
94 if strings.Index(dir, " ") >= 0 {
95 DisplayError("Folder '%s' must not contain spaces", dir)
96 return failOnEmpty()
97 }
98
99 getEnvPath := func(env string) string {
100
101 if env == "" {
102 return ""
103 }
104
105 val := os.Getenv(env)
106 if val == "" {
107 return ""
108 }
109
110 val = strings.TrimSuffix(val, "/")
111
112 return val
113 }
114
115 getEnvPaths := func(envs ...string) string {
116
117 // check environment variables in order
118 for _, env := range envs {
119 res := getEnvPath(env)
120 if res != "" {
121 return res
122 }
123 }
124
125 return ""
126 }
127
128 getIniFile := func(cfg string) string {
129
130 if cfg == "" {
131 return ""
132 }
133
134 inFile, err := os.Open(cfg)
135 if err != nil {
136 DisplayError("Unable to open configuration file '%s'", cfg)
137 return ""
138 }
139 defer inFile.Close()
140
141 inis := INIConverter(inFile)
142 if inis == nil {
143 DisplayError("Unable to create INI to XML converter")
144 return ""
145 }
146
147 text := ChanToString(inis)
148
149 text = strings.TrimSpace(text)
150
151 return text
152 }
153
154 var parsedConfig *XMLNode
155
156 config := os.Getenv("EDIRECT_LOCAL_CONFIG")
157 if config != "" {
158 text := getIniFile(config)
159 if text != "" {
160 parsedConfig = ParseRecord(text[:], "ConfigFile")
161 }
162 }
163
164 getConfigPath := func(sub string) string {
165
166 /*
167 [pubmed]
168 ARCHIVE=/Volumes/archive/
169 POSTING=/Volumes/posting/
170 WORKING=/Volumes/working/
171 SOURCES=/Volumes/sources/
172
173 [pmc]
174 ARCHIVE=/Volumes/archive/
175 WORKING=/Volumes/working/
176
177 [taxonomy]
178 ARCHIVE=/Volumes/archive/taxonomy
179 WORKING=/Volumes/working/taxonomy
180 */
181
182 if parsedConfig == nil || db == "" || sub == "" {
183 return ""
184 }
185
186 res := ""
187
188 VisitNodes(parsedConfig, db, func(sect *XMLNode) {
189
190 VisitElements(sect, sub, "", func(str string) { res = str })
191 })
192
193 return res
194 }
195
196 getConfigPaths := func(subs ...string) string {
197
198 // check configuration subfolders in order
199 for _, sub := range subs {
200 res := getConfigPath(sub)
201 if res != "" {
202 return res
203 }
204 }
205
206 return ""
207 }
208
209 path := ""
210
211 // in each case, first try configuration file pointing to by environment variable
212 switch dir {
213
214 case "Archive", "Config", "Data":
215 path = getConfigPaths("ARCHIVE")
216 if path == "" {
217 path = getEnvPaths("EDIRECT_LOCAL_ARCHIVE")
218 }
219
220 case "Sentinels":
221 path = getConfigPaths("ARCHIVE")
222 if path == "" {
223 path = getEnvPaths("EDIRECT_LOCAL_ARCHIVE")
224 }
225 if path != "" {
226 fldr = "Archive/" + dir
227 }
228
229 case "Extras", "Index", "Invert", "Merged", "Scratch":
230 path = getConfigPaths("WORKING", "ARCHIVE")
231 if path == "" {
232 path = getEnvPaths("EDIRECT_LOCAL_WORKING", "EDIRECT_LOCAL_ARCHIVE")
233 }
234
235 case "Current", "Indexed", "Inverted":
236 path = getConfigPaths("WORKING", "ARCHIVE")
237 if path == "" {
238 path = getEnvPaths("EDIRECT_LOCAL_WORKING", "EDIRECT_LOCAL_ARCHIVE")
239 }
240 if path != "" {
241 fldr = "Scratch/" + dir
242 }
243
244 case "Postings":
245 path = getConfigPaths("POSTING", "ARCHIVE")
246 if path == "" {
247 path = getEnvPaths("EDIRECT_LOCAL_POSTING", "EDIRECT_LOCAL_ARCHIVE")
248 }
249
250 case "Source":
251 path = getConfigPaths("SOURCES", "WORKING", "ARCHIVE")
252 if path == "" {
253 path = getEnvPaths("EDIRECT_LOCAL_SOURCES", "EDIRECT_LOCAL_WORKING", "EDIRECT_LOCAL_ARCHIVE")
254 }
255
256 default:
257 DisplayError("Unrecognized folder %s for database %s", fldr, db)
258 // warn if still using deprecated environment variables
259 if getEnvPath("EDIRECT_LOCAL_MASTER") != "" {
260 DisplayWarning("Please change deprecated environment variable EDIRECT_LOCAL_MASTER to EDIRECT_LOCAL_ARCHIVE")
261 }
262 if getEnvPath("EDIRECT_PUBMED_MASTER") != "" {
263 DisplayWarning("Please change deprecated environment variable EDIRECT_PUBMED_MASTER to EDIRECT_LOCAL_ARCHIVE")
264 }
265 if checkExists {
266 os.Exit(1)
267 }
268 }
269
270 if path == "" {
271 return failOnEmpty()
272 }
273
274 rslt := path + "/" + db + "/" + fldr
275
276 if checkExists {
277 _, err := os.Stat(rslt)
278 if err != nil && os.IsNotExist(err) {
279 DisplayError("Local folder %s for database %s is not mounted", fldr, db)
280 os.Exit(1)
281 }
282 }
283
284 return rslt
285 }
286
287 // GetLocalArchivePaths returns Archive and Working paths taken from environment variable(s) (DEPRECATED)
288 func GetLocalArchivePaths(db string) (string, string) {
289
290 DisplayWarning("DEPRECATED: The fetch-*, stream-*, and phrase-search scripts will be removed from EDirect in the near future")
291 DisplayWarning("DEPRECATED: Replace fetch-* or stream-* with xfetch, phrase-search with xinfo, xsearch, xlink, and xfilter")
292
293 // warn if still using deprecated environment variables as well as old function
294 if os.Getenv("EDIRECT_LOCAL_MASTER") != "" {
295 DisplayWarning("Please change deprecated environment variable EDIRECT_LOCAL_MASTER to EDIRECT_LOCAL_ARCHIVE")
296 }
297 if os.Getenv("EDIRECT_PUBMED_MASTER") != "" {
298 DisplayWarning("Please change deprecated environment variable EDIRECT_PUBMED_MASTER to EDIRECT_LOCAL_ARCHIVE")
299 }
300
301 db = strings.TrimSpace(db)
302 db = strings.TrimSuffix(db, "/")
303
304 if db == "" {
305 // if empty string, default to pubmed database
306 db = "pubmed"
307 }
308 db = strings.ToLower(db)
309
310 if strings.Index(db, " ") >= 0 {
311 DisplayError("Database '%s' must not contain spaces", db)
312 return "", ""
313 }
314
315 master, working, ok := "", "", false
316
317 getEnvPaths := func(mstr, wrkg string) (string, string, bool) {
318
319 ms := os.Getenv(mstr)
320 if ms == "" {
321 return "", "", false
322 }
323
324 wk := os.Getenv(wrkg)
325 if wk == "" {
326 wk = ms
327 }
328
329 if !strings.HasSuffix(ms, "/") {
330 ms += "/"
331 }
332 if !strings.HasSuffix(wk, "/") {
333 wk += "/"
334 }
335
336 return ms, wk, true
337 }
338
339 getConfigPaths := func(cnfg string) (string, string, bool) {
340
341 cf := os.Getenv(cnfg)
342 if cf == "" {
343 return "", "", false
344 }
345
346 getIniFile := func(fileName string) string {
347
348 if fileName == "" {
349 return ""
350 }
351
352 inFile, err := os.Open(fileName)
353 if err != nil {
354 DisplayError("Unable to open configuration file '%s'", fileName)
355 return ""
356 }
357 defer inFile.Close()
358
359 inis := INIConverter(inFile)
360 if inis == nil {
361 DisplayError("Unable to create INI to XML converter")
362 return ""
363 }
364
365 text := ChanToString(inis)
366
367 text = strings.TrimSpace(text)
368
369 return text
370 }
371
372 ms, wk := "", ""
373
374 text := getIniFile(cf)
375 if text != "" {
376
377 pat := ParseRecord(text[:], "ConfigFile")
378
379 VisitNodes(pat, db, func(sect *XMLNode) {
380
381 VisitElements(sect, "ARCHIVE", "", func(str string) { ms = str })
382 VisitElements(sect, "WORKING", "", func(str string) { wk = str })
383 })
384 }
385
386 if ms == "" {
387 return "", "", false
388 }
389
390 if wk == "" {
391 wk = ms
392 }
393
394 if !strings.HasSuffix(ms, "/") {
395 ms += "/"
396 }
397 if !strings.HasSuffix(wk, "/") {
398 wk += "/"
399 }
400
401 return ms, wk, true
402 }
403
404 // first try environment variable pointing to configuration file
405 master, working, ok = getConfigPaths("EDIRECT_LOCAL_CONFIG")
406 if ok {
407 return master, working
408 }
409
410 // new convention points to volume, which will have a subfolder for each specific database
411 master, working, ok = getEnvPaths("EDIRECT_LOCAL_ARCHIVE", "EDIRECT_LOCAL_WORKING")
412
413 // try older name of environment variable for primary path
414 if !ok {
415 master, working, ok = getEnvPaths("EDIRECT_LOCAL_MASTER", "EDIRECT_LOCAL_WORKING")
416 }
417
418 if ok {
419 // append database name to volume
420 return master + db + "/", working + db + "/"
421 }
422
423 // old convention has individual database-specific environment variables
424 switch db {
425 case "pubmed":
426 master, working, ok = getEnvPaths("EDIRECT_PUBMED_MASTER", "EDIRECT_PUBMED_WORKING")
427 case "pmc":
428 master, working, ok = getEnvPaths("EDIRECT_PMC_MASTER", "EDIRECT_PMC_WORKING")
429 case "taxonomy":
430 master, working, ok = getEnvPaths("EDIRECT_TAXONOMY_MASTER", "EDIRECT_TAXONOMY_WORKING")
431 }
432
433 if ok {
434 return master, working
435 }
436
437 return "", ""
438 }
439
440 type alias struct {
441 table map[string]string
442 lock sync.Mutex
443 fpath string
444 isLoaded bool
445 }
446
447 // loadAliasTable should be called within a lock on the alias.lock mutex
448 func (a *alias) loadAliasTable(reverse, commas bool) {
449
450 if a == nil || a.fpath == "" {
451 return
452 }
453
454 if a.isLoaded {
455 return
456 }
457
458 file, ferr := os.Open(a.fpath)
459
460 if file != nil && ferr == nil {
461 scanner := bufio.NewScanner(file)
462 for scanner.Scan() {
463 str := scanner.Text()
464 if str == "" {
465 continue
466 }
467 cols := strings.SplitN(str, "\t", 2)
468 if len(cols) != 2 {
469 continue
470 }
471
472 cleanTerm := func(str string) string {
473 str = CleanupQuery(str, false, true)
474 parts := strings.FieldsFunc(str, func(c rune) bool {
475 return (!unicode.IsLetter(c) && !unicode.IsDigit(c) && c != ',') || c > 127
476 })
477 str = strings.Join(parts, " ")
478 if commas {
479 str = strings.Replace(str, ",", " ", -1)
480 }
481 str = strings.ToLower(str)
482 str = strings.TrimSpace(str)
483 str = CompressRunsOfSpaces(str)
484 return str
485 }
486
487 one := cleanTerm(cols[0])
488 two := cleanTerm(cols[1])
489 if reverse {
490 a.table[two] = one
491 } else {
492 a.table[one] = two
493 }
494 }
495 }
496
497 file.Close()
498
499 // set even if loading failed to prevent multiple attempts
500 a.isLoaded = true
501 }
502
503 var journalAliases = map[string]string{
504 "pnas": "proc natl acad sci u s a",
505 "journal of immunology": "journal of immunology baltimore md 1950",
506 "biorxiv": "biorxiv the preprint server for biology",
507 "biorxivorg": "biorxiv the preprint server for biology",
508 }
509
510 var ptypAliases = map[string]string{
511 "clinical trial phase 1": "clinical trial phase i",
512 "clinical trial phase 2": "clinical trial phase ii",
513 "clinical trial phase 3": "clinical trial phase iii",
514 "clinical trial phase 4": "clinical trial phase iv",
515 "clinical trial phase one": "clinical trial phase i",
516 "clinical trial phase two": "clinical trial phase ii",
517 "clinical trial phase three": "clinical trial phase iii",
518 "clinical trial phase four": "clinical trial phase iv",
519 }
520
521 var (
522 meshName alias
523 meshTree alias
524 )
525
526 func printTermCount(base, term, field string) int {
527
528 data, _ := getPostingIDs(base, term, field, true, false)
529 size := len(data)
530 fmt.Fprintf(os.Stdout, "%d\t%s\n", size, term)
531
532 return size
533 }
534
535 func printTermCounts(base, term, field string) int {
536
537 pdlen := len(PostingDir(term))
538
539 if len(term) < pdlen {
540 DisplayError("Term count argument must be at least %d characters", pdlen)
541 os.Exit(1)
542 }
543
544 if strings.Contains(term[:pdlen], "*") {
545 DisplayError("Wildcard asterisk must not be in first %d characters", pdlen)
546 os.Exit(1)
547 }
548
549 dpath, key := PostingPath(base, field, term, false)
550 if dpath == "" {
551 return 0
552 }
553
554 // schedule asynchronous fetching
555 mi := readMasterIndexFuture(dpath, key, field)
556
557 tl := readTermListFuture(dpath, key, field)
558
559 // fetch master index and term list
560 indx := <-mi
561
562 trms := <-tl
563
564 if indx == nil || len(indx) < 1 {
565 return 0
566 }
567
568 if trms == nil || len(trms) < 1 {
569 return 0
570 }
571
572 // master index is padded with phantom term and postings position
573 numTerms := len(indx) - 1
574
575 strs := make([]string, numTerms)
576 if strs == nil || len(strs) < 1 {
577 return 0
578 }
579
580 retlength := int32(len("\n"))
581
582 // populate array of strings from term list
583 for i, j := 0, 1; i < numTerms; i++ {
584 from := indx[i].TermOffset
585 to := indx[j].TermOffset - retlength
586 j++
587 txt := string(trms[from:to])
588 strs[i] = txt
589 }
590
591 // change protecting underscore to space
592 term = strings.Replace(term, "_", " ", -1)
593
594 // flank pattern with start-of-string and end-of-string symbols
595 pat := "^" + term + "$"
596
597 // change asterisk in query to dot + star for regular expression
598 pat = strings.Replace(pat, "*", ".*", -1)
599
600 re, err := regexp.Compile(pat)
601
602 if err != nil {
603 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
604 return 0
605 }
606
607 count := 0
608
609 for R, str := range strs {
610 if re.MatchString(str) {
611 offset := indx[R].PostOffset
612 size := indx[R+1].PostOffset - offset
613 fmt.Fprintf(os.Stdout, "%d\t%s\n", size/4, str)
614 count++
615 }
616 }
617
618 return count
619 }
620
621 func printTermPositions(base, term, field string) int {
622
623 data, ofst := getPostingIDs(base, term, field, false, false)
624 size := len(data)
625 fmt.Fprintf(os.Stdout, "\n%d\t%s\n\n", size, term)
626
627 for i := range len(data) {
628 fmt.Fprintf(os.Stdout, "%12d\t", data[i])
629 pos := ofst[i]
630 sep := ""
631 for j := range len(pos) {
632 fmt.Fprintf(os.Stdout, "%s%d", sep, pos[j])
633 sep = ","
634 }
635 fmt.Fprintf(os.Stdout, "\n")
636 }
637
638 return size
639 }
640
641 func parseField(db, str string) (string, string) {
642
643 field := "TIAB"
644 if db == "pmc" {
645 field = "TEXT"
646 }
647
648 if strings.HasSuffix(str, "]") {
649 pos := strings.Index(str, "[")
650 if pos >= 0 {
651 field = str[pos:]
652 field = strings.TrimPrefix(field, "[")
653 field = strings.TrimSuffix(field, "]")
654 str = str[:pos]
655 str = strings.TrimSpace(str)
656 }
657 switch field {
658 case "NORM":
659 field = "TIAB"
660 case "STEM", "TIAB", "TITL", "ABST", "TEXT", "TERM":
661 case "PIPE":
662 default:
663 str = strings.Replace(str, " ", "_", -1)
664 }
665 }
666
667 return field, str
668 }
669
670 // QUERY EVALUATION FUNCTION
671
672 func evaluateQuery(base, db, phrase string, clauses []string, noStdout, isLink bool) (int, []int32) {
673
674 if clauses == nil || clauses[0] == "" {
675 return 0, nil
676 }
677
678 count := 0
679
680 // flag set if no tildes, indicates no proximity tests in query
681 noProx := true
682 for _, tkn := range clauses {
683 if strings.HasPrefix(tkn, "~") {
684 noProx = false
685 }
686 }
687
688 phrasePositions := func(pn, pm []uint32, dlt uint32) []uint32 {
689
690 var arry []uint32
691
692 ln, lm := len(pn), len(pm)
693
694 if ln < 1 || lm < 1 {
695 return arry
696 }
697
698 q, r := 0, 0
699
700 vn, vm := pn[q], pm[r]
701 vnd := vn + dlt
702
703 for {
704 if vnd > vm {
705 r++
706 if r == lm {
707 break
708 }
709 vm = pm[r]
710 } else if vnd < vm {
711 q++
712 if q == ln {
713 break
714 }
715 vn = pn[q]
716 vnd = vn + dlt
717 } else {
718 // store position of first word in current growing phrase
719 arry = append(arry, vn)
720 q++
721 r++
722 if q == ln || r == lm {
723 break
724 }
725 vn = pn[q]
726 vm = pm[r]
727 vnd = vn + dlt
728 }
729 }
730
731 return arry
732 }
733
734 proximityPositions := func(pn, pm []uint32, dlt uint32) []uint32 {
735
736 var arry []uint32
737
738 ln, lm := len(pn), len(pm)
739
740 if ln < 1 || lm < 1 {
741 return arry
742 }
743
744 q, r := 0, 0
745
746 vn, vm := pn[q], pm[r]
747 vnd := vn + dlt
748
749 for {
750 if vnd < vm {
751 q++
752 if q == ln {
753 break
754 }
755 vn = pn[q]
756 vnd = vn + dlt
757 } else if vn < vm {
758 // store position of first word in downstream phrase that passes proximity test
759 arry = append(arry, vm)
760 q++
761 r++
762 if q == ln || r == lm {
763 break
764 }
765 vn = pn[q]
766 vm = pm[r]
767 vnd = vn + dlt
768 } else {
769 r++
770 if r == lm {
771 break
772 }
773 vm = pm[r]
774 }
775 }
776
777 return arry
778 }
779
780 eval := func(str string) ([]int32, [][]uint32, int) {
781
782 // extract optional [FIELD] qualifier
783 field, str := parseField(db, str)
784
785 if field == "PIPE" {
786 // esearch -db pubmed -query "complement system proteins [MESH]" -pub clinical |
787 // efetch -format uid | phrase-search -query "[PIPE] AND coagulation [TITL]"
788 var data []int32
789 // read UIDs from stdin
790 uidq := CreateUIDReader(os.Stdin)
791 for ext := range uidq {
792
793 val, err := strconv.Atoi(ext.Text)
794 if err != nil {
795 DisplayError("Unrecognized UID %s", ext.Text)
796 os.Exit(1)
797 }
798
799 data = append(data, int32(val))
800 }
801 // sort UIDs before returning
802 slices.Sort(data)
803 return data, nil, 0
804 }
805
806 words := strings.Fields(str)
807
808 if words == nil || len(words) < 1 {
809 return nil, nil, 0
810 }
811
812 // if no tilde proximity tests, and not building up phrase from multiple words,
813 // no need to use more expensive position tests when calculating intersection
814 if noProx && len(words) == 1 {
815 term := words[0]
816 if strings.HasPrefix(term, "+") {
817 return nil, nil, 0
818 }
819 term = strings.Replace(term, "_", " ", -1)
820 data, _ := getPostingIDs(base, term, field, true, isLink)
821 count++
822 return data, nil, 1
823 }
824
825 dist := 0
826
827 var intersect []Arrays
828
829 var futures []<-chan Arrays
830
831 // schedule asynchronous fetching
832 for _, term := range words {
833
834 term = strings.Replace(term, "_", " ", -1)
835
836 if strings.HasPrefix(term, "+") {
837 dist += strings.Count(term, "+")
838 // run of stop words or explicit plus signs skip past one or more words in phrase
839 continue
840 }
841
842 fetch := postingIDsFuture(base, term, field, dist, isLink)
843
844 futures = append(futures, fetch)
845
846 dist++
847 }
848
849 runtime.Gosched()
850
851 for _, chn := range futures {
852
853 // fetch postings data
854 fut := <-chn
855
856 if len(fut.Data) < 1 {
857 // bail if word not present
858 return nil, nil, 0
859 }
860
861 // append posting and positions
862 intersect = append(intersect, fut)
863
864 runtime.Gosched()
865 }
866
867 if len(intersect) < 1 {
868 return nil, nil, 0
869 }
870
871 // start phrase with first word
872 data, ofst, dist := intersect[0].Data, intersect[0].Ofst, intersect[0].Dist+1
873
874 if len(intersect) == 1 {
875 return data, ofst, dist
876 }
877
878 for i := 1; i < len(intersect); i++ {
879
880 // add subsequent words, keep starting positions of phrases that contain all words in proper position
881 data, ofst = extendPositionalIDs(data, ofst, intersect[i].Data, intersect[i].Ofst, intersect[i].Dist, phrasePositions)
882 if len(data) < 1 {
883 // bail if phrase not present
884 return nil, nil, 0
885 }
886 dist = intersect[i].Dist + 1
887 }
888
889 count += len(intersect)
890
891 // return UIDs and all positions of current phrase
892 return data, ofst, dist
893 }
894
895 prevTkn := ""
896
897 nextToken := func() string {
898
899 if len(clauses) < 1 {
900 return ""
901 }
902
903 // remove next token from slice
904 tkn := clauses[0]
905 clauses = clauses[1:]
906
907 if tkn == "(" && prevTkn != "" && prevTkn != "&" && prevTkn != "|" && prevTkn != "!" {
908 DisplayError("Tokens '%s' and '%s' should be separated by AND, OR, or NOT", prevTkn, tkn)
909 os.Exit(1)
910 }
911
912 if prevTkn == ")" && tkn != "" && tkn != "&" && tkn != "|" && tkn != "!" && tkn != ")" {
913 DisplayError("Tokens '%s' and '%s' should be separated by AND, OR, or NOT", prevTkn, tkn)
914 os.Exit(1)
915 }
916
917 prevTkn = tkn
918
919 return tkn
920 }
921
922 // recursive definitions
923 var fact func() ([]int32, [][]uint32, int, string)
924 var prox func() ([]int32, string)
925 var excl func() ([]int32, string)
926 var term func() ([]int32, string)
927 var expr func() ([]int32, string)
928
929 fact = func() ([]int32, [][]uint32, int, string) {
930
931 var (
932 data []int32
933 ofst [][]uint32
934 delta int
935 tkn string
936 )
937
938 tkn = nextToken()
939
940 if tkn == "(" {
941 // recursively process expression in parentheses
942 data, tkn = expr()
943 if tkn == ")" {
944 tkn = nextToken()
945 } else {
946 DisplayError("Expected ')' but received '%s'", tkn)
947 os.Exit(1)
948 }
949 } else if tkn == ")" {
950 DisplayError("Unexpected ')' token")
951 os.Exit(1)
952 } else if tkn == "&" || tkn == "|" || tkn == "!" {
953 DisplayError("Unexpected operator '%s' in expression", tkn)
954 os.Exit(1)
955 } else if tkn == "" {
956 DisplayError("Unexpected end of expression in '%s'", phrase)
957 os.Exit(1)
958 } else {
959 // evaluate current phrase
960 data, ofst, delta = eval(tkn)
961 tkn = nextToken()
962 }
963
964 return data, ofst, delta, tkn
965 }
966
967 prox = func() ([]int32, string) {
968
969 var (
970 next []int32
971 noff [][]uint32
972 ndlt int
973 )
974
975 data, ofst, delta, tkn := fact()
976 if len(data) < 1 {
977 return nil, tkn
978 }
979
980 for strings.HasPrefix(tkn, "~") {
981 dist := strings.Count(tkn, "~")
982 next, noff, ndlt, tkn = fact()
983 if len(next) < 1 {
984 return nil, tkn
985 }
986 // next phrase must be within specified distance after the previous phrase
987 data, ofst = extendPositionalIDs(data, ofst, next, noff, delta+dist, proximityPositions)
988 if len(data) < 1 {
989 return nil, tkn
990 }
991 delta = ndlt
992 }
993
994 return data, tkn
995 }
996
997 excl = func() ([]int32, string) {
998
999 var next []int32
1000
1001 data, tkn := prox()
1002 for tkn == "!" {
1003 next, tkn = prox()
1004 data = excludeIDs(data, next)
1005 }
1006
1007 return data, tkn
1008 }
1009
1010 term = func() ([]int32, string) {
1011
1012 var next []int32
1013
1014 data, tkn := excl()
1015 for tkn == "&" {
1016 next, tkn = excl()
1017 data = intersectIDs(data, next)
1018 }
1019
1020 return data, tkn
1021 }
1022
1023 expr = func() ([]int32, string) {
1024
1025 var next []int32
1026
1027 data, tkn := term()
1028 for tkn == "|" {
1029 next, tkn = term()
1030 data = combineIDs(data, next)
1031 }
1032
1033 return data, tkn
1034 }
1035
1036 // enter recursive descent parser
1037 result, tkn := expr()
1038
1039 if tkn != "" {
1040 DisplayError("Unexpected token '%s' at end of expression", tkn)
1041 os.Exit(1)
1042 }
1043
1044 // sort final result
1045 slices.Sort(result)
1046
1047 if noStdout {
1048 return count, result
1049 }
1050
1051 // use buffers to speed up uid printing
1052 var buffer strings.Builder
1053
1054 wrtr := bufio.NewWriter(os.Stdout)
1055
1056 for _, pmid := range result {
1057 val := strconv.Itoa(int(pmid))
1058 buffer.WriteString(val[:])
1059 buffer.WriteString("\n")
1060 }
1061
1062 txt := buffer.String()
1063 if txt != "" {
1064 // print buffer
1065 wrtr.WriteString(txt[:])
1066 }
1067
1068 wrtr.Flush()
1069
1070 runtime.Gosched()
1071
1072 return count, nil
1073 }
1074
1075 // QUERY PARSING FUNCTIONS
1076
1077 func prepareQuery(str string) string {
1078
1079 if str == "" {
1080 return ""
1081 }
1082
1083 if strings.HasPrefix(str, "[PIPE]") {
1084 str = "stdin " + str
1085 }
1086
1087 // dash before AUTH indicates no truncation, double asterisk survives until setFieldQualifiers
1088 if strings.HasSuffix(str, "- [AUTH]") || strings.HasSuffix(str, "-[AUTH]") {
1089 str = strings.Replace(str, "-", "**", -1)
1090 }
1091 // also support trailing underscore (undocumented)
1092 if strings.HasSuffix(str, "_ [AUTH]") || strings.HasSuffix(str, "_[AUTH]") {
1093 str = strings.Replace(str, "_", "**", -1)
1094 }
1095
1096 removeInternalParentheses := func(str string) string {
1097
1098 if len(str) < 3 {
1099 return str
1100 }
1101
1102 var (
1103 buffer strings.Builder
1104 )
1105
1106 saveOneRune := func(prev, curr, next rune) {
1107
1108 if curr == '(' || curr == ')' {
1109 if prev != ' ' && prev != 0 && next != ' ' && next != 0 {
1110 curr = ' '
1111 }
1112 }
1113
1114 buffer.WriteRune(curr)
1115 }
1116
1117 arry := SlidingSlices(str, 3)
1118
1119 first := true
1120 last := rune(0)
1121 for _, item := range arry {
1122
1123 if len(item) < 3 {
1124 continue
1125 }
1126 prev, curr, next := rune(item[0]), rune(item[1]), rune(item[2])
1127
1128 if first {
1129 saveOneRune(0, prev, 0)
1130 first = false
1131 }
1132
1133 saveOneRune(prev, curr, next)
1134
1135 last = next
1136 }
1137 saveOneRune(0, last, 0)
1138
1139 return buffer.String()
1140 }
1141
1142 isBoolean := false
1143 words := strings.Split(str, " ")
1144 for _, word := range words {
1145 switch word {
1146 case "AND", "OR", "NOT":
1147 isBoolean = true
1148 default:
1149 }
1150 }
1151
1152 if isBoolean {
1153 // more care with parentheses in chemical names if query string also has Boolean operators
1154 str = removeInternalParentheses(str)
1155 } else {
1156 str = strings.Replace(str, "(", " ", -1)
1157 str = strings.Replace(str, ")", " ", -1)
1158 }
1159
1160 str = html.UnescapeString(str)
1161
1162 str = CleanupQuery(str, false, true)
1163
1164 str = strings.Replace(str, "~ ~", "~~", -1)
1165 str = strings.Replace(str, "~ ~", "~~", -1)
1166
1167 str = strings.TrimSpace(str)
1168
1169 // temporarily flank with spaces to detect misplaced operators at ends
1170 str = " " + str + " "
1171
1172 str = strings.Replace(str, " AND ", " & ", -1)
1173 str = strings.Replace(str, " OR ", " | ", -1)
1174 str = strings.Replace(str, " NOT ", " ! ", -1)
1175
1176 str = strings.Replace(str, "(", " ( ", -1)
1177 str = strings.Replace(str, ")", " ) ", -1)
1178 str = strings.Replace(str, "&", " & ", -1)
1179 str = strings.Replace(str, "|", " | ", -1)
1180 str = strings.Replace(str, "!", " ! ", -1)
1181
1182 // ensure that bracketed fields are flanked by spaces
1183 str = strings.Replace(str, "[", " [", -1)
1184 str = strings.Replace(str, "]", "] ", -1)
1185
1186 // remove temporary flanking spaces
1187 str = strings.TrimSpace(str)
1188
1189 str = strings.ToLower(str)
1190
1191 str = strings.Replace(str, "_", " ", -1)
1192
1193 if HasHyphenOrApostrophe(str) {
1194 str = FixSpecialCases(str)
1195 }
1196
1197 str = strings.Replace(str, "-", " ", -1)
1198
1199 str = strings.Replace(str, "'", "", -1)
1200
1201 // allow links like pubmed_cited and pubmed_cites
1202 str = strings.Replace(str, "[pubmed ", "[pubmed_", -1)
1203
1204 // break terms at punctuation, and at non-ASCII characters, allowing brackets for field names,
1205 // along with Boolean control symbols, underscore for protected terms, asterisk to indicate
1206 // truncation wildcard, tilde for maximum proximity, and plus sign for exactly one wildcard word
1207 terms := strings.FieldsFunc(str, func(c rune) bool {
1208 return (!unicode.IsLetter(c) && !unicode.IsDigit(c) &&
1209 c != '_' && c != '*' && c != '~' && c != '+' &&
1210 c != '$' && c != '&' && c != '|' && c != '!' &&
1211 c != '(' && c != ')' && c != '[' && c != ']') || c > 127
1212 })
1213
1214 // rejoin into processed sentence
1215 tmp := strings.Join(terms, " ")
1216
1217 tmp = CompressRunsOfSpaces(tmp)
1218 tmp = strings.TrimSpace(tmp)
1219
1220 return tmp
1221 }
1222
1223 func prepareExact(str, sfx string, deStop bool) string {
1224
1225 if str == "" {
1226 return ""
1227 }
1228
1229 if str == "[Not Available]." || str == "Health." {
1230 return ""
1231 }
1232
1233 str = CleanupQuery(str, true, true)
1234
1235 str = strings.Replace(str, "(", " ", -1)
1236 str = strings.Replace(str, ")", " ", -1)
1237
1238 str = strings.Replace(str, "_", " ", -1)
1239
1240 if HasHyphenOrApostrophe(str) {
1241 str = FixSpecialCases(str)
1242 }
1243
1244 str = strings.Replace(str, "-", " ", -1)
1245
1246 // remove trailing punctuation from each word
1247 var arry []string
1248
1249 terms := strings.Fields(str)
1250 for _, item := range terms {
1251 max := len(item)
1252 for max > 1 {
1253 ch := item[max-1]
1254 if ch != '.' && ch != ',' && ch != ':' && ch != ';' {
1255 break
1256 }
1257 // trim trailing period, comma, colon, and semicolon
1258 item = item[:max-1]
1259 // continue checking for runs of punctuation at end
1260 max--
1261 }
1262 if item == "" {
1263 continue
1264 }
1265 arry = append(arry, item)
1266 }
1267
1268 // rejoin into string
1269 cleaned := strings.Join(arry, " ")
1270
1271 // break clauses at punctuation other than space or underscore, and at non-ASCII characters
1272 clauses := strings.FieldsFunc(cleaned, func(c rune) bool {
1273 return (!unicode.IsLetter(c) && !unicode.IsDigit(c) && c != ' ' && c != '_') || c > 127
1274 })
1275
1276 // space replaces plus sign to separate runs of unpunctuated words
1277 phrases := strings.Join(clauses, " ")
1278
1279 var chain []string
1280
1281 // break phrases into individual words
1282 words := strings.Fields(phrases)
1283
1284 for _, item := range words {
1285
1286 // skip at site of punctuation break
1287 if item == "+" {
1288 chain = append(chain, "+")
1289 continue
1290 }
1291
1292 // skip if just a period, but allow terms that are all digits or period
1293 if item == "." {
1294 chain = append(chain, "+")
1295 continue
1296 }
1297
1298 // optional stop word removal
1299 if deStop && IsStopWord(item) {
1300 chain = append(chain, "+")
1301 continue
1302 }
1303
1304 // index single normalized term
1305 chain = append(chain, item)
1306 }
1307
1308 // rejoin into processed sentence
1309 tmp := strings.Join(chain, " ")
1310
1311 tmp = strings.Replace(tmp, "+ +", "++", -1)
1312 tmp = strings.Replace(tmp, "+ +", "++", -1)
1313
1314 tmp = CompressRunsOfSpaces(tmp)
1315 tmp = strings.TrimSpace(tmp)
1316
1317 if tmp != "" && !strings.HasSuffix(tmp, "]") {
1318 tmp += " " + sfx
1319 }
1320
1321 return tmp
1322 }
1323
1324 func processStopWords(str string, deStop bool) string {
1325
1326 if str == "" {
1327 return ""
1328 }
1329
1330 var chain []string
1331
1332 terms := strings.Fields(str)
1333
1334 nextField := func(terms []string) (string, int) {
1335
1336 for j, item := range terms {
1337 if strings.HasPrefix(item, "[") && strings.HasSuffix(item, "]") {
1338 return strings.ToUpper(item), j + 1
1339 }
1340 }
1341
1342 return "", 0
1343 }
1344
1345 // replace unwanted and stop words with plus sign
1346 for len(terms) > 0 {
1347
1348 item := terms[0]
1349 terms = terms[1:]
1350
1351 fld, j := nextField(terms)
1352
1353 stps := false
1354 rlxd := false
1355 switch fld {
1356 case "[NORM]":
1357 fld = "[TIAB]"
1358 fallthrough
1359 case "[TIAB]", "[TITL]", "[ABST]", "[TEXT]", "[TERM]":
1360 stps = true
1361 case "[STEM]":
1362 stps = true
1363 rlxd = true
1364 case "":
1365 stps = true
1366 default:
1367 }
1368
1369 addOneTerm := func(itm string) {
1370
1371 if stps {
1372 if itm == "." {
1373 // skip if just a period, but allow terms that are all digits or period
1374 chain = append(chain, "+")
1375 } else if deStop && IsStopWord(itm) {
1376 // skip if stop word, breaking phrase chain
1377 chain = append(chain, "+")
1378 } else if rlxd {
1379 isWildCard := strings.HasSuffix(itm, "*")
1380 if isWildCard {
1381 // temporarily remove trailing asterisk
1382 itm = strings.TrimSuffix(itm, "*")
1383 }
1384
1385 itm = porter2.Stem(itm)
1386 itm = strings.TrimSpace(itm)
1387
1388 if isWildCard {
1389 // do wildcard search in stemmed term list
1390 itm += "*"
1391 }
1392 chain = append(chain, itm)
1393 } else {
1394 // record single unmodified term
1395 chain = append(chain, itm)
1396 }
1397 } else {
1398 // do not treat non-TIAB terms as stop words
1399 chain = append(chain, itm)
1400 }
1401 }
1402
1403 if j == 0 {
1404 // index single normalized term
1405 addOneTerm(item)
1406 continue
1407 }
1408
1409 for j > 0 {
1410
1411 addOneTerm(item)
1412
1413 j--
1414 item = terms[0]
1415 terms = terms[1:]
1416 }
1417
1418 if fld != "" {
1419 chain = append(chain, fld)
1420 }
1421 }
1422
1423 // rejoin into processed sentence
1424 tmp := strings.Join(chain, " ")
1425
1426 tmp = strings.Replace(tmp, "+ +", "++", -1)
1427 tmp = strings.Replace(tmp, "+ +", "++", -1)
1428
1429 tmp = strings.Replace(tmp, "~ +", "~+", -1)
1430 tmp = strings.Replace(tmp, "+ ~", "+~", -1)
1431
1432 for strings.Contains(tmp, "~+") {
1433 tmp = strings.Replace(tmp, "~+", "~~", -1)
1434 }
1435 for strings.Contains(tmp, "+~") {
1436 tmp = strings.Replace(tmp, "+~", "~~", -1)
1437 }
1438
1439 tmp = CompressRunsOfSpaces(tmp)
1440 tmp = strings.TrimSpace(tmp)
1441
1442 return tmp
1443 }
1444
1445 func partitionQuery(str string) []string {
1446
1447 if str == "" {
1448 return nil
1449 }
1450
1451 str = CompressRunsOfSpaces(str)
1452 str = strings.TrimSpace(str)
1453
1454 str = " " + str + " "
1455
1456 // flank all operators with caret
1457 str = strings.Replace(str, " ( ", " ^ ( ^ ", -1)
1458 str = strings.Replace(str, " ) ", " ^ ) ^ ", -1)
1459 str = strings.Replace(str, " & ", " ^ & ^ ", -1)
1460 str = strings.Replace(str, " | ", " ^ | ^ ", -1)
1461 str = strings.Replace(str, " ! ", " ^ ! ^ ", -1)
1462 str = strings.Replace(str, " ~", " ^ ~", -1)
1463 str = strings.Replace(str, "~ ", "~ ^ ", -1)
1464
1465 str = CompressRunsOfSpaces(str)
1466 str = strings.TrimSpace(str)
1467
1468 str = strings.Replace(str, "^ ^", "^", -1)
1469
1470 if strings.HasPrefix(str, "^ ") {
1471 str = str[2:]
1472 }
1473 if strings.HasSuffix(str, " ^") {
1474 max := len(str)
1475 str = str[:max-2]
1476 }
1477
1478 str = strings.Replace(str, "~ ^ +", "~+", -1)
1479 str = strings.Replace(str, "+ ^ ~", "+~", -1)
1480
1481 str = strings.Replace(str, "~ +", "~+", -1)
1482 str = strings.Replace(str, "+ ~", "+~", -1)
1483
1484 for strings.Contains(str, "~+") {
1485 str = strings.Replace(str, "~+", "~~", -1)
1486 }
1487 for strings.Contains(str, "+~") {
1488 str = strings.Replace(str, "+~", "~~", -1)
1489 }
1490
1491 // split into non-broken phrase segments or operator symbols
1492 tmp := strings.Split(str, " ^ ")
1493
1494 return tmp
1495 }
1496
1497 func setFieldQualifiers(db string, clauses []string) []string {
1498
1499 var res []string
1500
1501 if clauses == nil {
1502 return nil
1503 }
1504
1505 for _, str := range clauses {
1506
1507 // pass control symbols unchanged
1508 if str == "(" || str == ")" || str == "&" || str == "|" || str == "!" || strings.HasPrefix(str, "~") {
1509 res = append(res, str)
1510 continue
1511 }
1512
1513 // pass angle bracket content delimiters (for -phrase, -require, -exclude)
1514 if str == "<" || str == ">" {
1515 res = append(res, str)
1516 continue
1517 }
1518
1519 if strings.HasSuffix(str, " [YEAR]") {
1520
1521 slen := len(str)
1522 str = str[:slen-7]
1523
1524 // regular 4-digit year
1525 if len(str) == 4 && IsAllDigitsOrPeriod(str) {
1526 res = append(res, str+" [YEAR]")
1527 continue
1528 }
1529
1530 // check for year wildcard
1531 if len(str) == 4 && str[3] == '*' && IsAllDigitsOrPeriod(str[:3]) {
1532
1533 DisplayError("Wildcards not supported - use ####:#### range instead")
1534 os.Exit(1)
1535 }
1536
1537 // allow year month day to look for unexpected annotation
1538 if len(str) > 9 {
1539 res = append(res, str+" [YEAR]")
1540 continue
1541 }
1542
1543 // check for year range
1544 if len(str) == 9 && str[4] == ' ' && IsAllDigitsOrPeriod(str[:4]) && IsAllDigitsOrPeriod(str[5:]) {
1545 start, err := strconv.Atoi(str[:4])
1546 if err != nil {
1547 DisplayError("Unable to recognize first year '%s'", str[:4])
1548 os.Exit(1)
1549 }
1550 stop, err := strconv.Atoi(str[5:])
1551 if err != nil {
1552 DisplayError("Unable to recognize final year '%s'", str[5:])
1553 os.Exit(1)
1554 }
1555 if start > stop {
1556 continue
1557 }
1558 // expand year range into individual year-by-year queries
1559 pfx := "("
1560 sfx := ")"
1561 for start <= stop {
1562 res = append(res, pfx)
1563 pfx = "|"
1564 yr := strconv.Itoa(start)
1565 res = append(res, yr+" [year]")
1566 start++
1567 }
1568 res = append(res, sfx)
1569 continue
1570 }
1571
1572 DisplayError("Unable to recognize year expression '%s'", str)
1573 os.Exit(1)
1574
1575 } else if strings.HasSuffix(str, " [AUTH]") ||
1576 strings.HasSuffix(str, " [FAUT]") ||
1577 strings.HasSuffix(str, " [LAUT]") {
1578
1579 slen := len(str)
1580 fld := str[slen-7:]
1581 str = str[:slen-7]
1582
1583 str = strings.TrimSpace(str)
1584 if str == "" {
1585 continue
1586 }
1587 fld = strings.TrimSpace(fld)
1588
1589 // double asterisk was converted from dash to indicate exact match
1590 if strings.HasSuffix(str, "**") {
1591 str = strings.TrimSuffix(str, "**")
1592 str = strings.TrimSpace(str)
1593 res = append(res, str+" "+fld)
1594 continue
1595 }
1596
1597 // if already has wildcard, leave in place
1598 if strings.Index(str, "*") >= 0 {
1599 res = append(res, str+" "+fld)
1600 continue
1601 }
1602
1603 // if just last name, space plus asterisk to wildcard on any initials
1604 if strings.Index(str, " ") < 0 {
1605 res = append(res, str+" * "+fld)
1606 continue
1607 }
1608
1609 // otherwise, if space between last name and initials, immediate asterisk for all subsequent initials
1610 res = append(res, str+"* "+fld)
1611 continue
1612
1613 } else if strings.HasSuffix(str, " [ANUM]") ||
1614 strings.HasSuffix(str, " [INUM]") ||
1615 strings.HasSuffix(str, " [FNUM]") ||
1616 strings.HasSuffix(str, " [TLEN]") ||
1617 strings.HasSuffix(str, " [TNUM]") {
1618
1619 slen := len(str)
1620 bdy := str[:slen-7]
1621 fld := str[slen-7:]
1622 bdy = strings.TrimSpace(bdy)
1623 fld = strings.TrimSpace(fld)
1624
1625 // look for remnant of colon separating two integers
1626 lft, rgt := SplitInTwoLeft(bdy, " ")
1627 lft = strings.TrimSpace(lft)
1628 rgt = strings.TrimSpace(rgt)
1629
1630 if lft == "" && rgt == "" {
1631 DisplayError("Unable to recognize expression '%s'", str)
1632 os.Exit(1)
1633 }
1634
1635 // regular integer
1636 if rgt == "" {
1637 // check for wildcard
1638 if strings.HasSuffix(lft, "*") {
1639
1640 DisplayError("Wildcards not supported - use #:# range instead")
1641 os.Exit(1)
1642 }
1643 if IsAllDigits(lft) {
1644 res = append(res, str)
1645 continue
1646 }
1647 DisplayError("Field %s must be an integer", fld)
1648 os.Exit(1)
1649 }
1650
1651 // check for integer range
1652 if !IsAllDigits(lft) || !IsAllDigits(rgt) {
1653 DisplayError("Unable to recognize expression '%s'", str)
1654 os.Exit(1)
1655 }
1656
1657 start, err := strconv.Atoi(lft)
1658 if err != nil {
1659 DisplayError("Unable to recognize starting number '%s'", lft)
1660 os.Exit(1)
1661 }
1662 stop, err := strconv.Atoi(rgt)
1663 if err != nil {
1664 DisplayError("Unable to recognize ending number '%s'", rgt)
1665 os.Exit(1)
1666 }
1667 if start > stop {
1668 // put into proper order
1669 start, stop = stop, start
1670 }
1671 // expand range into individual number-by-number queries
1672 fld = strings.ToLower(fld)
1673 pfx := "("
1674 sfx := ")"
1675 for start <= stop {
1676 res = append(res, pfx)
1677 pfx = "|"
1678 yr := strconv.Itoa(start)
1679 res = append(res, yr+" "+fld)
1680 start++
1681 }
1682 res = append(res, sfx)
1683 continue
1684
1685 } else if strings.HasSuffix(str, " [TREE]") {
1686
1687 slen := len(str)
1688 str = str[:slen-7]
1689
1690 if db == "pubmed" {
1691
1692 // pad if top-level mesh tree wildcard uses four character trie
1693 if len(str) == 4 && str[3] == '*' {
1694 key := str[:2]
1695 num, ok := TrieLen[key]
1696 if ok && num > 3 {
1697 str = str[0:3] + " " + "*"
1698 }
1699 }
1700
1701 str = strings.Replace(str, " ", ".", -1)
1702 tmp := str
1703 tmp = strings.TrimSuffix(tmp, "*")
1704 if len(tmp) > 2 && unicode.IsLower(rune(tmp[0])) && IsAllDigitsOrPeriod(tmp[1:]) {
1705 str = strings.Replace(str, ".", " ", -1)
1706 res = append(res, str+" [TREE]")
1707 continue
1708 }
1709
1710 DisplayError("Unable to recognize mesh code expression '%s'", str)
1711 os.Exit(1)
1712
1713 } else if db == "taxonomy" {
1714
1715 // e.g., "Eukaryota Metazoa Chordata Mammalia Primates * [TREE]"
1716
1717 res = append(res, str+" [TREE]")
1718 continue
1719 }
1720
1721 } else if strings.HasSuffix(str, " [JOUR]") {
1722
1723 slen := len(str)
1724 str = str[:slen-7]
1725
1726 // check hard-coded journal alias map (would be better to use map from Data/jourindx.txt)
1727 alias, ok := journalAliases[str]
1728 if ok {
1729 res = append(res, alias+" [JOUR]")
1730 continue
1731 }
1732
1733 // no alias found, use as is
1734 res = append(res, str+" [JOUR]")
1735 continue
1736
1737 } else if strings.HasSuffix(str, " [PTYP]") {
1738
1739 slen := len(str)
1740 str = str[:slen-7]
1741
1742 // convert clinical trial phase with arabic numeral or english word to roman numeral
1743 alias, ok := ptypAliases[str]
1744 if ok {
1745 res = append(res, alias+" [PTYP]")
1746 continue
1747 }
1748
1749 // no alias found, use as is
1750 res = append(res, str+" [PTYP]")
1751 continue
1752
1753 } else if strings.HasSuffix(str, " [DOI]") {
1754
1755 slen := len(str)
1756 str = str[:slen-6]
1757
1758 rev := ReverseString(str)
1759 res = append(res, rev+" [DOI]")
1760 continue
1761
1762 } else if strings.HasSuffix(str, " [MESH]") {
1763
1764 slen := len(str)
1765 str = str[:slen-7]
1766
1767 if meshName.fpath == "" || meshTree.fpath == "" {
1768 dataBase := GetLocalArchiveFolder("pubmed", "Data", false)
1769 if dataBase != "" {
1770 if meshName.fpath == "" {
1771 meshName.fpath = filepath.Join(dataBase, "meshname.txt")
1772 }
1773 if meshTree.fpath == "" {
1774 meshTree.fpath = filepath.Join(dataBase, "meshtree.txt")
1775 }
1776 }
1777 }
1778
1779 // load mesh tables within mutexes
1780 meshName.lock.Lock()
1781 if !meshName.isLoaded {
1782 meshName.loadAliasTable(true, true)
1783 }
1784 meshName.lock.Unlock()
1785
1786 meshTree.lock.Lock()
1787 if !meshTree.isLoaded {
1788 meshTree.loadAliasTable(false, false)
1789 }
1790 meshTree.lock.Unlock()
1791
1792 // check mesh alias tables
1793 if meshName.isLoaded && meshTree.isLoaded {
1794 code, ok := meshName.table[str]
1795 if ok {
1796 cluster, ok := meshTree.table[code]
1797 if ok {
1798 if strings.Index(cluster, ",") < 0 {
1799 res = append(res, cluster+"* [TREE]")
1800 continue
1801 }
1802 trees := strings.Split(cluster, ",")
1803 // expand multiple trees in OR group
1804 pfx := "("
1805 sfx := ")"
1806 for _, tr := range trees {
1807 res = append(res, pfx)
1808 pfx = "|"
1809 tr = strings.TrimSpace(tr)
1810 res = append(res, tr+"* [TREE]")
1811 }
1812 res = append(res, sfx)
1813 continue
1814 } else {
1815 res = append(res, code+" [CODE]")
1816 continue
1817 }
1818 }
1819 }
1820
1821 // skip if MeSH term not yet indexed in tree
1822 continue
1823 }
1824
1825 // remove leading and trailing plus signs and spaces
1826 for strings.HasPrefix(str, "+") || strings.HasPrefix(str, " ") {
1827 str = str[1:]
1828 }
1829 for strings.HasSuffix(str, "+") || strings.HasSuffix(str, " ") {
1830 slen := len(str)
1831 str = str[:slen-1]
1832 }
1833
1834 res = append(res, str)
1835 }
1836
1837 return res
1838 }
1839
1840 // SEARCH TERM LISTS FOR PHRASES OR NORMALIZED TERMS, OR MATCH BY PATTERN
1841
1842 // ProcessSearch evaluates query, returns list of PMIDs to stdout
1843 func ProcessSearch(db, phrase string, xact, titl, isLink, deStop bool) int {
1844
1845 if phrase == "" {
1846 return 0
1847 }
1848
1849 if db == "" {
1850 db = "pubmed"
1851 }
1852 db = strings.ToLower(db)
1853
1854 // obtain path from environment variable
1855 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
1856
1857 if titl {
1858 phrase = prepareExact(phrase, "[titl]", deStop)
1859 } else if xact {
1860 if db == "pmc" {
1861 phrase = prepareExact(phrase, "[text]", deStop)
1862 } else {
1863 phrase = prepareExact(phrase, "[tiab]", deStop)
1864 }
1865 } else {
1866 phrase = prepareQuery(phrase)
1867 }
1868
1869 phrase = processStopWords(phrase, deStop)
1870
1871 clauses := partitionQuery(phrase)
1872
1873 clauses = setFieldQualifiers(db, clauses)
1874
1875 count, _ := evaluateQuery(postingsBase, db, phrase, clauses, false, isLink)
1876
1877 return count
1878 }
1879
1880 // ProcessQuery evaluates query, returns list of PMIDs in array
1881 func ProcessQuery(db, phrase string, xact, titl, isLink, deStop bool) []int32 {
1882
1883 if phrase == "" {
1884 return nil
1885 }
1886
1887 if db == "" {
1888 db = "pubmed"
1889 }
1890 db = strings.ToLower(db)
1891
1892 // obtain path from environment variable
1893 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
1894
1895 if titl {
1896 phrase = prepareExact(phrase, "[titl]", deStop)
1897 } else if xact {
1898 if db == "pmc" {
1899 phrase = prepareExact(phrase, "[text]", deStop)
1900 } else {
1901 phrase = prepareExact(phrase, "[tiab]", deStop)
1902 }
1903 } else {
1904 phrase = prepareQuery(phrase)
1905 }
1906
1907 phrase = processStopWords(phrase, deStop)
1908
1909 clauses := partitionQuery(phrase)
1910
1911 clauses = setFieldQualifiers(db, clauses)
1912
1913 _, arry := evaluateQuery(postingsBase, db, phrase, clauses, true, isLink)
1914
1915 return arry
1916 }
1917
1918 // ProcessMock shows individual steps in processing query for evaluation
1919 func ProcessMock(db, phrase string, xact, titl, deStop bool) int {
1920
1921 if phrase == "" {
1922 return 0
1923 }
1924
1925 if db == "" {
1926 db = "pubmed"
1927 }
1928 db = strings.ToLower(db)
1929
1930 fmt.Fprintf(os.Stdout, "processSearch:\n\n%s\n\n", phrase)
1931
1932 if titl {
1933 phrase = prepareExact(phrase, "[titl]", deStop)
1934
1935 fmt.Fprintf(os.Stdout, "prepareExact:\n\n%s\n\n", phrase)
1936 } else if xact {
1937 if db == "pmc" {
1938 phrase = prepareExact(phrase, "[text]", deStop)
1939 } else {
1940 phrase = prepareExact(phrase, "[tiab]", deStop)
1941 }
1942
1943 fmt.Fprintf(os.Stdout, "prepareExact:\n\n%s\n\n", phrase)
1944 } else {
1945 phrase = prepareQuery(phrase)
1946
1947 fmt.Fprintf(os.Stdout, "prepareQuery:\n\n%s\n\n", phrase)
1948 }
1949
1950 phrase = processStopWords(phrase, deStop)
1951
1952 fmt.Fprintf(os.Stdout, "processStopWords:\n\n%s\n\n", phrase)
1953
1954 clauses := partitionQuery(phrase)
1955
1956 fmt.Fprintf(os.Stdout, "partitionQuery:\n\n")
1957 for _, tkn := range clauses {
1958 fmt.Fprintf(os.Stdout, "%s\n", tkn)
1959 }
1960 fmt.Fprintf(os.Stdout, "\n")
1961
1962 clauses = setFieldQualifiers(db, clauses)
1963
1964 fmt.Fprintf(os.Stdout, "setFieldQualifiers:\n\n")
1965 for _, tkn := range clauses {
1966 fmt.Fprintf(os.Stdout, "%s\n", tkn)
1967 }
1968 fmt.Fprintf(os.Stdout, "\n")
1969
1970 return 0
1971 }
1972
1973 // ProcessCount prints document count for each term, also supports terminal wildcards
1974 func ProcessCount(db, phrase string, plrl, psns, deStop bool) int {
1975
1976 if phrase == "" {
1977 return 0
1978 }
1979
1980 if db == "" {
1981 db = "pubmed"
1982 }
1983 db = strings.ToLower(db)
1984
1985 // obtain path from environment variable
1986 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
1987
1988 phrase = prepareQuery(phrase)
1989
1990 phrase = processStopWords(phrase, deStop)
1991
1992 clauses := partitionQuery(phrase)
1993
1994 clauses = setFieldQualifiers(db, clauses)
1995
1996 if clauses == nil {
1997 return 0
1998 }
1999
2000 count := 0
2001
2002 splitIntoWords := func(str string) []string {
2003
2004 if str == "" {
2005 return nil
2006 }
2007
2008 var arry []string
2009
2010 parts := strings.Split(str, "+")
2011
2012 for _, segment := range parts {
2013
2014 segment = strings.TrimSpace(segment)
2015
2016 if segment == "" {
2017 continue
2018 }
2019
2020 words := strings.Fields(segment)
2021
2022 for _, item := range words {
2023 if strings.HasPrefix(item, "~") {
2024 continue
2025 }
2026 arry = append(arry, item)
2027 }
2028 }
2029
2030 return arry
2031 }
2032
2033 checkTermCounts := func(txt string) {
2034
2035 field, str := parseField(db, txt)
2036
2037 var words []string
2038
2039 words = splitIntoWords(str)
2040
2041 if words == nil || len(words) < 1 {
2042 return
2043 }
2044
2045 for _, term := range words {
2046
2047 term = strings.Replace(term, "_", " ", -1)
2048
2049 if psns {
2050 count += printTermPositions(postingsBase, term, field)
2051 } else if plrl {
2052 count += printTermCounts(postingsBase, term, field)
2053 } else {
2054 count += printTermCount(postingsBase, term, field)
2055 }
2056 }
2057 }
2058
2059 for _, item := range clauses {
2060
2061 // skip control symbols
2062 if item == "(" || item == ")" || item == "&" || item == "|" || item == "!" {
2063 continue
2064 }
2065
2066 checkTermCounts(item)
2067 }
2068
2069 runtime.Gosched()
2070
2071 return count
2072 }
2073
2074 // TermCounts prints document counts for terms by subdirectory
2075 func TermCounts(db, field, key, ttls string) int {
2076
2077 if field == "" || key == "" || ttls == "" {
2078 return 0
2079 }
2080
2081 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
2082
2083 dpath := filepath.Join(postingsBase, field, ttls)
2084
2085 // schedule asynchronous fetching
2086 mi := readMasterIndexFuture(dpath, key, field)
2087
2088 tl := readTermListFuture(dpath, key, field)
2089
2090 // fetch master index and term list
2091 indx := <-mi
2092
2093 trms := <-tl
2094
2095 if indx == nil || len(indx) < 1 {
2096 return 0
2097 }
2098
2099 if trms == nil || len(trms) < 1 {
2100 return 0
2101 }
2102
2103 // master index is padded with phantom term and postings position
2104 numTerms := len(indx) - 1
2105
2106 strs := make([]string, numTerms)
2107 if strs == nil || len(strs) < 1 {
2108 return 0
2109 }
2110
2111 retlength := int32(len("\n"))
2112
2113 // populate array of strings from term list
2114 for i, j := 0, 1; i < numTerms; i++ {
2115 from := indx[i].TermOffset
2116 to := indx[j].TermOffset - retlength
2117 j++
2118 txt := string(trms[from:to])
2119 strs[i] = txt
2120 }
2121
2122 count := 0
2123
2124 for R, str := range strs {
2125 offset := indx[R].PostOffset
2126 size := indx[R+1].PostOffset - offset
2127 fmt.Fprintf(os.Stdout, "%d\t%s\n", size/4, str)
2128 count++
2129 }
2130
2131 return count
2132 }
2133
2134 // ProcessLinks reads a list of PMIDs, merges resulting links
2135 func ProcessLinks(db, fld string) {
2136
2137 if fld == "" {
2138 return
2139 }
2140
2141 // obtain path from environment variable
2142 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
2143
2144 // createLinkGrouper reads from UID reader and groups PMIDs under the same LinksTrie
2145 createLinkGrouper := func(base, fld string, inp <-chan XMLRecord) <-chan []string {
2146
2147 if base == "" || fld == "" || inp == nil {
2148 return nil
2149 }
2150
2151 out := make(chan []string, chanDepth)
2152 if out == nil {
2153 DisplayError("Unable to create link grouper channel")
2154 os.Exit(1)
2155 }
2156
2157 linkGrouper := func(base, fld string, inp <-chan XMLRecord, out chan<- []string) {
2158
2159 // report when grouper has no more records to process
2160 defer close(out)
2161
2162 var arry []string
2163
2164 currPfx := ""
2165
2166 for ext := range inp {
2167
2168 uid := ext.Text
2169 _, pfx := LinksTrie(uid, true)
2170
2171 if pfx != currPfx && currPfx != "" {
2172
2173 if arry != nil {
2174 // send group of PMIDs with the same line trie down the channel
2175 out <- arry
2176 }
2177
2178 // empty the slice
2179 arry = nil
2180 }
2181
2182 arry = append(arry, uid)
2183
2184 currPfx = pfx
2185 }
2186
2187 // send final results
2188 if arry != nil {
2189 // send group of PMIDs with the same line trie down the channel
2190 out <- arry
2191 }
2192 }
2193
2194 // launch single link grouper goroutine
2195 go linkGrouper(base, fld, inp, out)
2196
2197 return out
2198 }
2199
2200 // mutex for link results
2201 var llock sync.RWMutex
2202
2203 // map for combining link results
2204 combinedLinks := make(map[int]bool)
2205
2206 createLinkMergers := func(prom, field string, inp <-chan []string) <-chan string {
2207
2208 if prom == "" || field == "" || inp == nil {
2209 return nil
2210 }
2211
2212 out := make(chan string, chanDepth)
2213 if out == nil {
2214 DisplayError("Unable to create link merger channel")
2215 os.Exit(1)
2216 }
2217
2218 // linkMerge processes a set of terms from the same master index area
2219 linkMerge := func(wg *sync.WaitGroup, prom, field string, inp <-chan []string, out chan<- string) {
2220
2221 // report when this matcher has no more records to process
2222 defer wg.Done()
2223
2224 if inp == nil || out == nil {
2225 return
2226 }
2227
2228 for terms := range inp {
2229
2230 key := terms[0]
2231
2232 dir, ky := LinksTrie(key, true)
2233 if dir == "" {
2234 continue
2235 }
2236 dpath := filepath.Join(prom, field, dir)
2237 if dpath == "" {
2238 continue
2239 }
2240
2241 // schedule asynchronous fetching
2242 mi := readMasterIndexFuture(dpath, ky, field)
2243
2244 tl := readTermListFuture(dpath, ky, field)
2245
2246 // fetch master index and term list
2247 indx := <-mi
2248
2249 trms := <-tl
2250
2251 if indx == nil || len(indx) < 1 {
2252 continue
2253 }
2254
2255 if trms == nil || len(trms) < 1 {
2256 continue
2257 }
2258
2259 // master index is padded with phantom term and postings position
2260 numTerms := len(indx) - 1
2261
2262 strs := make([]string, numTerms)
2263 if strs == nil || len(strs) < 1 {
2264 continue
2265 }
2266
2267 retlength := int32(len("\n"))
2268
2269 // populate array of strings from term list
2270 for i, j := 0, 1; i < numTerms; i++ {
2271 from := indx[i].TermOffset
2272 to := indx[j].TermOffset - retlength
2273 j++
2274 txt := string(trms[from:to])
2275 strs[i] = txt
2276 }
2277
2278 postingsLoop := func(dpath, ky, field string) {
2279
2280 inFile, _ := commonOpenFile(dpath, ky+"."+field+".pst")
2281 if inFile == nil {
2282 return
2283 }
2284
2285 defer inFile.Close()
2286
2287 for _, term := range terms {
2288
2289 term = PadNumericID(term)
2290
2291 // binary search in term list
2292 L, R := 0, numTerms-1
2293 for L < R {
2294 mid := (L + R) / 2
2295 if strs[mid] < term {
2296 L = mid + 1
2297 } else {
2298 R = mid
2299 }
2300 }
2301
2302 linkLoop := func(offset, size int32) {
2303
2304 data := make([]int32, size/4)
2305 if data == nil || len(data) < 1 {
2306 return
2307 }
2308
2309 _, err := inFile.Seek(int64(offset), io.SeekStart)
2310 if err != nil {
2311 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2312 return
2313 }
2314
2315 // read relevant postings list section
2316 err = binary.Read(inFile, binary.LittleEndian, data)
2317 if err != nil {
2318 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2319 return
2320 }
2321
2322 if data == nil || len(data) < 1 {
2323 return
2324 }
2325
2326 llock.Lock()
2327
2328 for _, uid := range data {
2329 combinedLinks[int(uid)] = true
2330 }
2331
2332 llock.Unlock()
2333 }
2334
2335 // regular search requires exact match from binary search
2336 if R < numTerms && strs[R] == term {
2337
2338 offset := indx[R].PostOffset
2339 size := indx[R+1].PostOffset - offset
2340
2341 linkLoop(offset, size)
2342 }
2343 }
2344 }
2345
2346 postingsLoop(dpath, ky, field)
2347
2348 out <- ky
2349 }
2350 }
2351
2352 var wg sync.WaitGroup
2353
2354 // launch multiple link merger goroutines
2355 for range numServe {
2356 wg.Add(1)
2357 go linkMerge(&wg, prom, field, inp, out)
2358 }
2359
2360 // launch separate anonymous goroutine to wait until all mergers are done
2361 go func() {
2362 wg.Wait()
2363 close(out)
2364 }()
2365
2366 return out
2367 }
2368
2369 // read text PMIDs from stdin
2370 uidq := CreateUIDReader(os.Stdin)
2371
2372 grpq := createLinkGrouper(postingsBase, fld, uidq)
2373
2374 lnkq := createLinkMergers(postingsBase, fld, grpq)
2375
2376 // drain channel
2377 for range lnkq {
2378 }
2379
2380 // sort id keys in alphabetical order
2381 keys := slices.Sorted(maps.Keys(combinedLinks))
2382
2383 // use buffers to speed up PMID printing
2384 var buffer strings.Builder
2385
2386 wrtr := bufio.NewWriter(os.Stdout)
2387
2388 for _, uid := range keys {
2389 pmid := strconv.Itoa(uid)
2390 buffer.WriteString(pmid)
2391 buffer.WriteString("\n")
2392 }
2393
2394 txt := buffer.String()
2395 if txt != "" {
2396 // print buffer
2397 wrtr.WriteString(txt[:])
2398 }
2399
2400 wrtr.Flush()
2401
2402 runtime.Gosched()
2403 }
2404
2405 // ProcessMatch evaluates query, returns lines with term match count and UID
2406 func ProcessMatch(db, phrase string, deStop bool) {
2407
2408 if phrase == "" {
2409 return
2410 }
2411
2412 if db == "" {
2413 db = "pubmed"
2414 }
2415 db = strings.ToLower(db)
2416
2417 phrase = prepareQuery(phrase)
2418
2419 phrase = processStopWords(phrase, deStop)
2420
2421 clauses := partitionQuery(phrase)
2422
2423 clauses = setFieldQualifiers(db, clauses)
2424
2425 wordPairs := func(titl string) []string {
2426
2427 var arry []string
2428
2429 titl = strings.ToLower(titl)
2430
2431 // break phrases into individual words
2432 words := strings.FieldsFunc(titl, func(c rune) bool {
2433 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
2434 })
2435
2436 // word pairs (or isolated singletons) separated by stop words
2437 if len(words) > 0 {
2438 past := ""
2439 run := 0
2440 for _, item := range words {
2441 if IsStopWord(item) {
2442 if run == 1 && past != "" {
2443 arry = append(arry, past)
2444 }
2445 past = ""
2446 run = 0
2447 continue
2448 }
2449 if item == "" {
2450 past = ""
2451 continue
2452 }
2453 if past != "" {
2454 arry = append(arry, past+" "+item)
2455 }
2456 past = item
2457 run++
2458 }
2459 if run == 1 && past != "" {
2460 arry = append(arry, past)
2461 }
2462 }
2463
2464 return arry
2465 }
2466
2467 singleWords := func(titl string) []string {
2468
2469 var arry []string
2470
2471 titl = strings.ToLower(titl)
2472
2473 // break phrases into individual words
2474 words := strings.FieldsFunc(titl, func(c rune) bool {
2475 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
2476 })
2477
2478 for _, item := range words {
2479 if item == "" {
2480 continue
2481 }
2482 if IsStopWord(item) {
2483 continue
2484 }
2485 arry = append(arry, item)
2486 }
2487
2488 return arry
2489 }
2490
2491 nextToken := func() string {
2492
2493 if len(clauses) < 1 {
2494 return ""
2495 }
2496
2497 // remove next token from slice
2498 tkn := clauses[0]
2499 clauses = clauses[1:]
2500
2501 return tkn
2502 }
2503
2504 // only do single search for each unique query term
2505 uniqued := make(map[string]bool)
2506
2507 for {
2508 tkn := nextToken()
2509 if tkn == "" {
2510 break
2511 }
2512 if tkn == "&" || tkn == "|" || tkn == "^" {
2513 continue
2514 }
2515
2516 var terms []string
2517 field := ""
2518
2519 pos := strings.Index(tkn, "[")
2520 if pos >= 0 {
2521 field = tkn[pos:]
2522 tkn = tkn[:pos]
2523 field = strings.TrimSpace(field)
2524 tkn = strings.TrimSpace(tkn)
2525 }
2526 if field == "[PAIR]" {
2527 terms = wordPairs(tkn)
2528 } else {
2529 terms = singleWords(tkn)
2530 }
2531
2532 if len(terms) < 1 {
2533 break
2534 }
2535
2536 for _, item := range terms {
2537 uniqued[item+" "+field] = true
2538 }
2539 }
2540
2541 // histogram of counts for UIDs matching one or more terms
2542 counts := make(map[int32]int)
2543
2544 uniques := slices.Sorted(maps.Keys(uniqued))
2545
2546 for _, term := range uniques {
2547 arry := ProcessQuery(db, term, false, false, false, deStop)
2548 for _, uid := range arry {
2549 val := counts[uid]
2550 val++
2551 counts[uid] = val
2552 }
2553 }
2554
2555 // data reorganized by number of matches
2556 matches := make(map[int][]int32)
2557
2558 for id, ct := range counts {
2559 mtch := matches[ct]
2560 if mtch == nil {
2561 mtch = make([]int32, 0, 1)
2562 }
2563 mtch = append(mtch, id)
2564 matches[ct] = mtch
2565 }
2566
2567 // sort highest count to lowest count
2568 keys := slices.SortedFunc(maps.Keys(matches),
2569 func(i, j int) int {
2570 // sends arguments in reverse order
2571 return cmp.Compare(j, i)
2572 })
2573
2574 var buffer strings.Builder
2575
2576 wrtr := bufio.NewWriter(os.Stdout)
2577
2578 has := 0
2579
2580 for _, key := range keys {
2581
2582 if key == 1 && has > 0 {
2583 break
2584 }
2585 cts := matches[key]
2586 kys := strconv.Itoa(key)
2587
2588 // within the same count, sort lowest UID to highest UID
2589 slices.Sort(cts)
2590
2591 for _, uid := range cts {
2592 uids := strconv.Itoa(int(uid))
2593 buffer.WriteString(kys + "\t" + uids + "\n")
2594 }
2595
2596 has++
2597 // do not break if has > 2, now allows any count > 1,
2598 // use just-top-hits {n} to filter for top n counts
2599 }
2600
2601 txt := buffer.String()
2602 if txt != "" {
2603 // print buffer
2604 wrtr.WriteString(txt[:])
2605 }
2606
2607 wrtr.Flush()
2608
2609 runtime.Gosched()
2610 }
2611
2612 func streamTermsOrTotals(db, fld string, justTerms bool) <-chan string {
2613
2614 if db == "" {
2615 db = "pubmed"
2616 }
2617 if fld == "" {
2618 DisplayError("Field missing for visiting terms")
2619 os.Exit(1)
2620 }
2621
2622 // obtain paths from environment variable(s)
2623 postingsBase := GetLocalArchiveFolder(db, "Postings", true)
2624
2625 // check to make sure local postings are mounted
2626 _, err := os.Stat(postingsBase)
2627 if err != nil && os.IsNotExist(err) {
2628 DisplayError("Local postings files are not mounted")
2629 os.Exit(1)
2630 }
2631
2632 findTopDirs := func(db, fld string) <-chan string {
2633
2634 out := make(chan string, chanDepth)
2635 if out == nil {
2636 DisplayError("Unable to create term path channel")
2637 os.Exit(1)
2638 }
2639
2640 findTopDirs := func(base, fld string, out chan<- string) {
2641
2642 defer close(out)
2643
2644 fieldBase := filepath.Join(base, fld)
2645
2646 topDirs, err := os.ReadDir(fieldBase)
2647 if err != nil {
2648 return
2649 }
2650
2651 for _, item := range topDirs {
2652 name := item.Name()
2653 if name != "" && item.IsDir() {
2654 sub := filepath.Join(fieldBase, name)
2655 out <- sub
2656 }
2657 }
2658 }
2659
2660 go findTopDirs(postingsBase, fld, out)
2661
2662 return out
2663 }
2664
2665 findSubDirs := func(inp <-chan string) <-chan []string {
2666
2667 if inp == nil {
2668 return nil
2669 }
2670
2671 out := make(chan []string, chanDepth)
2672 if out == nil {
2673 DisplayError("Unable to create term exploration channel")
2674 os.Exit(1)
2675 }
2676
2677 getSubDirs := func(inp <-chan string, out chan<- []string) {
2678
2679 defer close(out)
2680
2681 visitOneTop := func(top string) {
2682
2683 var paths []string
2684
2685 // recursive definition
2686 var visitSubFolders func(path string)
2687
2688 // visitSubFolders recurses to leaf directories
2689 visitSubFolders = func(path string) {
2690
2691 contents, err := os.ReadDir(path)
2692 if err != nil {
2693 return
2694 }
2695
2696 for _, item := range contents {
2697 name := item.Name()
2698 if name == "" {
2699 continue
2700 }
2701 if item.IsDir() {
2702 continue
2703 }
2704 if strings.HasSuffix(name, ".trm") {
2705 name = strings.TrimSuffix(name, ".trm")
2706 tl := filepath.Join(path, name)
2707 paths = append(paths, tl)
2708 }
2709 }
2710 for _, item := range contents {
2711 name := item.Name()
2712 if name == "" {
2713 continue
2714 }
2715 if item.IsDir() {
2716 sub := filepath.Join(path, name)
2717 visitSubFolders(sub)
2718 }
2719 }
2720 }
2721
2722 visitSubFolders(top)
2723
2724 out <- paths
2725 }
2726
2727 for top := range inp {
2728 visitOneTop(top)
2729 }
2730 }
2731
2732 go getSubDirs(inp, out)
2733
2734 return out
2735 }
2736
2737 readBinaryFileToMaster := func(fileName string) []Master {
2738
2739 f, err := os.Open(fileName)
2740 if err != nil {
2741 DisplayError("Unable to open input file '%s'", fileName)
2742 return nil
2743 }
2744
2745 defer f.Close()
2746
2747 fi, err := f.Stat()
2748 if err != nil {
2749 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2750 return nil
2751 }
2752
2753 size := fi.Size()
2754
2755 data := make([]Master, size/8)
2756 if data == nil || len(data) < 1 {
2757 return nil
2758 }
2759
2760 err = binary.Read(f, binary.LittleEndian, &data)
2761 if err != nil {
2762 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
2763 return nil
2764 }
2765
2766 return data
2767 }
2768
2769 fetchTermSet := func(inp <-chan []string) <-chan []string {
2770
2771 if inp == nil {
2772 return nil
2773 }
2774
2775 out := make(chan []string, chanDepth)
2776 if out == nil {
2777 DisplayError("Unable to create term set channel")
2778 os.Exit(1)
2779 }
2780
2781 fetchTerms := func(inp <-chan string) <-chan string {
2782
2783 out := make(chan string, chanDepth)
2784 if out == nil {
2785 DisplayError("Unable to create term fetch channel")
2786 os.Exit(1)
2787 }
2788
2789 termFetcher := func(wg *sync.WaitGroup, inp <-chan string, out chan<- string) {
2790
2791 // report when more records to process
2792 defer wg.Done()
2793
2794 getTermCounts := func(pth string) {
2795
2796 trms := ReadTextFileToString(pth + ".trm")
2797 if trms == "" || len(trms) < 1 {
2798 return
2799 }
2800
2801 if justTerms {
2802 out <- trms
2803 return
2804 }
2805
2806 indx := readBinaryFileToMaster(pth + ".mst")
2807 if indx == nil || len(indx) < 1 {
2808 return
2809 }
2810
2811 // master index is padded with phantom term and postings position
2812 numTerms := len(indx) - 1
2813
2814 strs := make([]string, numTerms)
2815 if strs == nil || len(strs) < 1 {
2816 return
2817 }
2818
2819 retlength := int32(len("\n"))
2820
2821 // populate array of strings from term list
2822 for i, j := 0, 1; i < numTerms; i++ {
2823 from := indx[i].TermOffset
2824 to := indx[j].TermOffset - retlength
2825 j++
2826 txt := string(trms[from:to])
2827 strs[i] = txt
2828 }
2829
2830 var arry []string
2831
2832 for R, str := range strs {
2833 offset := indx[R].PostOffset
2834 size := indx[R+1].PostOffset - offset
2835 line := fmt.Sprintf("%d\t%s\n", size/4, str)
2836 arry = append(arry, line)
2837 }
2838
2839 lst := strings.Join(arry, "")
2840
2841 out <- lst
2842 }
2843
2844 for pth := range inp {
2845 getTermCounts(pth)
2846 }
2847 }
2848
2849 var wg sync.WaitGroup
2850
2851 // launch multiple fetcher goroutines
2852 for range numServe {
2853 wg.Add(1)
2854 go termFetcher(&wg, inp, out)
2855 }
2856
2857 // launch separate anonymous goroutine to wait until all fetchers are done
2858 go func() {
2859 wg.Wait()
2860 close(out)
2861 }()
2862
2863 return out
2864 }
2865
2866 fetchByGroup := func(inp <-chan []string, out chan<- []string) {
2867
2868 defer close(out)
2869
2870 for paths := range inp {
2871 slc := SliceToChan(paths)
2872 tms := fetchTerms(slc)
2873 var tlst []string
2874 for trm := range tms {
2875 tlst = append(tlst, trm)
2876 }
2877 out <- tlst
2878 }
2879 }
2880
2881 go fetchByGroup(inp, out)
2882
2883 return out
2884 }
2885
2886 sortTermSet := func(inp <-chan []string) <-chan string {
2887
2888 if inp == nil {
2889 return nil
2890 }
2891
2892 out := make(chan string, chanDepth)
2893 if out == nil {
2894 DisplayError("Unable to create term sorter channel")
2895 os.Exit(1)
2896 }
2897
2898 sortGroup := func(inp <-chan []string, out chan<- string) {
2899
2900 defer close(out)
2901
2902 sortOneSet := func(tlst []string) {
2903
2904 lists := make(map[string]string)
2905 if lists == nil {
2906 DisplayError("Unable to create term list map")
2907 os.Exit(1)
2908 }
2909
2910 for _, terms := range tlst {
2911
2912 lft, _, foundl := strings.Cut(terms, "\n")
2913 if foundl {
2914 lft = strings.TrimSpace(lft)
2915 _, rgt, foundr := strings.Cut(lft, "\t")
2916 if foundr {
2917 lists[rgt] = terms
2918 } else {
2919 lists[lft] = terms
2920 }
2921 }
2922 }
2923
2924 // sort terms in alphabetical order
2925 keys := slices.Sorted(maps.Keys(lists))
2926
2927 for _, key := range keys {
2928 str := lists[key]
2929 out <- str
2930 }
2931
2932 runtime.Gosched()
2933 }
2934
2935 for tlst := range inp {
2936 sortOneSet(tlst)
2937 }
2938 }
2939
2940 go sortGroup(inp, out)
2941
2942 return out
2943 }
2944
2945 trms := findTopDirs(db, fld)
2946 subs := findSubDirs(trms)
2947 tlst := fetchTermSet(subs)
2948 srts := sortTermSet(tlst)
2949
2950 if trms == nil || subs == nil || tlst == nil || srts == nil {
2951 DisplayError("Unable to create term generator")
2952 os.Exit(1)
2953 }
2954
2955 return srts
2956 }
2957
2958 // StreamTerms prints all postings terms for a given field
2959 func StreamTerms(db, fld string) <-chan string {
2960
2961 return streamTermsOrTotals(db, fld, true)
2962 }
2963
2964 // StreamTotals prints all postings terms and counts for a given field
2965 func StreamTotals(db, fld string) <-chan string {
2966
2967 return streamTermsOrTotals(db, fld, false)
2968 }
2969
2970 // initialize empty journal and MeSH maps before non-init functions are called
2971 func init() {
2972
2973 meshName.table = make(map[string]string)
2974 meshTree.table = make(map[string]string)
2975 }