Debian Codegraph @

extern/prep-taxoninfo.go

raw symbols SCIP
1 // prep-taxoninfo.go
2
3 // Public domain notice for all NCBI EDirect scripts is located at:
4 // https://www.ncbi.nlm.nih.gov/books/NBK179288/#chapter6.Public_Domain_Notice
5
6 package main
7
8 import (
9 "bufio"
10 "cmp"
11 "fmt"
12 "maps"
13 "os"
14 "path/filepath"
15 "slices"
16 "strconv"
17 "strings"
18 "unicode"
19 )
20
21 // copied from EDirect's eutils library
22
23 // Adding "replace eutils => ../eutils" to go.mod works for a ".go" program compiled
24 // with "go build", but not when called with "go run" as if it were a script, so these
25 // helpers for converting external data formats duplicate a few EDirect functions
26
27 var greekRunes = map[rune]string{
28 0x0190: "epsilon",
29 0x025B: "epsilon",
30 0x0391: "alpha",
31 0x0392: "beta",
32 0x0393: "gamma",
33 0x0394: "delta",
34 0x0395: "epsilon",
35 0x0396: "zeta",
36 0x0397: "eta",
37 0x0398: "theta",
38 0x0399: "iota",
39 0x039A: "kappa",
40 0x039B: "lambda",
41 0x039C: "mu",
42 0x039D: "nu",
43 0x039E: "xi",
44 0x039F: "omicron",
45 0x03A0: "pi",
46 0x03A1: "rho",
47 0x03A3: "sigma",
48 0x03A4: "tau",
49 0x03A5: "upsilon",
50 0x03A6: "phi",
51 0x03A7: "chi",
52 0x03A8: "psi",
53 0x03A9: "omega",
54 0x03B1: "alpha",
55 0x03B2: "beta",
56 0x03B3: "gamma",
57 0x03B4: "delta",
58 0x03B5: "epsilon",
59 0x03B6: "zeta",
60 0x03B7: "eta",
61 0x03B8: "theta",
62 0x03B9: "iota",
63 0x03BA: "kappa",
64 0x03BB: "lambda",
65 0x03BC: "mu",
66 0x03BD: "nu",
67 0x03BE: "xi",
68 0x03BF: "omicron",
69 0x03C0: "pi",
70 0x03C1: "rho",
71 0x03C2: "sigma",
72 0x03C3: "sigma",
73 0x03C4: "tau",
74 0x03C5: "upsilon",
75 0x03C6: "phi",
76 0x03C7: "chi",
77 0x03C8: "psi",
78 0x03C9: "omega",
79 0x03D0: "beta",
80 0x03D1: "theta",
81 0x03D5: "phi",
82 0x03D6: "pi",
83 0x03F0: "kappa",
84 0x03F1: "rho",
85 0x03F5: "epsilon",
86 0x1D5D: "beta",
87 0x1D66: "beta",
88 }
89
90 // rune table from data file
91 var asciiRunes map[rune]string
92
93 // parser character type lookup tables
94 var inBlank [256]bool
95
96 // reencodes < and > to &lt and &gt, and & to &amp
97 var rfix *strings.Replacer
98
99 // reencodes < and > to &lt and &gt, and & to &amp, and converts ' and " to space
100 var tfix *strings.Replacer
101
102 // ANSI escape codes for terminal color, highlight, and reverse
103 const (
104 RED = "\033[31m"
105 BLUE = "\033[34m"
106 BOLD = "\033[1m"
107 RVRS = "\033[7m"
108 INIT = "\033[0m"
109 LOUD = INIT + RED + BOLD
110 INVT = LOUD + RVRS
111 )
112
113 func displayError(format string, params ...any) {
114
115 str := fmt.Sprintf(format, params...)
116 fmt.Fprintf(os.Stderr, "\n%s ERROR: %s %s%s\n", INVT, LOUD, str, INIT)
117 }
118
119 func displayWarning(format string, params ...any) {
120
121 str := fmt.Sprintf(format, params...)
122 fmt.Fprintf(os.Stderr, "\n%s WARNING: %s %s%s\n", INVT, LOUD, str, INIT)
123 }
124
125 func isAllDigits(str string) bool {
126
127 for _, ch := range str {
128 if !unicode.IsDigit(ch) {
129 return false
130 }
131 }
132
133 return true
134 }
135
136 func compressRunsOfSpaces(str string) string {
137
138 whiteSpace := false
139 var buffer strings.Builder
140
141 for _, ch := range str {
142 if ch < 127 && inBlank[ch] {
143 if !whiteSpace {
144 buffer.WriteRune(' ')
145 }
146 whiteSpace = true
147 } else {
148 buffer.WriteRune(ch)
149 whiteSpace = false
150 }
151 }
152
153 return buffer.String()
154 }
155
156 func loadRuneTable(rt map[rune]string, dataPath, fileName string) bool {
157
158 loaded := false
159
160 fpath := filepath.Join(dataPath, fileName)
161 file, ferr := os.Open(fpath)
162
163 if file != nil && ferr == nil {
164 scanner := bufio.NewScanner(file)
165 for scanner.Scan() {
166
167 str := scanner.Text()
168 if str == "" {
169 continue
170 }
171 cols := strings.SplitN(str, "\t", 3)
172 if len(cols) < 2 {
173 continue
174 }
175 n, err := strconv.ParseUint(cols[0], 16, 32)
176 if err != nil {
177 continue
178 }
179
180 ch := rune(n)
181 st := cols[1]
182 rt[ch] = st
183
184 loaded = true
185 }
186 }
187 file.Close()
188
189 if !loaded {
190 displayWarning("Unable to load %s", fileName)
191 }
192
193 return loaded
194 }
195
196 func transformAccents(str string, spellGreek bool) string {
197
198 var arry []string
199
200 for _, ch := range str {
201
202 st := ""
203 ok := false
204
205 if ch < 128 {
206 // add printable 7-bit ASCII character directly
207 if ch > 31 {
208 arry = append(arry, string(ch))
209 }
210 continue
211 }
212
213 // leading and trailing spaces, if needed, are in the xxxRunes maps
214
215 if spellGreek {
216 // spells Greek letters (e.g., alpha, beta) for easier searching,
217 // handles glyph variants, treats Latin letter open E as Greek epsilon
218 st, ok = greekRunes[ch]
219 if ok {
220 arry = append(arry, st)
221 continue
222 }
223 }
224
225 // lookup remaining characters in asciiRunes table
226 st, ok = asciiRunes[ch]
227 if ok {
228 arry = append(arry, st)
229 }
230 }
231
232 str = strings.Join(arry, "")
233
234 return str
235 }
236
237 // initialize maps, tables, and variables
238 func init() {
239
240 asciiRunes = make(map[rune]string)
241
242 for i := range inBlank {
243 inBlank[i] = false
244 }
245 inBlank[' '] = true
246 inBlank['\t'] = true
247 inBlank['\n'] = true
248 inBlank['\r'] = true
249 inBlank['\f'] = true
250
251 rfix = strings.NewReplacer(
252 "<", "&lt;",
253 ">", "&gt;",
254 "&", "&amp;",
255 )
256
257 tfix = strings.NewReplacer(
258 "<", "&lt;",
259 ">", "&gt;",
260 "&", "&amp;",
261 "'", " ",
262 "\"", " ",
263 )
264 }
265
266 // TaxCodes holds nuclear, mitochondrial, plastid, and hydrogenosome genetic codes
267 type TaxCodes struct {
268 Nuclear string
269 Mitochondrial string
270 Plastid string
271 Hydrogenosome string
272 }
273
274 // TaxNames has several kinds of alternative names for a given node
275 type TaxNames struct {
276 Common []string
277 GenBank []string
278 Synonym []string
279 Authority []string
280 Equivalent []string
281 Includes []string
282 Acronym []string
283 Other []string
284 }
285
286 // TaxLevels has fields for well-established taxonomic ranks
287 type TaxLevels struct {
288 Species string
289 Genus string
290 Family string
291 Order string
292 Class string
293 Phylum string
294 Kingdom string
295 Realm string
296 Domain string // superkingdom
297 }
298
299 // TaxMods has fields for Org-ref.OrgName.OrgMod qualifiers
300 type TaxMods struct {
301 Clade string
302 Strain string
303 Subspecies string
304 Substrain string
305 Serovar string
306 Note string
307 }
308
309 // TaxType allows recording of type materials, etc. (see PMC4383940)
310 type TaxType struct {
311 Type string
312 Name string
313 }
314
315 // TaxonInfo is the master structure for archived, indexed taxonomy record
316 type TaxonInfo struct {
317 TaxID string
318 Scientific string
319 Rank string
320 Division string
321 Lineage string
322 ParentID string
323 Codes TaxCodes
324 Names TaxNames
325 Levels TaxLevels
326 Mods TaxMods
327 Specimens []TaxType
328 Children []string
329 }
330
331 // createTAXONINFO reads taxonomy files and create TaxonInfo records
332 func createTAXONINFO(verboseAncestors, verboseChildren bool) int {
333
334 recordCount := 0
335
336 // master map of taxon objects
337 taxonInfoMap := make(map[string]*TaxonInfo)
338
339 // GenBank division code lookup
340 divCodes := make(map[string]string)
341
342 // common function to handle reading of tab-delimited lines from taxonomy release files
343 processTableFile := func(fname string, expected int, proc func([]string)) {
344
345 if proc == nil {
346 return
347 }
348
349 inFile, err := os.Open(fname)
350 if err != nil {
351 displayError("Unable to open file %s - %s", fname, err.Error())
352 os.Exit(1)
353 }
354
355 defer inFile.Close()
356
357 scanr := bufio.NewScanner(inFile)
358
359 lineNum := 0
360
361 for scanr.Scan() {
362
363 lineNum++
364 line := scanr.Text()
365 if line == "" {
366 continue
367 }
368
369 cols := strings.Split(line, "\t")
370 if len(cols) != expected {
371 displayError("Found %d columns in line %d of file %s", len(cols), lineNum, fname)
372 continue
373 }
374
375 // send columns to indicated callback
376 proc(cols)
377 }
378 }
379
380 readDivisions := func(cols []string) {
381
382 divID, divCode, divName := cols[0], cols[2], cols[4]
383
384 if divID == "" || divCode == "" || divName == "" {
385 return
386 }
387
388 // looks up 3-letter division abbreviation from 1-digit number
389 divCodes[divID] = divCode
390 // overload to look up division name from 3-letter abbreviation
391 divCodes[divCode] = divName
392 }
393
394 readNameTable := func(cols []string) {
395
396 taxID, taxName, nameClass := cols[0], cols[2], cols[6]
397
398 if taxID == "" || taxName == "" || nameClass == "" {
399 return
400 }
401
402 tn, ok := taxonInfoMap[taxID]
403 if !ok {
404 // composite literal creates new node, initializes with taxonomy UID
405 tn = &TaxonInfo{TaxID: taxID}
406 // save new node in map
407 taxonInfoMap[taxID] = tn
408 }
409 if tn == nil {
410 return
411 }
412
413 if nameClass == "scientific name" {
414 // majority of lines are scientific name
415 tn.Scientific = taxName
416 return
417 }
418
419 // take address of composite structure in order to modify data in map
420 nam := &tn.Names
421
422 switch nameClass {
423 case "common name":
424 nam.Common = append(nam.Common, taxName)
425 case "genbank common name":
426 nam.GenBank = append(nam.GenBank, taxName)
427 case "synonym":
428 nam.Synonym = append(nam.Synonym, taxName)
429 case "equivalent name":
430 nam.Equivalent = append(nam.Equivalent, taxName)
431 case "includes":
432 nam.Includes = append(nam.Includes, taxName)
433 case "authority":
434 nam.Authority = append(nam.Authority, taxName)
435 case "acronym", "genbank acronym":
436 nam.Acronym = append(nam.Acronym, taxName)
437 default:
438 // "in-part" and "blast name"
439 nam.Other = append(nam.Other, taxName)
440 }
441 }
442
443 readFullLineage := func(cols []string) {
444
445 taxID, taxName, lineage := cols[0], cols[2], cols[4]
446
447 if taxID == "" || taxName == "" || lineage == "" {
448 return
449 }
450
451 tn, ok := taxonInfoMap[taxID]
452 if !ok {
453 return
454 }
455
456 sci := strings.ToLower(tn.Scientific)
457 sci = transformAccents(sci, true)
458 txn := strings.ToLower(taxName)
459 txn = transformAccents(txn, true)
460
461 if sci != txn {
462 displayError("FullTax Mismatch in TaxID %s\n%s - %s", tn.TaxID, sci, txn)
463 return
464 }
465
466 lineage = strings.TrimSuffix(lineage, "; ")
467 tn.Lineage = lineage
468 }
469
470 readRankedLineage := func(cols []string) {
471
472 taxID, taxName, species, genus, family, order, class, phylum, kingdom, realm, domain :=
473 cols[0], cols[2], cols[4], cols[6], cols[8], cols[10], cols[12], cols[14], cols[16], cols[18], cols[20]
474
475 if taxID == "" || taxName == "" {
476 return
477 }
478
479 tn, ok := taxonInfoMap[taxID]
480 if !ok {
481 return
482 }
483
484 sci := strings.ToLower(tn.Scientific)
485 sci = transformAccents(sci, true)
486 txn := strings.ToLower(taxName)
487 txn = transformAccents(txn, true)
488 if sci != txn {
489 displayError("RankTax Mismatch in TaxID %s\n%s - %s", tn.TaxID, sci, txn)
490 return
491 }
492
493 // species adjustments
494 if species == "" && genus != "" && strings.HasPrefix(tn.Scientific, genus+" ") {
495
496 // e.g., genus "Homo", scientific name "Homo sapiens", construct species - 9606
497 species = tn.Scientific
498 species = strings.TrimPrefix(species, genus+" ")
499
500 } else if species != "" && genus != "" && strings.HasPrefix(species, genus+" ") {
501
502 // e.g., species "Homo sapiens", genus "Homo", remove prefix from species - 63221, 741158
503 species = strings.TrimPrefix(species, genus+" ")
504 }
505 species = strings.TrimSuffix(species, " environmental sample")
506 species = strings.TrimSpace(species)
507
508 // take address to modify data in map
509 rnk := &tn.Levels
510
511 rnk.Species = species
512 rnk.Genus = genus
513 rnk.Family = family
514 rnk.Order = order
515 rnk.Class = class
516 rnk.Phylum = phylum
517 rnk.Kingdom = kingdom
518 rnk.Realm = realm
519 rnk.Domain = domain
520 }
521
522 readNodeTable := func(cols []string) {
523
524 taxID, parentID, rank, divID := cols[0], cols[2], cols[4], cols[8]
525 nucCode, mitoCode, plastCode, hydroCode := cols[12], cols[16], cols[26], cols[32]
526
527 if taxID == "" {
528 return
529 }
530
531 tn, ok := taxonInfoMap[taxID]
532 if !ok {
533 return
534 }
535
536 tn.ParentID = parentID
537
538 tn.Rank = rank
539
540 pn, ok := taxonInfoMap[parentID]
541 if ok {
542 pn.Children = append(pn.Children, taxID)
543 }
544
545 // division code 0 is Bacteria, only skip on empty string
546 if divID != "" {
547 code, ok := divCodes[divID]
548 if ok {
549 tn.Division = code
550 }
551 }
552
553 // normalize 0 to empty string for genetic codes
554 if nucCode == "0" {
555 nucCode = ""
556 }
557 if mitoCode == "0" {
558 mitoCode = ""
559 }
560 if plastCode == "0" {
561 plastCode = ""
562 }
563 if hydroCode == "0" {
564 hydroCode = ""
565 }
566
567 // take address to modify data in map
568 gcs := &tn.Codes
569
570 gcs.Nuclear = nucCode
571 gcs.Mitochondrial = mitoCode
572 gcs.Plastid = plastCode
573 gcs.Hydrogenosome = hydroCode
574
575 // take address to modify data in map
576 rnk := &tn.Levels
577
578 // fill in level of current rank for [TREE] construction
579 switch tn.Rank {
580 case "species":
581 if rnk.Species == "" {
582 rnk.Species = tn.Scientific
583 }
584 case "genus":
585 if rnk.Genus == "" {
586 rnk.Genus = tn.Scientific
587 }
588 case "family":
589 if rnk.Family == "" {
590 rnk.Family = tn.Scientific
591 }
592 case "order":
593 if rnk.Order == "" {
594 rnk.Order = tn.Scientific
595 }
596 case "class":
597 if rnk.Class == "" {
598 rnk.Class = tn.Scientific
599 }
600 case "phylum":
601 if rnk.Phylum == "" {
602 rnk.Phylum = tn.Scientific
603 }
604 case "kingdom":
605 if rnk.Kingdom == "" {
606 rnk.Kingdom = tn.Scientific
607 }
608 case "realm":
609 if rnk.Realm == "" {
610 rnk.Realm = tn.Scientific
611 }
612 case "domain":
613 if rnk.Domain == "" {
614 rnk.Domain = tn.Scientific
615 }
616 }
617
618 trimFlanks := func(str, pfx string) string {
619
620 /*
621 if strings.HasPrefix(str, "'") && strings.HasSuffix(str, "'") {
622 str = strings.TrimPrefix(str, "'")
623 str = strings.TrimSuffix(str, "'")
624 }
625 if strings.HasPrefix(str, "(") && strings.HasSuffix(str, ")") {
626 str = strings.TrimPrefix(str, "(")
627 str = strings.TrimSuffix(str, ")")
628 }
629 */
630 if pfx != "" && strings.HasPrefix(str, pfx) {
631 str = strings.TrimPrefix(str, pfx)
632 }
633 str = strings.TrimSpace(str)
634
635 return str
636 }
637
638 mds := &tn.Mods
639
640 // subspecies construction
641 if tn.Rank == "subspecies" && rnk.Genus != "" && rnk.Species != "" {
642
643 // e.g., scientific name "Homo sapiens neanderthalensis", genus "Homo", species "sapiens" - 63221
644 subspecies := strings.TrimPrefix(tn.Scientific, rnk.Genus+" ")
645 subspecies = strings.TrimPrefix(subspecies, rnk.Species+" ")
646 subspecies = strings.TrimPrefix(subspecies, "subsp. ")
647 subspecies = strings.TrimSpace(subspecies)
648
649 mds.Subspecies = trimFlanks(subspecies, "subspecies ")
650 }
651
652 // parse additional modifiers, e.g.,
653 // <Scientific>Prochlorococcus marinus subsp. pastoris str. NATL2 substr. M98C2B</Scientific> - 170609
654 // <Scientific>Salmonella enterica subsp. enterica serovar Typhi str. E98-2068</Scientific> - 496068
655
656 // tags are flanked by spaces to ensure correct matches
657 ptrns := []string{" clade ", " serovar ", " sp. ", " str. ", " strain ", " subsp. ", " substr. "}
658
659 var hits []int
660
661 modname := tn.Scientific
662 modname = strings.Replace(modname, "'", " ", -1)
663 modname = strings.Replace(modname, "(", " ", -1)
664 modname = strings.Replace(modname, ")", " ", -1)
665 if rnk.Genus != "" && rnk.Species != "" {
666 modname = strings.TrimPrefix(modname, rnk.Genus+" ")
667 modname = strings.TrimPrefix(modname, rnk.Species+" ")
668 }
669
670 // record location of specific qualifier tags
671 for _, md := range ptrns {
672 pos := strings.Index(modname, md)
673 if pos < 0 {
674 continue
675 }
676 hits = append(hits, pos)
677 }
678
679 // sort by position in scientific name string
680 slices.Sort(hits)
681
682 var clauses []string
683
684 // partition string into clauses
685 lst := 0
686 for _, pos := range hits {
687 cls := modname[lst:pos]
688 cls = strings.TrimSpace(cls)
689 if cls != "" {
690 clauses = append(clauses, cls)
691 }
692 lst = pos
693 }
694 // add clause after last matched position
695 cls := modname[lst:]
696 cls = strings.TrimSpace(cls)
697 if cls != "" {
698 clauses = append(clauses, cls)
699 }
700
701 clade, serovar, strain, subspecies, substrain, note := "", "", "", "", "", ""
702
703 // set specific modifiers based on qualifier tag
704 for _, cls := range clauses {
705
706 lft, rgt, found := strings.Cut(cls, " ")
707 if !found {
708 continue
709 }
710 rgt = strings.TrimSpace(rgt)
711 if rgt == "" {
712 continue
713 }
714
715 switch lft {
716 case "clade":
717 clade = rgt
718 case "serovar":
719 serovar = rgt
720 case "str.", "strain":
721 strain = rgt
722 case "subsp.":
723 subspecies = rgt
724 case "substr.":
725 substrain = rgt
726 case "sp.":
727 // absorb
728 default:
729 note = rgt
730 }
731 }
732
733 subspecies = strings.TrimPrefix(subspecies, "subsp ")
734 subspecies = strings.TrimPrefix(subspecies, "subs ")
735
736 if mds.Clade == "" {
737 mds.Clade = trimFlanks(clade, "clade ")
738 }
739 if mds.Subspecies == "" {
740 mds.Subspecies = trimFlanks(subspecies, "subspecies ")
741 }
742 if mds.Serovar == "" {
743 mds.Serovar = trimFlanks(serovar, "serovar ")
744 }
745 if mds.Strain == "" {
746 mds.Strain = trimFlanks(strain, "strain ")
747 }
748 if mds.Substrain == "" {
749 mds.Substrain = trimFlanks(substrain, "substrain ")
750 }
751
752 // strain construction
753 if tn.Rank == "strain" && mds.Strain == "" && rnk.Genus != "" && rnk.Species != "" {
754
755 // e.g., scientific name "Escherichia coli K-12", genus "Escherichia", species "coli" - 83333
756 strain := strings.TrimPrefix(modname, "str. ")
757 strain = strings.TrimSpace(strain)
758
759 mds.Strain = trimFlanks(strain, "strain ")
760 }
761
762 if mds.Note == "" {
763 mds.Note = trimFlanks(note, "")
764 }
765 }
766
767 readTypeMaterial := func(cols []string) {
768
769 taxID, taxName, typ, ident := cols[0], cols[2], cols[4], cols[6]
770
771 if taxID == "" || taxName == "" {
772 return
773 }
774
775 tn, ok := taxonInfoMap[taxID]
776 if !ok {
777 return
778 }
779
780 mat := TaxType{Type: typ, Name: ident}
781 tn.Specimens = append(tn.Specimens, mat)
782 }
783
784 uniqueStringArray := func(strs []string) []string {
785
786 rs := make([]string, 0, len(strs))
787 mp := make(map[string]bool)
788
789 for _, val := range strs {
790 // store lower-case version in map
791 lc := strings.ToLower(val)
792 _, ok := mp[lc]
793 if !ok {
794 mp[lc] = true
795 rs = append(rs, val)
796 }
797 }
798
799 return rs
800 }
801
802 // main body of function
803
804 // perform taxonomy file processing steps
805 processTableFile("division.dmp", 8, readDivisions)
806 processTableFile("names.dmp", 8, readNameTable)
807 processTableFile("fullnamelineage.dmp", 6, readFullLineage)
808 processTableFile("rankedlineage.dmp", 22, readRankedLineage)
809 processTableFile("nodes.dmp", 36, readNodeTable)
810 processTableFile("typematerial.dmp", 8, readTypeMaterial)
811
812 keys := slices.SortedFunc(maps.Keys(taxonInfoMap),
813 func(i, j string) int {
814 if isAllDigits(i) && isAllDigits(j) {
815 // numeric sort on strings checks lengths first
816 lni, lnj := len(i), len(j)
817 // shorter string is numerically lower, assuming no leading zeros
818 if lni < lnj {
819 return -1
820 }
821 if lni > lnj {
822 return 1
823 }
824 // same length allows comparison of numeric values without
825 // needing expensive string-to-integer conversion
826 }
827
828 // same length or non-numeric, can now do string comparison on contents
829 return cmp.Compare(i, j)
830 })
831
832 // buffer writes to stdout in chunks for efficiency
833 var buffer strings.Builder
834 count := 0
835 okay := false
836
837 wrtr := bufio.NewWriter(os.Stdout)
838
839 // variables to control printing of top-level set tags flanking all records
840 printSetHead := true
841 printSetTail := false
842
843 // variables to control printing of section tags flanking various content objects
844 head := ""
845 spaces := " "
846 fst := true
847
848 printHead := func(name, tag, val string) {
849
850 head = " <" + name
851 if tag != "" && val != "" {
852 head += " " + tag + "=\"" + val + "\""
853 }
854 head += ">\n"
855 // extra indentation of components
856 spaces = " "
857 fst = true
858 }
859
860 printTail := func(name string) {
861
862 if !fst {
863 // print closing section tag
864 tail := " </" + name + ">\n"
865 buffer.WriteString(tail)
866 }
867 head = ""
868 // restore indentation
869 spaces = " "
870 }
871
872 // use of attributes is not unreasonable for showing information about ancestor IDs, e.g.,
873 // <AnID name="Primates" rank="order">9443</AnID>
874
875 printWithAttribs := func(name, tag1, val1, tag2, val2, value string) {
876
877 if value != "" {
878
879 if strings.ContainsAny(value, "<>&") {
880 // reencodes <, >, and & to avoid breaking XML - 2137958, 2590565
881 value = rfix.Replace(value)
882 }
883
884 if val1 != "" && strings.ContainsAny(val1, "<>&'\"") {
885 // reencodes <, >, and &, and converts ' and " to space, to avoid breaking XML attributes
886 val1 = tfix.Replace(val1)
887 // then remove excess spaces
888 val1 = compressRunsOfSpaces(val1)
889 val1 = strings.TrimSpace(val1)
890 }
891 if val2 != "" && strings.ContainsAny(val2, "<>&'\"") {
892 val1 = tfix.Replace(val2)
893 val2 = compressRunsOfSpaces(val2)
894 val2 = strings.TrimSpace(val2)
895 }
896
897 if fst {
898 // print opening section tag
899 buffer.WriteString(head)
900 fst = false
901 }
902
903 // indent appropriate number of spaces
904 buffer.WriteString(spaces)
905
906 buffer.WriteString("<")
907 buffer.WriteString(name)
908 // print up to two optional attributes
909 if tag1 != "" && val1 != "" {
910 buffer.WriteString(" ")
911 buffer.WriteString(tag1)
912 buffer.WriteString("=\"")
913 buffer.WriteString(val1)
914 buffer.WriteString("\"")
915 }
916 if tag2 != "" && val2 != "" {
917 buffer.WriteString(" ")
918 buffer.WriteString(tag2)
919 buffer.WriteString("=\"")
920 buffer.WriteString(val2)
921 buffer.WriteString("\"")
922 }
923 buffer.WriteString(">")
924
925 buffer.WriteString(value)
926
927 buffer.WriteString("</")
928 buffer.WriteString(name)
929 buffer.WriteString(">\n")
930 }
931 }
932
933 printOne := func(name, value string) {
934
935 printWithAttribs(name, "", "", "", "", value)
936 }
937
938 printMany := func(name string, values []string) {
939
940 values = uniqueStringArray(values)
941 for _, str := range values {
942 printOne(name, str)
943 }
944 }
945
946 // supports searching the taxonomy hierarchy index term list using wildcard truncation on a
947 // lineage composed of the principal taxonomic ranks, e.g.,
948 // phrase-search -db taxonomy -query "Eukaryota Metazoa Chordata Mammalia Primates * [TREE]"
949
950 printTree := func(values []string) {
951
952 var arry []string
953
954 for _, str := range values {
955 if str != "" {
956 arry = append(arry, str)
957 }
958 }
959 tree := strings.Join(arry, "_")
960 if tree != "" {
961 printOne("Tree", tree)
962 }
963 }
964
965 // taxoninfo.xml output can be piped to xtract for analysis or record selection, e.g.,
966 // xtract -pattern TaxonInfo -select Genus -equals Homo -and Species -equals sapiens
967 // xtract -pattern TaxonInfo -select TaxID -equals 9606 -or TaxID -equals 63221
968
969 for _, key := range keys {
970
971 if printSetHead {
972 // print opening set tag before first record
973 buffer.WriteString("<TaxonInfoSet>\n")
974 printSetHead = false
975 printSetTail = true
976 }
977
978 // ensure indentation controls are reset
979 head = ""
980 spaces = " "
981 fst = true
982
983 buffer.WriteString("<TaxonInfo>\n")
984
985 tn := taxonInfoMap[key]
986
987 gcs := tn.Codes
988 nam := &tn.Names
989 rnk := tn.Levels
990 mds := tn.Mods
991
992 printOne("TaxID", tn.TaxID)
993 printOne("Rank", tn.Rank)
994 printOne("Scientific", tn.Scientific)
995
996 if rnk.Genus != "" && rnk.Species != "" {
997 if tn.Division == "VRL" && strings.Index(rnk.Species, " ") > 0 {
998 printOne("Binomial", rnk.Species)
999 } else {
1000 printOne("Binomial", rnk.Genus+" "+rnk.Species)
1001 }
1002 }
1003
1004 fullDiv, ok := divCodes[tn.Division]
1005 if ok {
1006 printWithAttribs("Division", "code", tn.Division, "", "", fullDiv)
1007 } else {
1008 printOne("Division", tn.Division)
1009 }
1010
1011 printOne("Lineage", tn.Lineage)
1012
1013 if rnk.Domain != "" {
1014 printTree([]string{
1015 rnk.Domain, rnk.Realm, rnk.Kingdom, rnk.Phylum, rnk.Class, rnk.Order, rnk.Family, rnk.Genus, rnk.Species,
1016 })
1017 }
1018
1019 if tn.TaxID != "1" {
1020 pID := tn.ParentID
1021 pn := taxonInfoMap[pID]
1022 if verboseAncestors {
1023 printWithAttribs("ParentID", "name", pn.Scientific, "", "", pID)
1024 } else {
1025 printOne("ParentID", pID)
1026 }
1027 }
1028
1029 printHead("Codes", "", "")
1030 printOne("Nuclear", gcs.Nuclear)
1031 printOne("Mitochondrial", gcs.Mitochondrial)
1032 printOne("Plastid", gcs.Plastid)
1033 printOne("Hydrogenosome", gcs.Hydrogenosome)
1034 printTail("Codes")
1035
1036 printHead("Names", "", "")
1037 printMany("Common", nam.Common)
1038 printMany("GenBank", nam.GenBank)
1039 printMany("Synonym", nam.Synonym)
1040 printMany("Equivalent", nam.Equivalent)
1041 printMany("Includes", nam.Includes)
1042 printMany("Authority", nam.Authority)
1043 printMany("Acronym", nam.Acronym)
1044 printMany("Other", nam.Other)
1045 printTail("Names")
1046
1047 printHead("Levels", "", "")
1048 printOne("Species", rnk.Species)
1049 printOne("Genus", rnk.Genus)
1050 printOne("Family", rnk.Family)
1051 printOne("Order", rnk.Order)
1052 printOne("Class", rnk.Class)
1053 printOne("Phylum", rnk.Phylum)
1054 printOne("Kingdom", rnk.Kingdom)
1055 printOne("Realm", rnk.Realm)
1056 printOne("Domain", rnk.Domain)
1057 printTail("Levels")
1058
1059 printHead("Modifiers", "", "")
1060 printOne("Subspecies", mds.Subspecies)
1061 printOne("Serovar", mds.Serovar)
1062 printOne("Strain", mds.Strain)
1063 printOne("Substrain", mds.Substrain)
1064 printOne("Clade", mds.Clade)
1065 printOne("Note", mds.Note)
1066 printTail("Modifiers")
1067
1068 if len(tn.Specimens) > 0 {
1069 // length of local slice is cached, no overhead to call again
1070 printHead("Specimens", "count", strconv.Itoa(len(tn.Specimens)))
1071 prev := ""
1072 for _, mat := range tn.Specimens {
1073 lc := strings.ToLower(mat.Name)
1074 if lc == prev {
1075 continue
1076 }
1077
1078 printWithAttribs("SpID", "type", mat.Type, "", "", mat.Name)
1079
1080 prev = lc
1081 }
1082 printTail("Specimens")
1083 }
1084
1085 if tn.TaxID != "1" {
1086 printHead("Ancestors", "", "")
1087 pn := tn
1088 for {
1089 pID := pn.ParentID
1090 pn = taxonInfoMap[pID]
1091 if verboseAncestors {
1092 printWithAttribs("AnID", "name", pn.Scientific, "rank", pn.Rank, pID)
1093 } else {
1094 printOne("AnID", pID)
1095 }
1096 if pID == "1" {
1097 break
1098 }
1099 }
1100 printTail("Ancestors")
1101 }
1102
1103 if len(tn.Children) > 0 {
1104 printHead("Children", "count", strconv.Itoa(len(tn.Children)))
1105 if verboseChildren {
1106 children := uniqueStringArray(tn.Children)
1107 for _, str := range children {
1108 cn := taxonInfoMap[str]
1109 printWithAttribs("ChID", "name", cn.Scientific, "rank", cn.Rank, cn.TaxID)
1110 }
1111 } else {
1112 printMany("ChID", tn.Children)
1113 }
1114 printTail("Children")
1115 }
1116
1117 buffer.WriteString("</TaxonInfo>\n")
1118
1119 recordCount++
1120 count++
1121
1122 if count >= 1000 {
1123 count = 0
1124 txt := buffer.String()
1125 if txt != "" {
1126 // print current buffer
1127 wrtr.WriteString(txt[:])
1128 }
1129 buffer.Reset()
1130 }
1131
1132 okay = true
1133 }
1134
1135 if okay {
1136 if printSetTail {
1137 // print closing set tag after last record
1138 buffer.WriteString("</TaxonInfoSet>\n")
1139 }
1140 txt := buffer.String()
1141 if txt != "" {
1142 // print final buffer
1143 wrtr.WriteString(txt[:])
1144 }
1145 }
1146 buffer.Reset()
1147
1148 wrtr.Flush()
1149
1150 return recordCount
1151 }
1152
1153 func main() {
1154
1155 // skip past executable name
1156 args := os.Args[1:]
1157
1158 if len(args) < 1 {
1159 displayError("Insufficient arguments for -taxon")
1160 os.Exit(1)
1161 }
1162
1163 // path to Unicode converters cannot be derived from program path, since
1164 // using "go run" compiles a temporary executable in an unrelated area
1165 dataPath := args[0]
1166
1167 // bulk of Unicode to ASCII mapping data is in a large external file
1168 loadRuneTable(asciiRunes, dataPath, "unicode-ascii.txt")
1169
1170 createTAXONINFO(true, true)
1171 }