Debian Codegraph @

eutils/citref.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: citref.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "bytes"
36 "fmt"
37 "html"
38 "io"
39 "math"
40 "net/http"
41 "net/url"
42 "os"
43 "regexp"
44 "slices"
45 "strconv"
46 "strings"
47 "sync"
48 "time"
49 "unicode"
50 )
51
52 func cit2json(query string) string {
53
54 if query == "" {
55 return ""
56 }
57
58 q := url.Values{}
59 q.Add("method", "heuristic")
60 q.Add("raw-text", query)
61 params := q.Encode()
62
63 base := "https://pubmed.ncbi.nlm.nih.gov/api/citmatch"
64 path := fmt.Sprintf("%s?%s", base, params)
65
66 // persistent HTTP connection by default
67 resp, err := http.Get(path)
68 if err != nil {
69 fmt.Fprintf(os.Stderr, "%s\n", err)
70 return ""
71 }
72
73 // client must read and close response body to keep connection alive
74 defer resp.Body.Close()
75
76 body, err := io.ReadAll(resp.Body)
77 if err != nil {
78 fmt.Fprintf(os.Stderr, "%s\n", err)
79 return ""
80 }
81
82 jsn := string(body) + "\n"
83
84 return jsn
85 }
86
87 func json2pmid(jsn string) (bool, string, string) {
88
89 if jsn == "" {
90 return false, "empty", "0"
91 }
92
93 if strings.Index(jsn, "Too Many Requests") > 1 {
94 return true, "overuse", "0"
95 }
96
97 if strings.Index(jsn, "doctype") > 1 {
98 return false, "failed", "0"
99 }
100
101 if strings.Index(jsn, "internal server error") > 1 {
102 return false, "error", "0"
103 }
104
105 if strings.Index(jsn, "\"success\":false,") > 1 {
106 return false, "failure", "0"
107 }
108
109 if strings.Index(jsn, "\"count\":1,") > 1 {
110 pos := strings.Index(jsn, "pubmed")
111 if pos > 1 {
112 npmid := jsn[pos+9:]
113 pos = strings.Index(npmid, "\"")
114 if pos > 0 {
115 npmid = npmid[:pos]
116 if IsAllDigits(npmid) {
117 value, err := strconv.Atoi(npmid)
118 if err == nil && value > 0 {
119 // success
120 return true, "citmatch", npmid
121 }
122 }
123 }
124 }
125 return true, "unrecognized", "0"
126 }
127
128 if strings.Index(jsn, "\"count\":0,") < 0 {
129 return false, "unknown", "0"
130 }
131
132 return true, "unmatched", "0"
133 }
134
135 // Citation2PMID is a shortcut for extracting the PMID from the citMatch network service result
136 func Citation2PMID(query string) string {
137
138 if query == "" {
139 return ""
140 }
141
142 jsn := cit2json(query)
143
144 ok, _, pmid := json2pmid(jsn)
145
146 if !ok {
147 // try a second time on server failure
148 jsn = cit2json(query)
149 _, _, pmid = json2pmid(jsn)
150 }
151
152 return pmid
153 }
154
155 func regenerateCitText(citFields map[string]string) string {
156
157 if citFields == nil {
158 return ""
159 }
160
161 var cmtx []string
162
163 faut := citFields["FAUT"]
164 laut := citFields["LAUT"]
165 csrt := citFields["CSRT"]
166 titl := citFields["TITL"]
167 jour := citFields["JOUR"]
168 vol := citFields["VOL"]
169 iss := citFields["ISS"]
170 page := citFields["PAGE"]
171 year := citFields["YEAR"]
172
173 ttl := titl
174 ttl = strings.Replace(ttl, ".", "", -1)
175 ttl = strings.Replace(ttl, "(", "", -1)
176 ttl = strings.Replace(ttl, ")", "", -1)
177
178 jnl := jour
179 jnl = strings.Replace(jnl, ".", "", -1)
180 jnl = strings.Replace(jnl, "(", "", -1)
181 jnl = strings.Replace(jnl, ")", "", -1)
182
183 pg, _ := SplitInTwoLeft(page, "-")
184
185 // populate TEXT items
186 addItem := func(val string) {
187 if val != "" {
188 cmtx = append(cmtx, val)
189 }
190 }
191
192 addItem(faut)
193 if laut != faut {
194 addItem(laut)
195 }
196 if faut == "" && laut == "" {
197 addItem(csrt)
198 }
199 addItem(ttl)
200 addItem(jnl)
201 addItem(vol)
202 addItem(iss)
203 addItem(pg)
204 addItem(year)
205
206 cmtxt := strings.Join(cmtx, " ")
207 cmtxt = strings.TrimSpace(cmtxt)
208 cmtxt = CompressRunsOfSpaces(cmtxt)
209
210 return cmtxt
211 }
212
213 // NormalizeCitation moves PMID to ORIG, and creates TEXT, if not already present
214 func NormalizeCitation(text string) string {
215
216 if text == "" {
217 return ""
218 }
219
220 citFields := make(map[string]string)
221
222 // stream tokens, collecting XML values in map
223 StreamValues(text[:], "CITATION", func(tag, attr, content string) { citFields[tag] = content })
224
225 // remove original TEXT field
226 delete(citFields, "TEXT")
227
228 // regenerate TEXT value
229 citFields["TEXT"] = regenerateCitText(citFields)
230
231 // collect fields in desired order
232 flds := []string{"ACCN", "DIV", "REF", "FAUT", "LAUT", "CSRT", "ATHR", "TITL",
233 "JOUR", "VOL", "ISS", "PAGE", "YEAR", "TEXT", "STAT", "ORIG", "PMID", "NOTE"}
234
235 var arry []string
236
237 for _, fld := range flds {
238 nxt, ok := citFields[fld]
239 if ok && nxt != "" {
240 arry = append(arry, "<"+fld+">"+nxt+"</"+fld+">")
241 }
242 }
243
244 body := strings.Join(arry, "")
245
246 res := "<CITATION>" + body + "</CITATION>"
247
248 return res
249 }
250
251 func genBankRefIndex(inp io.Reader, deStop, doStem bool) <-chan string {
252
253 if inp == nil {
254 return nil
255 }
256
257 out := make(chan string, chanDepth)
258 if out == nil {
259 DisplayError("Unable to create GenBank converter channel")
260 os.Exit(1)
261 }
262
263 const twelvespaces = " "
264 const twentyonespaces = " "
265
266 indexGenBank := func(inp io.Reader, out chan<- string) {
267
268 // close channel when all records have been sent
269 defer close(out)
270
271 var rec strings.Builder
272
273 var arry []string
274
275 var cmtx []string
276
277 scanr := bufio.NewScanner(inp)
278
279 row := 0
280
281 prevTitles := make(map[string]bool)
282
283 nextLine := func() string {
284
285 for scanr.Scan() {
286 line := scanr.Text()
287 if line == "" {
288 continue
289 }
290 return line
291 }
292 return ""
293
294 }
295
296 for {
297 arry = nil
298 cmtx = nil
299
300 division := ""
301 dirSub := false
302
303 // read first line of next record
304 line := nextLine()
305 if line == "" {
306 break
307 }
308
309 row++
310
311 for {
312 if line == "" {
313 break
314 }
315 if !strings.HasPrefix(line, "LOCUS") {
316 // skip release file header information
317 line = nextLine()
318 row++
319 continue
320 }
321 break
322 }
323
324 readContinuationLines := func(str string) string {
325
326 for {
327 // read next line
328 line = nextLine()
329 row++
330 if !strings.HasPrefix(line, twelvespaces) {
331 // if not continuation line, break out of loop
332 break
333 }
334 // append subsequent line and continue with loop
335 txt := strings.TrimPrefix(line, twelvespaces)
336 str += " " + txt
337 }
338
339 str = CompressRunsOfSpaces(str)
340 str = strings.TrimSpace(str)
341
342 return str
343 }
344
345 writeOneElement := func(spaces, tag, value string) {
346
347 rec.WriteString(spaces)
348 rec.WriteString("<")
349 rec.WriteString(tag)
350 rec.WriteString(">")
351 value = html.EscapeString(value)
352 rec.WriteString(value)
353 rec.WriteString("</")
354 rec.WriteString(tag)
355 rec.WriteString(">\n")
356 }
357
358 // each section will exit with the next line ready to process
359
360 if strings.HasPrefix(line, "LOCUS") {
361
362 // start of record
363
364 // do not break if given artificial multi-line LOCUS
365 str := readContinuationLines(line)
366
367 cols := strings.Fields(str)
368 ln := len(cols)
369 if ln == 8 {
370 division = cols[6]
371 } else if ln == 7 {
372 division = cols[5]
373 }
374
375 // read next line and continue - handled by readContinuationLines above
376 // line = nextLine()
377 // row++
378 }
379
380 if strings.HasPrefix(line, "DEFINITION") {
381 readContinuationLines(line)
382 }
383
384 // record accession
385 accn := ""
386
387 if strings.HasPrefix(line, "ACCESSION") {
388
389 txt := strings.TrimPrefix(line, "ACCESSION")
390 str := readContinuationLines(txt)
391 accessions := strings.Fields(str)
392 ln := len(accessions)
393 if ln > 0 {
394 accn = accessions[0]
395 }
396 }
397
398 if strings.HasPrefix(line, "VERSION") {
399
400 cols := strings.Fields(line)
401 if len(cols) == 2 || len(cols) == 3 {
402 accn = cols[1]
403 }
404
405 // read next line and continue
406 line = nextLine()
407 row++
408 }
409
410 if strings.HasPrefix(line, "DBLINK") {
411 readContinuationLines(line)
412 }
413
414 if strings.HasPrefix(line, "DBSOURCE") {
415 readContinuationLines(line)
416 }
417
418 if strings.HasPrefix(line, "KEYWORDS") {
419 readContinuationLines(line)
420 }
421
422 if strings.HasPrefix(line, "SOURCE") {
423 readContinuationLines(line)
424 }
425
426 if strings.HasPrefix(line, " ORGANISM") {
427
428 line = nextLine()
429 row++
430 if strings.HasPrefix(line, twelvespaces) {
431 readContinuationLines(line)
432 }
433 }
434
435 // beginning of reference section
436 for {
437 if !strings.HasPrefix(line, "REFERENCE") {
438 // exit out of reference section
439 break
440 }
441
442 rec.Reset()
443
444 rec.WriteString(" <CITATION>\n")
445
446 if accn != "" {
447 writeOneElement(" ", "ACCN", accn)
448 }
449
450 if division != "" {
451 writeOneElement(" ", "DIV", division)
452 }
453
454 txt := strings.TrimPrefix(line, "REFERENCE")
455 str := readContinuationLines(txt)
456 str = CompressRunsOfSpaces(str)
457 str = strings.TrimSpace(str)
458 idx := strings.Index(str, "(")
459 ref := ""
460 if idx > 0 {
461 ref = strings.TrimSpace(str[:idx])
462 } else {
463 ref = strings.TrimSpace(str)
464 }
465 // reference number
466 writeOneElement(" ", "REF", ref)
467 row++
468
469 faut := ""
470 laut := ""
471
472 var athr []string
473
474 if strings.HasPrefix(line, " AUTHORS") {
475
476 count := 0
477
478 txt := strings.TrimPrefix(line, " AUTHORS")
479 auths := readContinuationLines(txt)
480
481 authors := strings.Split(auths, ", ")
482 for _, auth := range authors {
483 auth = strings.TrimSpace(auth)
484 if auth == "" {
485 continue
486 }
487 pair := strings.Split(auth, " and ")
488 for _, name := range pair {
489
490 // convert GenBank author to searchable form
491 name = GenBankToMedlineAuthors(name)
492
493 if faut == "" {
494 faut = name
495 }
496 laut = name
497
498 athr = append(athr, name)
499 // writeOneElement(" ", "AUTH", name)
500
501 count++
502 }
503 }
504
505 if faut != "" {
506 writeOneElement(" ", "FAUT", faut)
507 cmtx = append(cmtx, faut)
508 }
509 if laut != "" {
510 writeOneElement(" ", "LAUT", laut)
511 if laut != faut {
512 cmtx = append(cmtx, laut)
513 }
514 }
515 if len(athr) > 0 {
516 athrs := strings.Join(athr, ", ")
517 writeOneElement(" ", "ATHR", athrs)
518 }
519 }
520
521 if strings.HasPrefix(line, " CONSRTM") {
522
523 txt := strings.TrimPrefix(line, " CONSRTM")
524 cons := readContinuationLines(txt)
525
526 writeOneElement(" ", "CSRT", cons)
527 if faut == "" && laut == "" {
528 cmtx = append(cmtx, cons)
529 }
530 }
531
532 inPress := false
533
534 if strings.HasPrefix(line, " TITLE") {
535
536 txt := strings.TrimPrefix(line, " TITLE")
537 titl := readContinuationLines(txt)
538
539 if titl != "" {
540 writeOneElement(" ", "TITL", titl)
541 ttl := titl
542 ttl = strings.Replace(ttl, ".", "", -1)
543 ttl = strings.Replace(ttl, "(", "", -1)
544 ttl = strings.Replace(ttl, ")", "", -1)
545 cmtx = append(cmtx, ttl)
546 }
547
548 if titl == "Direct Submission" {
549 dirSub = true
550 }
551 }
552
553 if strings.HasPrefix(line, " JOURNAL") {
554
555 txt := strings.TrimPrefix(line, " JOURNAL")
556 jour := readContinuationLines(txt)
557
558 if strings.HasSuffix(jour, " In press") {
559 inPress = true
560 }
561
562 if dirSub {
563 if len(jour) > 23 && strings.HasPrefix(jour, "Submitted (") {
564 year := jour[18:22]
565 year = strings.TrimSpace(year)
566 if year != "" {
567 writeOneElement(" ", "YEAR", year)
568 }
569 }
570 } else if inPress {
571 jour = strings.TrimSuffix(jour, " In press")
572 if strings.HasSuffix(jour, ")") {
573 idx0 := strings.LastIndex(jour, "(")
574 if idx0 >= 0 {
575 doi := ""
576 year := jour[idx0:]
577 jour := jour[:idx0]
578 year = strings.TrimPrefix(year, "(")
579 year = strings.TrimSuffix(year, ")")
580 year = strings.TrimSpace(year)
581 jour = strings.TrimSpace(jour)
582 idxd := strings.Index(jour, ", doi:")
583 if idxd >= 0 {
584 doi = jour[idxd:]
585 jour = jour[:idxd]
586 doi = strings.TrimPrefix(doi, ", doi:")
587 jour = strings.TrimSpace(jour)
588 doi = strings.TrimSpace(doi)
589 }
590 // truncate journal at comma
591 cmma := strings.Index(jour, ",")
592 if cmma >= 0 {
593 jour = jour[:cmma]
594 }
595 // truncate journal at first digit
596 for i, r := range jour {
597 if unicode.IsDigit(r) {
598 jour = jour[:i]
599 break
600 }
601 }
602 // check for parenthetical city, e.g., "Mol. Biol. (Mosk.)"
603 if jour != "" && doi == "" && year != "" && !IsAllDigits(year) {
604 year = strings.TrimSuffix(year, ".")
605 jour += " (" + year + ")"
606 year = ""
607 }
608 jour = strings.Replace(jour, "&#39;", "'", -1)
609 jour = strings.Replace(jour, "'", "", -1)
610 jour = strings.Replace(jour, ".", " ", -1)
611 jour = strings.TrimSpace(jour)
612 jour = CompressRunsOfSpaces(jour)
613 if jour != "" {
614 writeOneElement(" ", "JOUR", jour)
615 jnl := jour
616 jnl = strings.Replace(jnl, ".", "", -1)
617 jnl = strings.Replace(jnl, "(", "", -1)
618 jnl = strings.Replace(jnl, ")", "", -1)
619 cmtx = append(cmtx, jnl)
620 }
621 if doi != "" {
622 writeOneElement(" ", "DOI", doi)
623 }
624 if year != "" && IsAllDigits(year) {
625 writeOneElement(" ", "YEAR", year)
626 cmtx = append(cmtx, year)
627 }
628 }
629 } else {
630 // no year, just get in-press journal
631 jour = strings.Replace(jour, "&#39;", "'", -1)
632 jour = strings.Replace(jour, "'", "", -1)
633 jour = strings.Replace(jour, ".", " ", -1)
634 jour = strings.TrimSpace(jour)
635 jour = CompressRunsOfSpaces(jour)
636 if jour != "" {
637 writeOneElement(" ", "JOUR", jour)
638 jnl := jour
639 jnl = strings.Replace(jnl, ".", "", -1)
640 jnl = strings.Replace(jnl, "(", "", -1)
641 jnl = strings.Replace(jnl, ")", "", -1)
642 cmtx = append(cmtx, jnl)
643 }
644 }
645 } else {
646 journal := ""
647 volume := ""
648 issue := ""
649 pages := ""
650 year := ""
651 lft, rgt := SplitInTwoLeft(jour, ",")
652 if lft != "" && rgt != "" {
653 if strings.HasSuffix(lft, ")") {
654 idx1 := strings.LastIndex(lft, "(")
655 if idx1 >= 0 {
656 issue = lft[idx1:]
657 lft = lft[:idx1]
658 issue = strings.TrimPrefix(issue, "(")
659 issue = strings.TrimSuffix(issue, ")")
660 issue = strings.TrimSpace(issue)
661 lft = strings.TrimSpace(lft)
662 }
663 }
664 idx2 := strings.LastIndex(lft, " ")
665 if idx2 >= 0 {
666 volume = lft[idx2:]
667 lft = lft[:idx2]
668 volume = strings.TrimSpace(volume)
669 lft = strings.TrimSpace(lft)
670 }
671 journal = lft
672 if strings.HasSuffix(rgt, ")") {
673 idx3 := strings.LastIndex(rgt, "(")
674 if idx3 >= 0 {
675 year = rgt[idx3:]
676 rgt = rgt[:idx3]
677 year = strings.TrimPrefix(year, "(")
678 year = strings.TrimSuffix(year, ")")
679 year = strings.TrimSpace(year)
680 rgt = strings.TrimSpace(rgt)
681 }
682 }
683 pages = rgt
684 journal = strings.TrimSpace(journal)
685 pages = strings.TrimSpace(pages)
686 journal = strings.Replace(journal, ".", " ", -1)
687 journal = strings.TrimSpace(journal)
688 journal = CompressRunsOfSpaces(journal)
689 if journal != "" {
690 writeOneElement(" ", "JOUR", journal)
691 jnl := journal
692 jnl = strings.Replace(jnl, ".", "", -1)
693 jnl = strings.Replace(jnl, "(", "", -1)
694 jnl = strings.Replace(jnl, ")", "", -1)
695 cmtx = append(cmtx, jnl)
696 }
697 if volume != "" {
698 writeOneElement(" ", "VOL", volume)
699 cmtx = append(cmtx, volume)
700 }
701 if issue != "" {
702 writeOneElement(" ", "ISS", issue)
703 cmtx = append(cmtx, issue)
704 }
705 if pages != "" {
706 writeOneElement(" ", "PAGE", pages)
707 pg, _ := SplitInTwoLeft(pages, "-")
708 cmtx = append(cmtx, pg)
709 }
710 if year != "" {
711 writeOneElement(" ", "YEAR", year)
712 cmtx = append(cmtx, year)
713 }
714 }
715 }
716
717 }
718
719 cmtxt := strings.Join(cmtx, " ")
720 cmtxt = strings.TrimSpace(cmtxt)
721 cmtxt = CompressRunsOfSpaces(cmtxt)
722 if cmtxt != "" {
723 // write TEXT field for citmatch service
724 writeOneElement(" ", "TEXT", cmtxt)
725 }
726
727 pmid := ""
728 if strings.HasPrefix(line, " PUBMED") {
729
730 txt := strings.TrimPrefix(line, " PUBMED")
731 pmid = readContinuationLines(txt)
732
733 pmid = strings.TrimSpace(pmid)
734 }
735
736 stat := ""
737 if dirSub {
738 stat = "dirsub"
739 } else if inPress {
740 stat = "inpress"
741 } else if pmid != "" {
742 stat = "published"
743 } else {
744 stat = "unpub"
745 }
746
747 isDuplicate := false
748 prv := cmtxt
749 if prv != "" {
750 if prevTitles[prv] {
751 isDuplicate = true
752 } else {
753 prevTitles[prv] = true
754 }
755 }
756
757 writeOneElement(" ", "STAT", stat)
758
759 if strings.HasPrefix(line, " MEDLINE") {
760 // old MEDLINE uid not supported
761 readContinuationLines(line)
762 }
763
764 if strings.HasPrefix(line, " REMARK") {
765 readContinuationLines(line)
766 }
767
768 if pmid != "" {
769 // write PMID immediately before end of CITATION object
770 writeOneElement(" ", "ORIG", pmid)
771 }
772
773 rec.WriteString(" </CITATION>")
774
775 txt = rec.String()
776
777 if !isDuplicate {
778
779 // record nonredundant reference
780 arry = append(arry, txt)
781 }
782
783 // reset working buffer
784 rec.Reset()
785 // continue to next reference
786 }
787 // end of reference section
788
789 if strings.HasPrefix(line, "COMMENT") {
790 readContinuationLines(line)
791 }
792
793 if strings.HasPrefix(line, "PRIMARY") {
794 readContinuationLines(line)
795 }
796
797 if strings.HasPrefix(line, "FEATURES") {
798
799 line = nextLine()
800 row++
801
802 for {
803 if !strings.HasPrefix(line, " ") {
804 // exit out of features section
805 break
806 }
807 if len(line) < 22 {
808 line = nextLine()
809 row++
810 continue
811 }
812
813 for {
814 line = nextLine()
815 row++
816 if !strings.HasPrefix(line, twentyonespaces) {
817 break
818 }
819 txt := strings.TrimPrefix(line, twentyonespaces)
820 if strings.HasPrefix(txt, "/") {
821 // if not continuation of location, break out of loop
822 break
823 }
824 // append subsequent line and continue with loop
825 }
826
827 for {
828 if !strings.HasPrefix(line, twentyonespaces) {
829 // if not qualifier line, break out of loop
830 break
831 }
832 txt := strings.TrimPrefix(line, twentyonespaces)
833 if strings.HasPrefix(txt, "/") {
834 // read new qualifier and start of value
835
836 for {
837 line = nextLine()
838 row++
839 if !strings.HasPrefix(line, twentyonespaces) {
840 break
841 }
842 txt := strings.TrimPrefix(line, twentyonespaces)
843 if strings.HasPrefix(txt, "/") {
844 // if not continuation of qualifier, break out of loop
845 break
846 }
847 // append subsequent line to value and continue with loop
848 }
849 }
850 }
851 // end of this feature
852 // continue to next feature
853 }
854 }
855 // TSA, TLS, WGS, or CONTIG lines may be next
856
857 altName := ""
858
859 if strings.HasPrefix(line, "TSA") ||
860 strings.HasPrefix(line, "TLS") ||
861 strings.HasPrefix(line, "WGS") {
862
863 line = line[3:]
864 }
865
866 if strings.HasPrefix(line, "WGS_CONTIG") ||
867 strings.HasPrefix(line, "WGS_SCAFLD") {
868
869 line = line[10:]
870 }
871
872 if altName != "" {
873
874 for {
875 // read next line
876 line = nextLine()
877 row++
878 if !strings.HasPrefix(line, twelvespaces) {
879 // if not continuation of contig, break out of loop
880 break
881 }
882 // append subsequent line and continue with loop
883 }
884 }
885
886 if strings.HasPrefix(line, "CONTIG") {
887
888 for {
889 // read next line
890 line = nextLine()
891 row++
892 if !strings.HasPrefix(line, twelvespaces) {
893 // if not continuation of contig, break out of loop
894 break
895 }
896 // append subsequent line and continue with loop
897 }
898 }
899
900 if strings.HasPrefix(line, "BASE COUNT") {
901 readContinuationLines(line)
902 // not supported
903 }
904
905 if strings.HasPrefix(line, "ORIGIN") {
906
907 line = nextLine()
908 row++
909 }
910
911 // remainder should be sequence
912
913 for line != "" {
914
915 if strings.HasPrefix(line, "//") {
916
917 for _, txt := range arry {
918 // send formatted record down channel
919 out <- txt
920 }
921
922 // go to top of loop for next record
923 break
924 }
925
926 // read next line and continue
927 line = nextLine()
928 row++
929
930 }
931
932 // continue to next record
933 }
934 }
935
936 // launch single indexer goroutine
937 go indexGenBank(inp, out)
938
939 return out
940 }
941
942 func emblRefIndex(inp io.Reader, deStop, doStem bool) <-chan string {
943
944 if inp == nil {
945 return nil
946 }
947
948 out := make(chan string, chanDepth)
949 if out == nil {
950 DisplayError("Unable to create EMBL converter channel")
951 os.Exit(1)
952 }
953
954 indexEmbl := func(inp io.Reader, out chan<- string) {
955
956 // close channel when all records have been sent
957 defer close(out)
958
959 var rec strings.Builder
960
961 var cmtx []string
962
963 scanr := bufio.NewScanner(inp)
964
965 row := 0
966 line := ""
967
968 prevTitles := make(map[string]bool)
969
970 nextLine := func() string {
971
972 for scanr.Scan() {
973 line := scanr.Text()
974 if line == "" {
975 continue
976 }
977 return line
978 }
979 return ""
980
981 }
982
983 for {
984 if line == "" {
985 break
986 }
987 if !strings.HasPrefix(line, "ID ") {
988 // skip release file header information
989 line = nextLine()
990 row++
991 continue
992 }
993 break
994 }
995
996 for {
997
998 accn := ""
999
1000 for {
1001
1002 // read next line of record
1003 line = nextLine()
1004 if line == "" {
1005 break
1006 }
1007
1008 row++
1009
1010 if strings.HasPrefix(line, "ID ") {
1011 continue
1012 }
1013
1014 if strings.HasPrefix(line, "XX") {
1015 continue
1016 }
1017
1018 if strings.HasPrefix(line, "AC ") {
1019
1020 // read accession
1021 accn = strings.TrimPrefix(line, "AC ")
1022 pos := strings.Index(accn, ";")
1023 if pos >= 0 {
1024 accn = accn[:pos]
1025 }
1026 accn = strings.TrimSpace(accn)
1027 continue
1028 }
1029
1030 if strings.HasPrefix(line, "SV ") {
1031
1032 // accession.version overrides accession
1033 accn = strings.TrimPrefix(line, "SV ")
1034 accn = strings.TrimSpace(accn)
1035 continue
1036 }
1037
1038 for strings.HasPrefix(line, "RN ") {
1039
1040 cmtx = nil
1041
1042 // start of publication
1043 rn := strings.TrimPrefix(line, "RN [")
1044 pos := strings.Index(rn, "]")
1045 if pos >= 0 {
1046 rn = rn[:pos]
1047 }
1048
1049 // read next line
1050 line = nextLine()
1051 row++
1052
1053 writeOneElement := func(spaces, tag, value string) {
1054
1055 rec.WriteString(spaces)
1056 rec.WriteString("<")
1057 rec.WriteString(tag)
1058 rec.WriteString(">")
1059 value = html.EscapeString(value)
1060 rec.WriteString(value)
1061 rec.WriteString("</")
1062 rec.WriteString(tag)
1063 rec.WriteString(">\n")
1064 }
1065
1066 isContinuation := func(txt string) bool {
1067
1068 if txt == "" {
1069 return false
1070 }
1071 if txt == "XX" || txt == "//" {
1072 return false
1073 }
1074 if len(txt) < 6 {
1075 return true
1076 }
1077 if txt[0] >= 'A' && txt[0] <= 'Z' &&
1078 txt[1] >= 'A' && txt[1] <= 'Z' &&
1079 txt[2] == ' ' && txt[3] == ' ' && txt[4] == ' ' {
1080 return false
1081 }
1082 return true
1083 }
1084
1085 collectRefStrings := func(pfx string) string {
1086
1087 if !strings.HasPrefix(line, pfx) {
1088 return ""
1089 }
1090
1091 var arry []string
1092
1093 str := strings.TrimPrefix(line, pfx)
1094 str = strings.TrimSpace(str)
1095 arry = append(arry, str)
1096
1097 res := ""
1098 for {
1099 line = nextLine()
1100 row++
1101
1102 if strings.HasPrefix(line, pfx) {
1103 str = strings.TrimPrefix(line, pfx)
1104 arry = append(arry, str)
1105 } else if isContinuation(line) {
1106 arry = append(arry, line)
1107 } else {
1108 res = strings.Join(arry, " ")
1109 break
1110 }
1111 }
1112
1113 res = strings.TrimSuffix(res, ";")
1114 if strings.HasPrefix(res, "\"") && strings.HasSuffix(res, "\"") {
1115 res = strings.TrimPrefix(res, "\"")
1116 res = strings.TrimSuffix(res, "\"")
1117 }
1118 res = strings.TrimSpace(res)
1119 return res
1120 }
1121
1122 // collect publication fields
1123
1124 collectRefStrings("RP ")
1125 collectRefStrings("RC ")
1126 rx := collectRefStrings("RX ")
1127 ra := collectRefStrings("RA ")
1128 rg := collectRefStrings("RG ")
1129 rt := collectRefStrings("RT ")
1130 rl := collectRefStrings("RL ")
1131
1132 isolateAuthors := func(ra string) (string, string, string) {
1133
1134 if ra == "" {
1135 return "", "", ""
1136 }
1137
1138 ra = strings.Replace(ra, ".", "", -1)
1139 ra = strings.TrimSpace(ra)
1140
1141 var auths []string
1142
1143 auths = strings.Split(ra, ", ")
1144 alen := len(auths)
1145 if alen < 1 {
1146 return "", "", ""
1147 }
1148
1149 fst := auths[0]
1150 lst := auths[alen-1]
1151 if lst == fst {
1152 lst = ""
1153 }
1154
1155 return fst, lst, ra
1156 }
1157
1158 faut, laut, athr := isolateAuthors(ra)
1159
1160 pmid := ""
1161 if strings.HasPrefix(rx, "PubMed=") {
1162 rx = strings.TrimPrefix(rx, "PubMed=")
1163 pos := strings.Index(rx, ";")
1164 if pos >= 0 {
1165 rx = rx[:pos]
1166 }
1167 rx = strings.TrimSpace(rx)
1168 pmid = rx
1169 }
1170
1171 titl := rt
1172
1173 jour := ""
1174 vol := ""
1175 page := ""
1176 year := ""
1177
1178 submitted := false
1179 if strings.HasPrefix(rl, "Submitted") {
1180 submitted = true
1181 } else if strings.HasSuffix(rl, ").") {
1182 pos := strings.LastIndex(rl, "(")
1183 if pos >= 0 {
1184 fst := rl[:pos]
1185 year = rl[pos:]
1186 year = strings.TrimPrefix(year, "(")
1187 year = strings.TrimSuffix(year, ").")
1188 pos = strings.Index(fst, ":")
1189 if pos >= 0 {
1190 pos = strings.LastIndex(fst, " ")
1191 if pos >= 0 {
1192 jour = fst[:pos]
1193 nxt := fst[pos+1:]
1194 vol, page = SplitInTwoLeft(nxt, ":")
1195 page, _ = SplitInTwoLeft(page, "-")
1196 }
1197 }
1198 }
1199 }
1200
1201 rec.Reset()
1202
1203 // if no journal, skip
1204 if submitted {
1205 continue
1206 }
1207
1208 rec.WriteString(" <CITATION>\n")
1209
1210 if accn != "" {
1211 writeOneElement(" ", "ACCN", accn)
1212 }
1213
1214 writeOneElement(" ", "REF", rn)
1215
1216 if faut != "" {
1217 writeOneElement(" ", "FAUT", faut)
1218 cmtx = append(cmtx, faut)
1219 }
1220 if laut != "" {
1221 writeOneElement(" ", "LAUT", laut)
1222 if laut != faut {
1223 cmtx = append(cmtx, laut)
1224 }
1225 }
1226 if athr != "" {
1227 writeOneElement(" ", "ATHR", athr)
1228 }
1229
1230 if rg != "" {
1231 writeOneElement(" ", "CSRT", rg)
1232 if faut == "" && laut == "" {
1233 cmtx = append(cmtx, rg)
1234 }
1235 }
1236
1237 if titl != "" {
1238 writeOneElement(" ", "TITL", titl)
1239 ttl := titl
1240 ttl = strings.Replace(ttl, ".", "", -1)
1241 ttl = strings.Replace(ttl, "(", "", -1)
1242 ttl = strings.Replace(ttl, ")", "", -1)
1243 cmtx = append(cmtx, ttl)
1244 }
1245
1246 if jour != "" {
1247 jour = strings.Replace(jour, "&#39;", "'", -1)
1248 jour = strings.Replace(jour, "'", "", -1)
1249 jour = strings.Replace(jour, ".", " ", -1)
1250 jour = strings.TrimSpace(jour)
1251 jour = CompressRunsOfSpaces(jour)
1252 writeOneElement(" ", "JOUR", jour)
1253 jnl := jour
1254 jnl = strings.Replace(jnl, ".", "", -1)
1255 jnl = strings.Replace(jnl, "(", "", -1)
1256 jnl = strings.Replace(jnl, ")", "", -1)
1257 cmtx = append(cmtx, jnl)
1258 }
1259 if vol != "" {
1260 writeOneElement(" ", "VOL", vol)
1261 cmtx = append(cmtx, vol)
1262 }
1263 if page != "" {
1264 writeOneElement(" ", "PAGE", page)
1265 pg, _ := SplitInTwoLeft(page, "-")
1266 cmtx = append(cmtx, pg)
1267 }
1268 if year != "" {
1269 writeOneElement(" ", "YEAR", year)
1270 cmtx = append(cmtx, year)
1271 }
1272
1273 cmtxt := strings.Join(cmtx, " ")
1274 cmtxt = strings.TrimSpace(cmtxt)
1275 cmtxt = CompressRunsOfSpaces(cmtxt)
1276 if cmtxt != "" {
1277 // write TEXT field for citmatch service
1278 writeOneElement(" ", "TEXT", cmtxt)
1279 }
1280
1281 isDuplicate := false
1282 prv := cmtxt
1283 if prv != "" {
1284 if prevTitles[prv] {
1285 isDuplicate = true
1286 } else {
1287 prevTitles[prv] = true
1288 }
1289 }
1290
1291 if pmid != "" {
1292 // write PMID immediately before end of CITATION object
1293 writeOneElement(" ", "ORIG", pmid)
1294 }
1295
1296 rec.WriteString(" </CITATION>")
1297
1298 txt := rec.String()
1299
1300 if !isDuplicate {
1301
1302 // record nonredundant reference
1303 out <- txt
1304 }
1305 }
1306
1307 if strings.HasPrefix(line, "//") {
1308
1309 // go to top of loop for next record
1310 break
1311 }
1312
1313 // continue reading lines
1314 }
1315
1316 line = nextLine()
1317 if line == "" {
1318 break
1319 }
1320 }
1321 }
1322
1323 // launch single indexer goroutine
1324 go indexEmbl(inp, out)
1325
1326 return out
1327 }
1328
1329 // GenBankRefIndex reads GenBank or EMBL flatfiles and sends reference index XML records down a channel
1330 func GenBankRefIndex(inp io.Reader, deStop, doStem bool) <-chan string {
1331
1332 if inp == nil {
1333 return nil
1334 }
1335
1336 const FirstBuffSize = 4096
1337
1338 getFirstBlock := func() string {
1339
1340 buffer := make([]byte, FirstBuffSize)
1341 n, err := inp.Read(buffer)
1342 if err != nil && err != io.EOF {
1343 DisplayError("Unable to read first block: %s", err.Error())
1344 // os.Exit(1)
1345 }
1346 bufr := buffer[:n]
1347 return string(bufr)
1348 }
1349
1350 first := getFirstBlock()
1351
1352 mlt := io.MultiReader(strings.NewReader(first), inp)
1353
1354 isGbf := false
1355 isEbi := false
1356 matched := 0
1357
1358 // auto-detect GenBank/GenPept or EBI/EMBL/UniProt format
1359 if first != "" {
1360 posG1 := strings.Index(first, "LOCUS")
1361 posG2 := strings.Index(first, "DEFINITION")
1362 if posG1 >= 0 && posG2 >= 0 && posG1 < posG2 {
1363 isGbf = true
1364 matched++
1365 } else {
1366 posG1 = FirstBuffSize
1367 posG2 = FirstBuffSize
1368 }
1369 posE1 := strings.Index(first, "ID ")
1370 posE2 := strings.Index(first, "DE ")
1371 if posE1 >= 0 && posE2 >= 0 && posE1 < posE2 {
1372 isEbi = true
1373 matched++
1374 } else {
1375 posE1 = FirstBuffSize
1376 posE2 = FirstBuffSize
1377 }
1378 if matched > 1 {
1379 if posG1 < posE1 && posG2 < posE2 {
1380 isEbi = false
1381 } else {
1382 isGbf = false
1383 }
1384 }
1385 }
1386
1387 if isGbf {
1388 return genBankRefIndex(mlt, deStop, doStem)
1389 } else if isEbi {
1390 return emblRefIndex(mlt, deStop, doStem)
1391 }
1392
1393 // neither format detected
1394 return nil
1395 }
1396
1397 // CitCache structure used to prevent duplicate processing of same reference in pop/phy/mut/eco set components
1398 type CitCache struct {
1399 // citation cache variables
1400 mlock sync.Mutex
1401 matchRingList []string
1402 matchResultCache map[string]string
1403 inUse map[string]bool
1404 maximum int
1405 }
1406
1407 // NewCitCache allows server application to maintain cache over multiple calls to CreateCitMatchers
1408 func NewCitCache(max int) *CitCache {
1409
1410 // 0 defaults to keeping most recent 500 matches
1411 if max == 0 {
1412 max = 500
1413 }
1414 // -1 eliminates practical limits in the match cache
1415 if max == -1 {
1416 max = math.MaxInt32
1417 }
1418
1419 return &CitCache{
1420 matchResultCache: make(map[string]string),
1421 inUse: make(map[string]bool),
1422 maximum: max,
1423 }
1424 }
1425
1426 // PreloadCitCache reads -format compact CITATION XML after ref2pmid lookup
1427 func PreloadCitCache(fileName string, cache *CitCache) {
1428
1429 if fileName == "" || cache == nil {
1430 return
1431 }
1432
1433 inFile, err := os.Open(fileName)
1434 if err != nil {
1435 fmt.Fprintf(os.Stderr, "%s\n", err.Error())
1436 return
1437 }
1438
1439 defer inFile.Close()
1440
1441 // force unlimited cache size
1442 cache.maximum = math.MaxInt32
1443
1444 scanr := bufio.NewScanner(inFile)
1445
1446 addToCache := func(text string) {
1447
1448 citFields := make(map[string]string)
1449
1450 // stream tokens, collecting XML values in map
1451 StreamValues(text[:], "CITATION", func(tag, attr, content string) { citFields[tag] = content })
1452
1453 // identifying string for use in citation cache
1454 ident := citFields["TEXT"]
1455
1456 pmid := citFields["PMID"]
1457 note := citFields["NOTE"]
1458
1459 pm := ""
1460 if pmid != "" {
1461 pm = "<PMID>" + pmid + "</PMID>"
1462 }
1463 nt := ""
1464 if note != "" {
1465 nt = "<NOTE>" + note + "</NOTE>"
1466 }
1467
1468 suffix := pm + nt
1469
1470 // cache result (cached PMID + NOTE can be empty)
1471 cache.matchResultCache[ident] = suffix
1472 }
1473
1474 // loop through input lines
1475 for scanr.Scan() {
1476 line := scanr.Text()
1477 addToCache(line)
1478 }
1479 }
1480
1481 // CreateCitMatchers reads CITATION XML and returns matching PMIDs
1482 func CreateCitMatchers(inp <-chan XMLRecord, options []string, deStop, doStem bool, cache *CitCache, jtaMap map[string]string) <-chan XMLRecord {
1483
1484 if inp == nil {
1485 return nil
1486 }
1487
1488 out := make(chan XMLRecord, chanDepth)
1489 if out == nil {
1490 DisplayError("Unable to create citmatch channel")
1491 os.Exit(1)
1492 }
1493
1494 if cache == nil {
1495 cache = NewCitCache(0)
1496 }
1497
1498 // flags from command-line arguments
1499 strict := false
1500 remote := false
1501 verify := false
1502 local := true
1503 verbose := false
1504 debug := false
1505 slower := false
1506
1507 for _, rgs := range options {
1508 opts := strings.Split(rgs, ",")
1509 for _, opt := range opts {
1510 if opt == "" {
1511 continue
1512 }
1513 switch opt {
1514 case "strict":
1515 strict = true
1516 case "remote":
1517 remote = true
1518 case "verify":
1519 verify = true
1520 case "test":
1521 //skip verify and edirect tests
1522 local = false
1523 // citmatch only
1524 remote = true
1525 case "verbose":
1526 verbose = true
1527 case "debug":
1528 debug = true
1529 case "slow", "slower":
1530 slower = true
1531 default:
1532 DisplayError("Unrecognized -options choice '%s'", opt)
1533 os.Exit(1)
1534 }
1535 }
1536 }
1537
1538 // archiveBase needed by eutisl.fetchOneXMLRecord function
1539 archiveBase := ""
1540
1541 if local {
1542
1543 // obtain path from environment variable, check to make sure local archive is mounted
1544 archiveBase = GetLocalArchiveFolder("pubmed", "Archive", true)
1545
1546 if archiveBase == "" {
1547 DisplayError("Unable to get local archive path")
1548 os.Exit(1)
1549 }
1550
1551 // obtain path from environment variable, check to make sure local postings directory is mounted
1552 if GetLocalArchiveFolder("pubmed", "Postings", true) == "" {
1553 DisplayError("Unable to get local postings path")
1554 os.Exit(1)
1555 }
1556
1557 }
1558
1559 errataQuery := "comment on [PROP] OR erratum for [PROP] OR expression of concern for [PROP] OR reprint of [PROP] OR republished in [PROP] OR retracted and republished in [PROP] OR retraction in [PROP] OR update in [PROP]"
1560
1561 toExclude := ProcessQuery("pubmed", errataQuery, false, false, false, deStop)
1562
1563 isExcluded := make(map[string]bool)
1564 if isExcluded != nil {
1565 for _, item := range toExclude {
1566 idx := strconv.Itoa(int(item))
1567 isExcluded[idx] = true
1568 }
1569 }
1570
1571 // gbCitMatch reads partitioned XML from channel and looks up candidate PMIDs
1572 gbCitMatch := func(wg *sync.WaitGroup, inp <-chan XMLRecord, out chan<- XMLRecord) {
1573
1574 // report when this matcher has no more records to process
1575 defer wg.Done()
1576
1577 sortedWords := func(titl string) []string {
1578
1579 temp := make(map[string]bool)
1580
1581 titl = strings.ToLower(titl)
1582
1583 // break phrases into individual words
1584 words := strings.FieldsFunc(titl, func(c rune) bool {
1585 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
1586 })
1587
1588 for _, item := range words {
1589 // continuing if IsStopWord i or ii here prevented correct matching of PMIDs 4411932 and 4747603 (neurotoxins I and II)
1590 temp[item] = true
1591 }
1592
1593 var arry []string
1594
1595 for item := range temp {
1596 if temp[item] {
1597 arry = append(arry, item)
1598 }
1599 }
1600
1601 slices.Sort(arry)
1602
1603 return arry
1604 }
1605
1606 getTitle := func(uid int32) string {
1607
1608 if uid < 1 {
1609 return ""
1610 }
1611
1612 val := strconv.Itoa(int(uid))
1613
1614 var buf bytes.Buffer
1615 pma := fetchOneXMLRecord(val, archiveBase, "", ".xml", true, buf)
1616 pma = strings.TrimSpace(pma)
1617 if pma == "" {
1618 return ""
1619 }
1620
1621 refFields := make(map[string]string)
1622
1623 StreamValues(pma[:], "PubmedArticle", func(tag, attr, content string) { refFields[tag] = content })
1624
1625 titl := refFields["ArticleTitle"]
1626
1627 return titl
1628 }
1629
1630 uniqueWords := func(strs []string) []string {
1631
1632 rs := make([]string, 0, len(strs))
1633 mp := make(map[string]bool)
1634
1635 for _, val := range strs {
1636 _, ok := mp[val]
1637 if !ok {
1638 mp[val] = true
1639 rs = append(rs, val)
1640 }
1641 }
1642
1643 return rs
1644 }
1645
1646 intersectWords := func(a, b []string) int {
1647
1648 temp := make(map[string]bool)
1649 num := 0
1650
1651 for _, item := range a {
1652 temp[item] = true
1653 }
1654
1655 for _, item := range b {
1656 if temp[item] {
1657 num++
1658 }
1659 }
1660
1661 return num
1662 }
1663
1664 unionWords := func(a, b []string) int {
1665
1666 temp := make(map[string]bool)
1667 num := 0
1668
1669 for _, item := range a {
1670 if !temp[item] {
1671 num++
1672 }
1673 temp[item] = true
1674 }
1675
1676 for _, item := range b {
1677 if !temp[item] {
1678 num++
1679 }
1680 temp[item] = true
1681 }
1682
1683 return num
1684 }
1685
1686 // look for closest match to actual title among candidate PMIDs
1687 jaccard := func(titl string, ids []int32) int32 {
1688
1689 if len(ids) < 1 {
1690 return 0
1691 }
1692
1693 titl = NormalizeTitle(titl)
1694 titl = strings.ToLower(titl)
1695 titleWords := sortedWords(titl)
1696 titleWords = uniqueWords(titleWords)
1697
1698 bestScore := 0
1699 bestPMID := int32(0)
1700
1701 if debug {
1702 fmt.Fprintf(os.Stderr, " %s\n", titl)
1703 }
1704
1705 for _, uid := range ids {
1706 ttl := getTitle(uid)
1707 if ttl != "" {
1708 ttl = NormalizeTitle(ttl)
1709 ttl = strings.ToLower(ttl)
1710 ttlWords := sortedWords(ttl)
1711 ttlWords = uniqueWords(ttlWords)
1712
1713 intrs := intersectWords(titleWords, ttlWords)
1714 union := unionWords(titleWords, ttlWords)
1715 score := intrs * 100 / union
1716
1717 if debug {
1718 fmt.Fprintf(os.Stderr, "%8d %3d %s\n", uid, score, ttl)
1719 }
1720
1721 // highest score should prefer original paper over errata and corrigenda
1722 if score > bestScore {
1723 bestScore = score
1724 bestPMID = uid
1725 }
1726 }
1727 }
1728
1729 // require score of at least 60 to filter out false positives
1730 if bestScore < 60 {
1731 return 0
1732 }
1733
1734 return bestPMID
1735 }
1736
1737 intersectMatches := func(a, b []int32) []int32 {
1738
1739 temp := make(map[int32]bool)
1740 var res []int32
1741
1742 for _, item := range a {
1743 temp[item] = true
1744 }
1745
1746 for _, item := range b {
1747 if temp[item] {
1748 res = append(res, item)
1749 }
1750 }
1751
1752 return res
1753 }
1754
1755 excludeMatches := func(a, b []int32) []int32 {
1756
1757 temp := make(map[int32]bool)
1758 var res []int32
1759
1760 for _, item := range b {
1761 temp[item] = true
1762 }
1763
1764 for _, item := range a {
1765 if !temp[item] {
1766 res = append(res, item)
1767 }
1768 }
1769
1770 return res
1771 }
1772
1773 wordPairs := func(titl string) []string {
1774
1775 var arry []string
1776
1777 titl = strings.ToLower(titl)
1778
1779 // break phrases into individual words
1780 words := strings.FieldsFunc(titl, func(c rune) bool {
1781 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
1782 })
1783
1784 // word pairs (or isolated singletons) separated by stop words
1785 if len(words) > 0 {
1786 past := ""
1787 run := 0
1788 for _, item := range words {
1789 if IsStopWord(item) {
1790 if run == 1 && past != "" {
1791 arry = append(arry, past)
1792 }
1793 past = ""
1794 run = 0
1795 continue
1796 }
1797 if item == "" {
1798 past = ""
1799 continue
1800 }
1801 if past != "" {
1802 arry = append(arry, past+" "+item)
1803 }
1804 past = item
1805 run++
1806 }
1807 if run == 1 && past != "" {
1808 arry = append(arry, past)
1809 }
1810 }
1811
1812 return arry
1813 }
1814
1815 singleWords := func(titl string) []string {
1816
1817 var arry []string
1818
1819 titl = strings.ToLower(titl)
1820
1821 // break phrases into individual words
1822 words := strings.FieldsFunc(titl, func(c rune) bool {
1823 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
1824 })
1825
1826 for _, item := range words {
1827 if item == "" {
1828 continue
1829 }
1830 if IsStopWord(item) {
1831 continue
1832 }
1833 arry = append(arry, item)
1834 }
1835
1836 return arry
1837 }
1838
1839 /*
1840 wordRuns := func(titl string) []string {
1841
1842 var arry []string
1843
1844 titl = strings.ToLower(titl)
1845
1846 words := strings.FieldsFunc(titl, func(c rune) bool {
1847 return !unicode.IsLetter(c) && !unicode.IsDigit(c)
1848 })
1849
1850 // phrases (or isolated singletons) separated by stop words
1851 if len(words) > 1 {
1852 i := 0
1853 j := 0
1854 item := ""
1855 for j, item = range words {
1856 if IsStopWord(item) {
1857 if j > i {
1858 term := strings.Join(words[i:j], " ")
1859 arry = append(arry, term)
1860 }
1861 i = j + 1
1862 }
1863 }
1864 if j > i {
1865 term := strings.Join(words[i:j], " ")
1866 arry = append(arry, term)
1867 }
1868 }
1869
1870 return arry
1871 }
1872 */
1873
1874 searchTitleParts := func(terms []string, field string, min int) []int32 {
1875
1876 var candidates []int32
1877
1878 if len(terms) < 1 {
1879 return candidates
1880 }
1881
1882 // histogram of counts for PMIDs matching one or more word pair queries
1883 pmatch := make(map[int32]int)
1884
1885 for _, item := range terms {
1886 arry := ProcessQuery("pubmed", item+" ["+field+"]", false, false, false, deStop)
1887 for _, uid := range arry {
1888 val := pmatch[uid]
1889 val++
1890 pmatch[uid] = val
1891 }
1892 }
1893
1894 // find maximum number of adjacent overlapping word pair matches
1895 max := 0
1896 for _, vl := range pmatch {
1897 if vl > max {
1898 max = vl
1899 }
1900 }
1901
1902 // require at least 3 matching pairs or 4 matching words to avoid false positives
1903 if max < min {
1904 return candidates
1905 }
1906
1907 // collect up to 25 PMIDs with maximum adjacent overlapping word pair count
1908 num := 0
1909 for ky, vl := range pmatch {
1910 if vl == max {
1911 candidates = append(candidates, ky)
1912 num++
1913 if num >= 25 {
1914 break
1915 }
1916 }
1917 }
1918
1919 // histogram showing distribution of partial matches
1920 if debug {
1921 if num > 0 {
1922 top, mid, low := 0, 0, 0
1923 for _, vl := range pmatch {
1924 if vl == max {
1925 top++
1926 } else if vl == max-1 {
1927 mid++
1928 } else if vl == max-2 {
1929 low++
1930 }
1931 }
1932 sep := "matches: "
1933 if top > 0 {
1934 fmt.Fprintf(os.Stderr, "%s%d @ [%d]", sep, top, max)
1935 sep = ", "
1936 }
1937 if mid > 0 {
1938 fmt.Fprintf(os.Stderr, "%s%d @ [%d]", sep, mid, max-1)
1939 sep = ", "
1940 }
1941 if low > 0 {
1942 fmt.Fprintf(os.Stderr, "%s%d @ [%d]", sep, low, max-2)
1943 }
1944 fmt.Fprintf(os.Stderr, "\n")
1945 }
1946
1947 }
1948
1949 return candidates
1950 }
1951
1952 matchByTitle := func(titl string) ([]int32, string) {
1953
1954 var byTitle []int32
1955
1956 titl = NormalizeTitle(titl)
1957 titl = strings.ToLower(titl)
1958 if debug {
1959 fmt.Fprintf(os.Stderr, "title: %s\n", titl)
1960 }
1961
1962 if titl == "" {
1963 return byTitle, "missing title"
1964 }
1965
1966 // adjacent overlapping word pairs, plus single words between stop words or at ends
1967 pairs := wordPairs(titl)
1968 if len(pairs) < 1 {
1969 return byTitle, "title has no matching word pairs in search index"
1970 }
1971
1972 byTitle = searchTitleParts(pairs, "PAIR", 3)
1973 if len(byTitle) < 1 {
1974 if slower {
1975 words := singleWords(titl)
1976 if len(words) < 1 {
1977 return byTitle, "title has no matching words in search index"
1978 }
1979
1980 byTitle = searchTitleParts(words, "TITL", 4)
1981 }
1982 if len(byTitle) < 1 {
1983 return byTitle, "no candidates for matching title"
1984 }
1985 }
1986
1987 return byTitle, ""
1988 }
1989
1990 matchByAuthor := func(faut, laut, csrt string) ([]int32, string, string) {
1991
1992 var byAuthor []int32
1993
1994 faut = NormalizeAuthor(faut)
1995 faut = strings.ToLower(faut)
1996
1997 laut = NormalizeAuthor(laut)
1998 laut = strings.ToLower(laut)
1999
2000 if faut == "" && laut == "" && csrt == "" {
2001 return byAuthor, "empty authors", ""
2002 }
2003
2004 if faut == "" && laut == "" {
2005
2006 // no authors, just consortium
2007 csrt = NormalizeTitle(csrt)
2008 csrt = strings.ToLower(csrt)
2009
2010 query := csrt + " [CSRT]"
2011
2012 if debug {
2013 fmt.Fprintf(os.Stderr, "consortia: %s\n", query)
2014 }
2015
2016 // find PMIDs indexed under consortium
2017 byAuthor = ProcessQuery("pubmed", query, false, false, false, deStop)
2018 if len(byAuthor) < 1 {
2019 return byAuthor, "unrecognized consortium '" + csrt + "'", csrt
2020 }
2021
2022 return byAuthor, "", csrt
2023 }
2024
2025 // authors present, ignore any consortium
2026 query := faut
2027 if strings.Index(faut, " ") < 0 {
2028 // if just last name, space plus asterisk to wildcard on initials
2029 query += " "
2030 }
2031 // otherwise, if space between last name and initials, immediate asterisk for term truncation
2032 if strict {
2033 query += "* [FAUT]"
2034 } else {
2035 query += "* [AUTH]"
2036 }
2037 if faut != laut && laut != "" {
2038 query += " OR " + laut
2039 if strings.Index(laut, " ") < 0 {
2040 query += " "
2041 }
2042 if strict {
2043 query += "* [LAUT]"
2044 } else {
2045 query += "* [AUTH]"
2046 }
2047 }
2048 if debug {
2049 fmt.Fprintf(os.Stderr, "authors: %s\n", query)
2050 }
2051
2052 names := faut
2053 if faut != laut && laut != "" {
2054 names += " OR " + laut
2055 }
2056
2057 // find PMIDs indexed under first or last author, use wildcard after truncating to single initial
2058 byAuthor = ProcessQuery("pubmed", query, false, false, false, deStop)
2059 if len(byAuthor) < 1 {
2060 return byAuthor, "unrecognized author '" + names + "'", names
2061 }
2062
2063 return byAuthor, "", names
2064 }
2065
2066 matchByJournal := func(jour string) ([]int32, string, string) {
2067
2068 var byJournal []int32
2069
2070 jour = NormalizeJournal(jour)
2071 jour = strings.ToLower(jour)
2072
2073 if jour == "" {
2074 return byJournal, "empty journal", ""
2075 }
2076
2077 jta, ok := jtaMap[jour]
2078 if !ok || jta == "" {
2079 return byJournal, "unmappable journal '" + jour + "'", jour
2080 }
2081
2082 jour = NormalizeJournal(jta)
2083 jour = strings.ToLower(jour)
2084
2085 if strings.Index(jour, "|") >= 0 {
2086 return byJournal, "ambiguous journal '" + jour + "'", jour
2087 }
2088
2089 query := jour + " [JOUR]"
2090 if debug {
2091 fmt.Fprintf(os.Stderr, "journal: %s\n", query)
2092 }
2093
2094 byJournal = ProcessQuery("pubmed", query, false, false, false, deStop)
2095 if len(byJournal) < 1 {
2096 return byJournal, "unrecognized journal '" + jour + "'", jour
2097 }
2098
2099 return byJournal, "", jour
2100 }
2101
2102 matchByYear := func(year string) ([]int32, string, string) {
2103
2104 var byYear []int32
2105
2106 if year == "" {
2107 return byYear, "", ""
2108 }
2109
2110 yr, err := strconv.Atoi(year)
2111 if err != nil {
2112 return byYear, "unrecognized year '" + year + "'", year
2113 }
2114 lst := strconv.Itoa(yr - 1)
2115 nxt := strconv.Itoa(yr + 1)
2116 if strict {
2117 lst = strconv.Itoa(yr)
2118 }
2119
2120 query := lst + ":" + nxt + " [YEAR]"
2121 if debug {
2122 fmt.Fprintf(os.Stderr, "year: %s\n", query)
2123 }
2124
2125 span := lst + ":" + nxt
2126
2127 byYear = ProcessQuery("pubmed", query, false, false, false, deStop)
2128 if len(byYear) < 1 {
2129 return byYear, "unrecognized year range '" + span + "'", span
2130 }
2131
2132 return byYear, "", span
2133 }
2134
2135 // citFind returns PMID and optional message containing reason for failure
2136 citFind := func(citFields map[string]string) (int32, string) {
2137
2138 if citFields == nil {
2139 return 0, "map missing"
2140 }
2141
2142 note := ""
2143 between := ""
2144
2145 // initial candidates based on most matches to overlapping word pairs in title
2146
2147 titl := citFields["TITL"]
2148
2149 byTitle, reasonT := matchByTitle(titl)
2150 if reasonT != "" {
2151 return 0, reasonT
2152 }
2153
2154 // prepare postings subsets to filter candidates by author, journal, and year
2155
2156 faut := citFields["FAUT"]
2157 laut := citFields["LAUT"]
2158 csrt := citFields["CSRT"]
2159
2160 byAuthor, reasonA, labelA := matchByAuthor(faut, laut, csrt)
2161 if reasonA != "" {
2162 if strict {
2163 return 0, reasonA
2164 }
2165 note += between + reasonA
2166 between = ", "
2167 }
2168
2169 jour := citFields["JOUR"]
2170
2171 byJournal, reasonJ, labelJ := matchByJournal(jour)
2172 if reasonJ != "" {
2173 if strict {
2174 return 0, reasonJ
2175 }
2176 note += between + reasonJ
2177 between = ", "
2178 }
2179
2180 year := citFields["YEAR"]
2181
2182 byYear, reasonY, labelY := matchByYear(year)
2183 if reasonY != "" {
2184 if strict {
2185 return 0, reasonY
2186 }
2187 note += between + reasonY
2188 between = ", "
2189 }
2190
2191 // interesections
2192
2193 working := byTitle
2194
2195 // exclude erratum for, retraction in, etc.
2196 if len(working) > 0 {
2197 temp := excludeMatches(working, toExclude)
2198 if len(temp) > 0 {
2199 working = temp
2200 }
2201 }
2202
2203 // restrict by author name
2204 if len(byAuthor) > 0 {
2205 temp := intersectMatches(working, byAuthor)
2206 if len(temp) < 1 {
2207 if strict {
2208 return 0, "author does not match title"
2209 }
2210 note += between + "title does not match author '" + labelA + "'"
2211 return 0, note + ", exiting"
2212 }
2213 working = temp
2214 } else if strict {
2215 return 0, "no author match"
2216 }
2217
2218 // restrict by journal name, but ignore if no match
2219 if len(byJournal) > 0 {
2220 temp := intersectMatches(working, byJournal)
2221 if len(temp) < 1 {
2222 if strict {
2223 return 0, "journal does not match title"
2224 }
2225 note += between + "title does not match journal '" + labelJ + "'"
2226 between = ", "
2227 } else {
2228 working = temp
2229 }
2230 } else if strict {
2231 return 0, "no journal match"
2232 }
2233
2234 // restrict by year range, but ignore if no match
2235 if len(byYear) > 0 {
2236 temp := intersectMatches(working, byYear)
2237 if len(temp) < 1 {
2238 if strict {
2239 return 0, "year range does not match title"
2240 }
2241 note += between + "title does not match year range '" + labelY + "'"
2242 between = ", "
2243 } else {
2244 working = temp
2245 }
2246 } else if strict {
2247 return 0, "no year match"
2248 }
2249
2250 if len(working) < 1 {
2251 return 0, "match not found"
2252 }
2253
2254 // get best matching candidate
2255 pmid := jaccard(titl, working)
2256 if pmid != 0 {
2257 return pmid, note
2258 }
2259
2260 note += between + "jaccard failed"
2261 return pmid, note
2262 }
2263
2264 // collect citation fields, without sequence accession or reference number
2265 citBody := func(citFields map[string]string) string {
2266
2267 var arry []string
2268
2269 flds := []string{"FAUT", "LAUT", "CSRT", "ATHR", "TITL", "JOUR", "VOL", "ISS", "PAGE", "YEAR", "TEXT", "STAT", "ORIG"}
2270
2271 for _, fld := range flds {
2272 nxt, ok := citFields[fld]
2273 if ok && nxt != "" {
2274 arry = append(arry, "<"+fld+">"+nxt+"</"+fld+">")
2275 }
2276 }
2277
2278 return strings.Join(arry, "")
2279 }
2280
2281 citPrefix := func(citFields map[string]string) string {
2282
2283 var arry []string
2284
2285 flds := []string{"ACCN", "DIV", "REF"}
2286
2287 for _, fld := range flds {
2288 nxt, ok := citFields[fld]
2289 if ok && nxt != "" {
2290 arry = append(arry, "<"+fld+">"+nxt+"</"+fld+">")
2291 }
2292 }
2293
2294 return strings.Join(arry, "")
2295 }
2296
2297 pma2ref := func(pma string) map[string]string {
2298
2299 refFields := make(map[string]string)
2300
2301 pat := ParseRecord(pma[:], "PubmedArticle")
2302
2303 var athr []string
2304
2305 VisitNodes(pat, "AuthorList/Author", func(auth *XMLNode) {
2306
2307 lastname := ""
2308 initials := ""
2309
2310 VisitElements(auth, "LastName", "", func(str string) {
2311 lastname = str
2312 })
2313
2314 VisitElements(auth, "Initials", "", func(str string) {
2315 initials = str
2316 })
2317
2318 name := NormalizeAuthor(lastname + " " + initials)
2319 name = strings.ToLower(name)
2320
2321 athr = append(athr, name)
2322 })
2323
2324 ln := len(athr)
2325 if ln > 0 {
2326 refFields["FAUT"] = athr[0]
2327 refFields["LAUT"] = athr[ln-1]
2328 refFields["ATHR"] = strings.Join(athr, ", ")
2329 }
2330
2331 VisitElements(pat, "ArticleTitle", "", func(str string) {
2332 str = NormalizeTitle(str)
2333 refFields["TITL"] = strings.ToLower(str)
2334 })
2335
2336 VisitNodes(pat, "Article/Journal", func(jour *XMLNode) {
2337
2338 VisitElements(jour, "ISOAbbreviation", "", func(str string) {
2339 str = NormalizeJournal(str)
2340 refFields["JOUR"] = strings.ToLower(str)
2341 })
2342
2343 VisitElements(jour, "JournalIssue/Volume", "", func(str string) {
2344 refFields["VOL"] = strings.ToLower(str)
2345 })
2346
2347 VisitElements(jour, "JournalIssue/Issue", "", func(str string) {
2348 refFields["ISS"] = strings.ToLower(str)
2349 })
2350
2351 VisitElements(jour, "PubDate/Year", "", func(str string) {
2352 refFields["YEAR"] = strings.ToLower(str)
2353 })
2354 })
2355
2356 VisitElements(pat, "Pagination/MedlinePgn", "", func(str string) {
2357 str = NormalizePage(str)
2358 refFields["PAGE"] = strings.ToLower(str)
2359 })
2360
2361 return refFields
2362 }
2363
2364 checkCitedPMID := func(citFields, refFields map[string]string) bool {
2365
2366 compareFields := func(fld string, required, period bool, clean func(str string) string) bool {
2367
2368 if fld == "" {
2369 return false
2370 }
2371
2372 cit := citFields[fld]
2373 ref := refFields[fld]
2374
2375 if cit != "" && ref != "" {
2376 if clean != nil {
2377 cit = clean(cit)
2378 ref = clean(ref)
2379 }
2380
2381 cit = strings.ToLower(cit)
2382 ref = strings.ToLower(ref)
2383
2384 if period {
2385 cit = strings.TrimSuffix(cit, ".")
2386 ref = strings.TrimSuffix(ref, ".")
2387 }
2388
2389 if cit == ref {
2390 return true
2391 }
2392
2393 // fmt.Fprintf(os.Stderr, "ACCN %s, FLD %s mismatch -\n'%s'\n'%s'\n\n", citFields["ACCN"], fld, cit, ref)
2394
2395 // both items present but values not equal
2396 return false
2397 }
2398
2399 if required {
2400
2401 // fmt.Fprintf(os.Stderr, "ACCN %s, FLD %s mismatch -\n'%s'\n'%s'\n\n", citFields["ACCN"], fld, cit, ref)
2402
2403 // one or both items missing but required
2404 return false
2405 }
2406
2407 // both items missing but optional
2408 return true
2409 }
2410
2411 if citFields["FAUT"] != "" && citFields["LAUT"] != "" {
2412 // first author in citation must match first author in record,
2413 // OR last author in citation must match last author in record
2414 if !compareFields("FAUT", true, false, NormalizeAuthor) && !compareFields("LAUT", true, false, NormalizeAuthor) {
2415 return false
2416 }
2417 } else if citFields["CSRT"] != "" {
2418 // consortium in citation must match consortium in record
2419 if !compareFields("CSRT", true, true, NormalizeTitle) {
2420 return false
2421 }
2422 }
2423 if !compareFields("TITL", true, true, NormalizeTitle) {
2424 // if failure, check again without non-alphanumeric characters
2425 relaxTitle := func(str string) string {
2426
2427 if str == "" {
2428 return ""
2429 }
2430
2431 str = NormalizeTitle(str)
2432 str = strings.ToLower(str)
2433
2434 str = RelaxString(str)
2435 str = strings.Replace(str, " ", "", -1)
2436
2437 return str
2438 }
2439
2440 ctk := relaxTitle(citFields["TITL"])
2441 rfk := relaxTitle(refFields["TITL"])
2442
2443 // compare compressed alphanumeric keys
2444 if ctk != rfk {
2445 return false
2446 }
2447
2448 // compressed keys matched exactly, so continue with tests
2449 }
2450 if !compareFields("JOUR", true, false, NormalizeJournal) {
2451 return false
2452 }
2453 if !compareFields("VOL", false, false, nil) {
2454 return false
2455 }
2456 if !compareFields("ISS", false, false, nil) {
2457 return false
2458 }
2459 if !compareFields("PAGE", false, false, NormalizePage) {
2460 return false
2461 }
2462 if !compareFields("YEAR", true, false, nil) {
2463 // if year is present in citation, require an exact match to year in record
2464 return false
2465 }
2466
2467 return true
2468 }
2469
2470 re, _ := regexp.Compile(">[ \n\r\t]+<")
2471
2472 matchCit := func(text string) string {
2473
2474 citFields := make(map[string]string)
2475
2476 // stream tokens, collecting XML values in map
2477 StreamValues(text[:], "CITATION", func(tag, attr, content string) { citFields[tag] = content })
2478
2479 // identifying string for use in citation cache
2480 ident := citFields["TEXT"]
2481
2482 // citation fields
2483 body := citBody(citFields)
2484
2485 // current ACCN, DIV, and REF fields
2486 prefix := citPrefix(citFields)
2487
2488 attempts := 5
2489 keepChecking := true
2490
2491 for keepChecking && attempts > 0 {
2492 cache.mlock.Lock()
2493 // check if same citation is already in progress in another goroutine
2494 isInUse, _ := cache.inUse[ident]
2495 cache.mlock.Unlock()
2496
2497 if isInUse {
2498 time.Sleep(time.Second)
2499 attempts--
2500 } else {
2501 keepChecking = false
2502 }
2503 }
2504
2505 // check if same reference was processed recently
2506 cache.mlock.Lock()
2507 cachedText, ok := cache.matchResultCache[ident]
2508 cache.mlock.Unlock()
2509 if ok {
2510 // return cached result of previous lookup (cached PMID + NOTE can be empty)
2511 return "<CITATION>" + prefix + body + cachedText + "</CITATION>"
2512 }
2513
2514 // set inUse flag for this citation
2515 cache.mlock.Lock()
2516 cache.inUse[ident] = true
2517 cache.mlock.Unlock()
2518
2519 orig := citFields["ORIG"]
2520
2521 pmid := ""
2522 note := ""
2523
2524 if local {
2525
2526 // conditionally try to verify original PMID in citation
2527 if orig != "" && verify && IsAllDigits(orig) {
2528
2529 var buf bytes.Buffer
2530 pma := fetchOneXMLRecord(orig, archiveBase, "", ".xml", true, buf)
2531 pma = strings.TrimSpace(pma)
2532
2533 refFields := pma2ref(pma)
2534
2535 if checkCitedPMID(citFields, refFields) {
2536
2537 if isExcluded != nil && !isExcluded[orig] {
2538 pmid = orig
2539 note = "verified"
2540 } else {
2541 note = "excluded"
2542 }
2543 }
2544 }
2545
2546 // do citation lookup calculations
2547 if pmid == "" {
2548 pid, nte := citFind(citFields)
2549 if pid > 0 {
2550 pmid = strconv.Itoa(int(pid))
2551 if verbose {
2552 note = nte
2553 } else if note == "excluded" {
2554 if pmid == orig {
2555 note = "confirmed"
2556 } else {
2557 note = "replaced"
2558 }
2559 } else {
2560 note = "edirect"
2561 }
2562 }
2563 }
2564
2565 if debug {
2566 fmt.Fprintf(os.Stderr, "pmid %s, orig %s, reason %s\n", pmid, orig, note)
2567 }
2568 }
2569
2570 // conditionally try citmatch network service if local EDirect matcher failed
2571 if pmid == "" && remote {
2572
2573 jsn := cit2json(ident)
2574
2575 ok := false
2576 nte := ""
2577 ok, nte, pmid = json2pmid(jsn)
2578
2579 if !ok {
2580 // try a second time on server failure
2581 jsn = cit2json(ident)
2582 _, nte, pmid = json2pmid(jsn)
2583 }
2584
2585 if pmid != "" {
2586 if verbose {
2587 note = nte
2588 } else if note == "excluded" {
2589 if pmid == orig {
2590 note = "accepted"
2591 } else {
2592 note = "overridden"
2593 }
2594 } else {
2595 note = nte
2596 }
2597 }
2598 }
2599
2600 // non-verbose note is simple - verified, edirect, citmatch, overuse, failed, unmatched
2601 if !verbose && pmid == "" && note == "" {
2602 note = "unmatched"
2603 }
2604
2605 pm := ""
2606 if pmid != "" {
2607 pm = "<PMID>" + pmid + "</PMID>"
2608 }
2609 nt := ""
2610 if note != "" {
2611 nt = "<NOTE>" + note + "</NOTE>"
2612 }
2613
2614 suffix := pm + nt
2615
2616 res := "<CITATION>" + prefix + body + suffix + "</CITATION>"
2617
2618 if re != nil {
2619 text = re.ReplaceAllString(res, "><")
2620 }
2621
2622 cache.mlock.Lock()
2623 // clear inUse flag
2624 delete(cache.inUse, ident)
2625
2626 // cache result (cached PMID + NOTE can be empty)
2627 cache.matchResultCache[ident] = suffix
2628
2629 // limit cache to the most recent citation strings
2630 cache.matchRingList = append(cache.matchRingList, ident)
2631 if len(cache.matchRingList) > cache.maximum {
2632 // extract oldest entry from ring buffer
2633 oldest := cache.matchRingList[0]
2634 cache.matchRingList = cache.matchRingList[1:]
2635 // delete oldest entry from map
2636 delete(cache.matchResultCache, oldest)
2637 }
2638 cache.mlock.Unlock()
2639
2640 // return record with newly-matched PMID (or reason for failure)
2641 return res
2642 }
2643
2644 // read partitioned XML from producer channel
2645 for ext := range inp {
2646
2647 text := ext.Text
2648
2649 // rename original PMID
2650 text = strings.Replace(text, "<PMID>", "<ORIG>", -1)
2651 text = strings.Replace(text, "</PMID>", "</ORIG>", -1)
2652
2653 rsult := matchCit(text[:])
2654
2655 out <- XMLRecord{Index: ext.Index, Text: rsult}
2656 }
2657 }
2658
2659 var wg sync.WaitGroup
2660
2661 // launch multiple citmatch goroutines
2662 for range numServe {
2663 wg.Add(1)
2664 go gbCitMatch(&wg, inp, out)
2665 }
2666
2667 // launch separate anonymous goroutine to wait until all citation matchers are done
2668 go func() {
2669 wg.Wait()
2670 close(out)
2671 }()
2672
2673 return out
2674 }