Debian Codegraph @

eutils/gbff.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: gbff.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "bufio"
35 "html"
36 "io"
37 "os"
38 "strings"
39 "sync"
40 "unicode"
41 )
42
43 // GenBankConverter reads flatfiles and sends INSDSeq XML records down a channel
44 func GenBankConverter(inp io.Reader) <-chan string {
45
46 if inp == nil {
47 return nil
48 }
49
50 out := make(chan string, chanDepth)
51 if out == nil {
52 DisplayError("Unable to create GenBank converter channel")
53 os.Exit(1)
54 }
55
56 const twelvespaces = " "
57 const twentyonespaces = " "
58
59 convertGenBank := func(inp io.Reader, out chan<- string) {
60
61 // close channel when all records have been sent
62 defer close(out)
63
64 var rec strings.Builder
65 var alt strings.Builder
66 var con strings.Builder
67 var seq strings.Builder
68
69 scanr := bufio.NewScanner(inp)
70
71 row := 0
72
73 nextLine := func() string {
74
75 for scanr.Scan() {
76 line := scanr.Text()
77 if line == "" {
78 continue
79 }
80
81 // https://stackoverflow.com/questions/58994146/how-to-remove-non-printable-characters
82 line = strings.Map(func(r rune) rune {
83 if unicode.IsPrint(r) {
84 return r
85 }
86 return -1
87 }, line)
88
89 return line
90 }
91 return ""
92
93 }
94
95 for {
96
97 rec.Reset()
98
99 // read first line of next record
100 line := nextLine()
101 if line == "" {
102 break
103 }
104
105 row++
106
107 for {
108 if line == "" {
109 break
110 }
111 if !strings.HasPrefix(line, "LOCUS") {
112 // skip release file header information
113 line = nextLine()
114 row++
115 continue
116 }
117 break
118 }
119
120 readContinuationLines := func(str string) string {
121
122 for {
123 // read next line
124 line = nextLine()
125 row++
126 if !strings.HasPrefix(line, twelvespaces) {
127 // if not continuation line, break out of loop
128 break
129 }
130 // append subsequent line and continue with loop
131 txt := strings.TrimPrefix(line, twelvespaces)
132 str += " " + txt
133 }
134
135 str = CompressRunsOfSpaces(str)
136 str = strings.TrimSpace(str)
137
138 return str
139 }
140
141 writeOneElement := func(spaces, tag, value string) {
142
143 rec.WriteString(spaces)
144 rec.WriteString("<")
145 rec.WriteString(tag)
146 rec.WriteString(">")
147 value = html.EscapeString(value)
148 rec.WriteString(value)
149 rec.WriteString("</")
150 rec.WriteString(tag)
151 rec.WriteString(">\n")
152 }
153
154 // each section will exit with the next line ready to process
155
156 if strings.HasPrefix(line, "LOCUS") {
157
158 // start of record
159 rec.WriteString(" <INSDSeq>\n")
160
161 // do not break if given artificial multi-line LOCUS
162 str := readContinuationLines(line)
163
164 cols := strings.Fields(str)
165 ln := len(cols)
166 if ln == 8 {
167 moleculetype := cols[4]
168 strandedness := ""
169 if strings.HasPrefix(moleculetype, "ds-") {
170 moleculetype = strings.TrimPrefix(moleculetype, "ds-")
171 strandedness = "double"
172 } else if strings.HasPrefix(moleculetype, "ss-") {
173 moleculetype = strings.TrimPrefix(moleculetype, "ss-")
174 strandedness = "single"
175 } else if strings.HasPrefix(moleculetype, "ms-") {
176 moleculetype = strings.TrimPrefix(moleculetype, "ms-")
177 strandedness = "mixed"
178 } else if strings.HasSuffix(moleculetype, "DNA") {
179 strandedness = "double"
180 } else if strings.HasSuffix(moleculetype, "RNA") {
181 strandedness = "single"
182 }
183
184 writeOneElement(" ", "INSDSeq_locus", cols[1])
185 writeOneElement(" ", "INSDSeq_length", cols[2])
186
187 if strandedness != "" {
188 writeOneElement(" ", "INSDSeq_strandedness", strandedness)
189 }
190
191 writeOneElement(" ", "INSDSeq_moltype", moleculetype)
192 writeOneElement(" ", "INSDSeq_topology", cols[5])
193 writeOneElement(" ", "INSDSeq_division", cols[6])
194 writeOneElement(" ", "INSDSeq_update-date", cols[7])
195
196 } else if ln == 7 {
197
198 writeOneElement(" ", "INSDSeq_locus", cols[1])
199 writeOneElement(" ", "INSDSeq_length", cols[2])
200 writeOneElement(" ", "INSDSeq_moltype", "AA")
201 writeOneElement(" ", "INSDSeq_topology", cols[4])
202 writeOneElement(" ", "INSDSeq_division", cols[5])
203 writeOneElement(" ", "INSDSeq_update-date", cols[6])
204
205 } else {
206 DisplayWarning("%s", str)
207 }
208
209 // read next line and continue - handled by readContinuationLines above
210 // line = nextLine()
211 // row++
212 }
213
214 if strings.HasPrefix(line, "DEFINITION") {
215
216 txt := strings.TrimPrefix(line, "DEFINITION")
217 def := readContinuationLines(txt)
218 def = strings.TrimSuffix(def, ".")
219
220 writeOneElement(" ", "INSDSeq_definition", def)
221 }
222
223 var secondaries []string
224
225 if strings.HasPrefix(line, "ACCESSION") {
226
227 txt := strings.TrimPrefix(line, "ACCESSION")
228 str := readContinuationLines(txt)
229 accessions := strings.Fields(str)
230 ln := len(accessions)
231 if ln > 1 {
232
233 writeOneElement(" ", "INSDSeq_primary-accession", accessions[0])
234
235 // skip past primary accession, collect secondaries
236 secondaries = accessions[1:]
237
238 } else if ln == 1 {
239
240 writeOneElement(" ", "INSDSeq_primary-accession", accessions[0])
241
242 } else {
243 DisplayError("ACCESSION %s", str)
244 }
245 }
246
247 accnver := ""
248 gi := ""
249
250 if strings.HasPrefix(line, "VERSION") {
251
252 cols := strings.Fields(line)
253 if len(cols) == 2 {
254
255 accnver = cols[1]
256 writeOneElement(" ", "INSDSeq_accession-version", accnver)
257
258 } else if len(cols) == 3 {
259
260 accnver = cols[1]
261 writeOneElement(" ", "INSDSeq_accession-version", accnver)
262
263 // collect gi for other-seqids
264 if strings.HasPrefix(cols[2], "GI:") {
265 gi = strings.TrimPrefix(cols[2], "GI:")
266 }
267
268 } else {
269 DisplayError("%s", line)
270 }
271
272 // read next line and continue
273 line = nextLine()
274 row++
275 }
276
277 if gi != "" {
278
279 rec.WriteString(" <INSDSeq_other-seqids>\n")
280 writeOneElement(" ", "INSDSeqid", "gi|"+gi)
281 rec.WriteString(" </INSDSeq_other-seqids>\n")
282 }
283
284 if len(secondaries) > 0 {
285
286 rec.WriteString(" <INSDSeq_secondary-accessions>\n")
287
288 for _, secndry := range secondaries {
289
290 if strings.HasPrefix(secndry, "REGION") {
291 break
292 }
293 writeOneElement(" ", "INSDSecondary-accn", secndry)
294 }
295
296 rec.WriteString(" </INSDSeq_secondary-accessions>\n")
297
298 // reset secondaries slice
299 secondaries = nil
300 }
301
302 dblink := ""
303
304 if strings.HasPrefix(line, "DBLINK") {
305
306 txt := strings.TrimPrefix(line, "DBLINK")
307 dblink = readContinuationLines(txt)
308 }
309
310 srcdb := ""
311
312 if strings.HasPrefix(line, "DBSOURCE") {
313
314 txt := strings.TrimPrefix(line, "DBSOURCE")
315 srcdb = readContinuationLines(txt)
316 }
317
318 if strings.HasPrefix(line, "KEYWORDS") {
319
320 txt := strings.TrimPrefix(line, "KEYWORDS")
321 key := readContinuationLines(txt)
322 key = strings.TrimSuffix(key, ".")
323
324 if key != "" {
325 rec.WriteString(" <INSDSeq_keywords>\n")
326 kywds := strings.Split(key, ";")
327 for _, kw := range kywds {
328 kw = strings.TrimSpace(kw)
329 if kw == "" || kw == "." {
330 continue
331 }
332
333 writeOneElement(" ", "INSDKeyword", kw)
334 }
335 rec.WriteString(" </INSDSeq_keywords>\n")
336 }
337 }
338
339 if strings.HasPrefix(line, "SOURCE") {
340
341 txt := strings.TrimPrefix(line, "SOURCE")
342 src := readContinuationLines(txt)
343
344 writeOneElement(" ", "INSDSeq_source", src)
345 }
346
347 if strings.HasPrefix(line, " ORGANISM") {
348
349 org := strings.TrimPrefix(line, " ORGANISM")
350 org = CompressRunsOfSpaces(org)
351 org = strings.TrimSpace(org)
352
353 writeOneElement(" ", "INSDSeq_organism", org)
354
355 line = nextLine()
356 row++
357 if strings.HasPrefix(line, twelvespaces) {
358 txt := strings.TrimPrefix(line, twelvespaces)
359 tax := readContinuationLines(txt)
360 tax = strings.TrimSuffix(tax, ".")
361
362 writeOneElement(" ", "INSDSeq_taxonomy", tax)
363 }
364 }
365
366 rec.WriteString(" <INSDSeq_references>\n")
367 for {
368 if !strings.HasPrefix(line, "REFERENCE") {
369 // exit out of reference section
370 break
371 }
372
373 ref := "0"
374
375 rec.WriteString(" <INSDReference>\n")
376
377 txt := strings.TrimPrefix(line, "REFERENCE")
378 str := readContinuationLines(txt)
379 str = CompressRunsOfSpaces(str)
380 str = strings.TrimSpace(str)
381 idx := strings.Index(str, "(")
382 if idx > 0 {
383 ref = strings.TrimSpace(str[:idx])
384
385 writeOneElement(" ", "INSDReference_reference", ref)
386
387 posn := str[idx+1:]
388 posn = strings.TrimSuffix(posn, ")")
389 posn = strings.TrimSpace(posn)
390 if posn == "sites" {
391
392 writeOneElement(" ", "INSDReference_position", posn)
393
394 } else {
395 var arry []string
396 cls := strings.Split(posn, ";")
397 for _, item := range cls {
398 item = strings.TrimPrefix(item, "bases ")
399 item = strings.TrimPrefix(item, "residues ")
400 item = strings.TrimSpace(item)
401 cols := strings.Fields(item)
402 if len(cols) == 3 && cols[1] == "to" {
403 arry = append(arry, cols[0]+".."+cols[2])
404 }
405 }
406 if len(arry) > 0 {
407 posit := strings.Join(arry, ",")
408 writeOneElement(" ", "INSDReference_position", posit)
409 } else {
410 DisplayError("%s", posn)
411 }
412 }
413 } else {
414 ref = strings.TrimSpace(str)
415
416 writeOneElement(" ", "INSDReference_reference", ref)
417 }
418 row++
419
420 if strings.HasPrefix(line, " AUTHORS") {
421
422 txt := strings.TrimPrefix(line, " AUTHORS")
423 auths := readContinuationLines(txt)
424
425 rec.WriteString(" <INSDReference_authors>\n")
426 authors := strings.Split(auths, ", ")
427 for _, auth := range authors {
428 auth = strings.TrimSpace(auth)
429 if auth == "" {
430 continue
431 }
432 pair := strings.Split(auth, " and ")
433 for _, name := range pair {
434
435 writeOneElement(" ", "INSDAuthor", name)
436 }
437 }
438 rec.WriteString(" </INSDReference_authors>\n")
439 }
440
441 if strings.HasPrefix(line, " CONSRTM") {
442
443 txt := strings.TrimPrefix(line, " CONSRTM")
444 cons := readContinuationLines(txt)
445
446 writeOneElement(" ", "INSDReference_consortium", cons)
447 }
448
449 if strings.HasPrefix(line, " TITLE") {
450
451 txt := strings.TrimPrefix(line, " TITLE")
452 titl := readContinuationLines(txt)
453
454 writeOneElement(" ", "INSDReference_title", titl)
455 }
456
457 if strings.HasPrefix(line, " JOURNAL") {
458
459 txt := strings.TrimPrefix(line, " JOURNAL")
460 jour := readContinuationLines(txt)
461
462 writeOneElement(" ", "INSDReference_journal", jour)
463 }
464
465 if strings.HasPrefix(line, " PUBMED") {
466
467 txt := strings.TrimPrefix(line, " PUBMED")
468 pmid := readContinuationLines(txt)
469
470 writeOneElement(" ", "INSDReference_pubmed", pmid)
471 }
472
473 if strings.HasPrefix(line, " MEDLINE") {
474
475 txt := strings.TrimPrefix(line, " MEDLINE")
476 // old MEDLINE uid not supported
477 readContinuationLines(txt)
478 }
479
480 if strings.HasPrefix(line, " REMARK") {
481
482 txt := strings.TrimPrefix(line, " REMARK")
483 rem := readContinuationLines(txt)
484
485 writeOneElement(" ", "INSDReference_remark", rem)
486 }
487
488 // end of this reference
489 rec.WriteString(" </INSDReference>\n")
490 // continue to next reference
491 }
492 rec.WriteString(" </INSDSeq_references>\n")
493
494 if strings.HasPrefix(line, "COMMENT") {
495
496 txt := strings.TrimPrefix(line, "COMMENT")
497 com := readContinuationLines(txt)
498
499 writeOneElement(" ", "INSDSeq_comment", com)
500 }
501
502 if strings.HasPrefix(line, "PRIMARY") {
503
504 txt := strings.TrimPrefix(line, "PRIMARY")
505 pmy := readContinuationLines(txt)
506
507 writeOneElement(" ", "INSDSeq_primary", pmy)
508 }
509
510 if srcdb != "" {
511 writeOneElement(" ", "INSDSeq_source-db", srcdb)
512 }
513
514 rec.WriteString(" <INSDSeq_feature-table>\n")
515 if strings.HasPrefix(line, "FEATURES") {
516
517 line = nextLine()
518 row++
519
520 for {
521 if !strings.HasPrefix(line, " ") {
522 // exit out of features section
523 break
524 }
525 if len(line) < 22 {
526 DisplayError("%s", line)
527 line = nextLine()
528 row++
529 continue
530 }
531
532 rec.WriteString(" <INSDFeature>\n")
533
534 // read feature key and start of location
535 fkey := line[5:21]
536 fkey = strings.TrimSpace(fkey)
537
538 writeOneElement(" ", "INSDFeature_key", fkey)
539
540 loc := line[21:]
541 loc = strings.TrimSpace(loc)
542 for {
543 line = nextLine()
544 row++
545 if !strings.HasPrefix(line, twentyonespaces) {
546 break
547 }
548 txt := strings.TrimPrefix(line, twentyonespaces)
549 if strings.HasPrefix(txt, "/") {
550 // if not continuation of location, break out of loop
551 break
552 }
553 // append subsequent line and continue with loop
554 loc += strings.TrimSpace(txt)
555 }
556
557 writeOneElement(" ", "INSDFeature_location", loc)
558
559 locationOperator := ""
560 isComp := false
561 prime5 := false
562 prime3 := false
563
564 // parseloc recursive definition
565 var parseloc func(string) []string
566
567 parseloc = func(str string) []string {
568
569 var acc []string
570
571 if strings.HasPrefix(str, "join(") && strings.HasSuffix(str, ")") {
572
573 locationOperator = "join"
574
575 str = strings.TrimPrefix(str, "join(")
576 str = strings.TrimSuffix(str, ")")
577 items := strings.Split(str, ",")
578
579 for _, thisloc := range items {
580 inner := parseloc(thisloc)
581 for _, sub := range inner {
582 acc = append(acc, sub)
583 }
584 }
585
586 } else if strings.HasPrefix(str, "order(") && strings.HasSuffix(str, ")") {
587
588 locationOperator = "order"
589
590 str = strings.TrimPrefix(str, "order(")
591 str = strings.TrimSuffix(str, ")")
592 items := strings.Split(str, ",")
593
594 for _, thisloc := range items {
595 inner := parseloc(thisloc)
596 for _, sub := range inner {
597 acc = append(acc, sub)
598 }
599 }
600
601 } else if strings.HasPrefix(str, "complement(") && strings.HasSuffix(str, ")") {
602
603 isComp = true
604
605 str = strings.TrimPrefix(str, "complement(")
606 str = strings.TrimSuffix(str, ")")
607 items := parseloc(str)
608
609 // reverse items
610 for i, j := 0, len(items)-1; i < j; i, j = i+1, j-1 {
611 items[i], items[j] = items[j], items[i]
612 }
613
614 // reverse from and to positions, flip direction of angle brackets (partial flags)
615 for _, thisloc := range items {
616 pts := strings.Split(thisloc, "..")
617 ln := len(pts)
618 if ln == 2 {
619 fst := pts[0]
620 scd := pts[1]
621 lf := ""
622 rt := ""
623 if strings.HasPrefix(fst, "<") {
624 fst = strings.TrimPrefix(fst, "<")
625 rt = ">"
626 }
627 if strings.HasPrefix(scd, ">") {
628 scd = strings.TrimPrefix(scd, ">")
629 lf = "<"
630 }
631 acc = append(acc, lf+scd+".."+rt+fst)
632 } else if ln > 0 {
633 acc = append(acc, pts[0])
634 }
635 }
636
637 } else {
638
639 // save individual interval or point if no leading accession
640 if strings.Index(str, ":") < 0 {
641 acc = append(acc, str)
642 }
643 }
644
645 return acc
646 }
647
648 items := parseloc(loc)
649
650 rec.WriteString(" <INSDFeature_intervals>\n")
651
652 numIvals := 0
653
654 // report individual intervals
655 for _, thisloc := range items {
656 if thisloc == "" {
657 continue
658 }
659
660 numIvals++
661
662 rec.WriteString(" <INSDInterval>\n")
663 pts := strings.Split(thisloc, "..")
664 if len(pts) == 2 {
665
666 // fr..to
667 fr := pts[0]
668 to := pts[1]
669 if strings.HasPrefix(fr, "<") {
670 fr = strings.TrimPrefix(fr, "<")
671 prime5 = true
672 }
673 if strings.HasPrefix(to, ">") {
674 to = strings.TrimPrefix(to, ">")
675 prime3 = true
676 }
677 writeOneElement(" ", "INSDInterval_from", fr)
678 writeOneElement(" ", "INSDInterval_to", to)
679 if isComp {
680 rec.WriteString(" <INSDInterval_iscomp value=\"true\"/>\n")
681 }
682 writeOneElement(" ", "INSDInterval_accession", accnver)
683
684 } else {
685
686 crt := strings.Split(thisloc, "^")
687 if len(crt) == 2 {
688
689 // fr^to
690 fr := crt[0]
691 to := crt[1]
692 writeOneElement(" ", "INSDInterval_from", fr)
693 writeOneElement(" ", "INSDInterval_to", to)
694 if isComp {
695 rec.WriteString(" <INSDInterval_iscomp value=\"true\"/>\n")
696 }
697 rec.WriteString(" <INSDInterval_interbp value=\"true\"/>\n")
698 writeOneElement(" ", "INSDInterval_accession", accnver)
699
700 } else {
701
702 // pt
703 pt := pts[0]
704 if strings.HasPrefix(pt, "<") {
705 pt = strings.TrimPrefix(pt, "<")
706 prime5 = true
707 }
708 if strings.HasPrefix(pt, ">") {
709 pt = strings.TrimPrefix(pt, ">")
710 prime3 = true
711 }
712 writeOneElement(" ", "INSDInterval_point", pt)
713 writeOneElement(" ", "INSDInterval_accession", accnver)
714 }
715 }
716 rec.WriteString(" </INSDInterval>\n")
717 }
718
719 rec.WriteString(" </INSDFeature_intervals>\n")
720
721 if numIvals > 1 {
722 writeOneElement(" ", "INSDFeature_operator", locationOperator)
723 }
724 if prime5 {
725 rec.WriteString(" <INSDFeature_partial5 value=\"true\"/>\n")
726 }
727 if prime3 {
728 rec.WriteString(" <INSDFeature_partial3 value=\"true\"/>\n")
729 }
730
731 isLegalQualifier := func(str string) bool {
732
733 if str == "" {
734 return false
735 }
736
737 lft, rgt := SplitInTwoLeft(str, "=")
738 if lft == "" || rgt == "" {
739 return false
740 }
741
742 ky := strings.ToUpper(lft)
743 val, ok := legalQuals[ky]
744 if ok && lft == val {
745 return true
746 }
747
748 return false
749 }
750
751 hasQual := false
752 hasMolWt := false
753 for {
754 if !strings.HasPrefix(line, twentyonespaces) {
755 // if not qualifier line, break out of loop
756 break
757 }
758 txt := strings.TrimPrefix(line, twentyonespaces)
759 qual := ""
760 val := ""
761 if strings.HasPrefix(txt, "/") {
762 if !hasQual {
763 hasQual = true
764 rec.WriteString(" <INSDFeature_quals>\n")
765 }
766 // read new qualifier and start of value
767 qual = strings.TrimPrefix(txt, "/")
768 qual = strings.TrimSpace(qual)
769 idx := strings.Index(qual, "=")
770 if idx > 0 {
771 val = qual[idx+1:]
772 qual = qual[:idx]
773 }
774
775 for {
776 line = nextLine()
777 row++
778 if !strings.HasPrefix(line, twentyonespaces) {
779 break
780 }
781 txt := strings.TrimPrefix(line, twentyonespaces)
782 if strings.HasPrefix(txt, "/") && isLegalQualifier(txt[1:]) {
783 // if not continuation of qualifier, break out of loop
784 break
785 }
786 // append subsequent line to value and continue with loop
787 if qual == "transcription" || qual == "translation" || qual == "peptide" || qual == "anticodon" {
788 val += strings.TrimSpace(txt)
789 } else {
790 val += " " + strings.TrimSpace(txt)
791 }
792 }
793
794 if qual == "country" && fkey == "source" {
795 qual = "geo_loc_name"
796 }
797
798 if qual == "calculated_mol_wt" || qual == "mol_wt" {
799 hasMolWt = true
800 }
801
802 val = strings.TrimPrefix(val, "\"")
803 val = strings.TrimSuffix(val, "\"")
804 val = strings.TrimSpace(val)
805
806 if qual == "translation" && !hasMolWt {
807 mw := ProteinWeight(val, true, false)
808 if mw != "" {
809 rec.WriteString(" <INSDQualifier>\n")
810 writeOneElement(" ", "INSDQualifier_name", "calculated_mol_wt")
811 writeOneElement(" ", "INSDQualifier_value", mw)
812 rec.WriteString(" </INSDQualifier>\n")
813 hasMolWt = true
814 }
815 }
816
817 rec.WriteString(" <INSDQualifier>\n")
818
819 writeOneElement(" ", "INSDQualifier_name", qual)
820
821 if val != "" {
822
823 writeOneElement(" ", "INSDQualifier_value", val)
824 }
825
826 rec.WriteString(" </INSDQualifier>\n")
827 }
828 }
829 if hasQual {
830 rec.WriteString(" </INSDFeature_quals>\n")
831 }
832
833 // end of this feature
834 rec.WriteString(" </INSDFeature>\n")
835 // continue to next feature
836 }
837 }
838 rec.WriteString(" </INSDSeq_feature-table>\n")
839
840 // TSA, TLS, WGS, or CONTIG lines may be next
841
842 altName := ""
843
844 if strings.HasPrefix(line, "TSA") ||
845 strings.HasPrefix(line, "TLS") ||
846 strings.HasPrefix(line, "WGS") {
847
848 alt.Reset()
849
850 altName = line[:3]
851 line = line[3:]
852 }
853
854 if strings.HasPrefix(line, "WGS_CONTIG") ||
855 strings.HasPrefix(line, "WGS_SCAFLD") {
856
857 alt.Reset()
858
859 altName = line[:3]
860 line = line[10:]
861 }
862
863 if altName != "" {
864
865 altName = strings.ToLower(altName)
866 txt := strings.TrimSpace(line)
867 alt.WriteString(txt)
868 for {
869 // read next line
870 line = nextLine()
871 row++
872 if !strings.HasPrefix(line, twelvespaces) {
873 // if not continuation of contig, break out of loop
874 break
875 }
876 // append subsequent line and continue with loop
877 txt = strings.TrimPrefix(line, twelvespaces)
878 txt = strings.TrimSpace(txt)
879 alt.WriteString(txt)
880 }
881 }
882
883 if strings.HasPrefix(line, "CONTIG") {
884
885 // pathological records can have over 90,000 components, use strings.Builder
886 con.Reset()
887
888 txt := strings.TrimPrefix(line, "CONTIG")
889 txt = strings.TrimSpace(txt)
890 con.WriteString(txt)
891 for {
892 // read next line
893 line = nextLine()
894 row++
895 if !strings.HasPrefix(line, twelvespaces) {
896 // if not continuation of contig, break out of loop
897 break
898 }
899 // append subsequent line and continue with loop
900 txt = strings.TrimPrefix(line, twelvespaces)
901 txt = strings.TrimSpace(txt)
902 con.WriteString(txt)
903 }
904 }
905
906 if strings.HasPrefix(line, "BASE COUNT") {
907
908 txt := strings.TrimPrefix(line, "BASE COUNT")
909 readContinuationLines(txt)
910 // not supported
911 }
912
913 if strings.HasPrefix(line, "ORIGIN") {
914
915 line = nextLine()
916 row++
917 }
918
919 // remainder should be sequence
920
921 // sequence can be millions of bases, use strings.Builder
922 seq.Reset()
923
924 for line != "" {
925
926 if strings.HasPrefix(line, "//") {
927
928 // end of record, print collected sequence
929 str := seq.String()
930 if str != "" {
931
932 writeOneElement(" ", "INSDSeq_sequence", str)
933 }
934 seq.Reset()
935
936 // print contig section
937 str = con.String()
938 str = strings.TrimSpace(str)
939 if str != "" {
940 writeOneElement(" ", "INSDSeq_contig", str)
941 }
942 con.Reset()
943
944 if altName != "" {
945 rec.WriteString(" <INSDSeq_alt-seq>\n")
946 rec.WriteString(" <INSDAltSeqData>\n")
947 str = alt.String()
948 str = strings.TrimSpace(str)
949 if str != "" {
950 writeOneElement(" ", "INSDAltSeqData_name", altName)
951 rec.WriteString(" <INSDAltSeqData_items>\n")
952 fr, to := SplitInTwoLeft(str, "-")
953 if fr != "" && to != "" {
954 rec.WriteString(" <INSDAltSeqItem>\n")
955 writeOneElement(" ", "INSDAltSeqItem_first-accn", fr)
956 writeOneElement(" ", "INSDAltSeqItem_last-accn", to)
957 rec.WriteString(" </INSDAltSeqItem>\n")
958 } else {
959 writeOneElement(" ", "INSDAltSeqItem_value", str)
960 }
961 rec.WriteString(" </INSDAltSeqData_items>\n")
962 }
963 alt.Reset()
964 rec.WriteString(" </INSDAltSeqData>\n")
965 rec.WriteString(" </INSDSeq_alt-seq>\n")
966 }
967
968 if dblink != "" {
969 rec.WriteString(" <INSDSeq_xrefs>\n")
970 // collect for database-reference
971 flds := strings.Fields(dblink)
972 for len(flds) > 1 {
973 tag := flds[0]
974 val := flds[1]
975 flds = flds[2:]
976 tag = strings.TrimSuffix(tag, ":")
977 rec.WriteString(" <INSDXref>\n")
978 writeOneElement(" ", "INSDXref_dbname", tag)
979 writeOneElement(" ", "INSDXref_id", val)
980 rec.WriteString(" </INSDXref>\n")
981 }
982 rec.WriteString(" </INSDSeq_xrefs>\n")
983 }
984
985 // end of record
986 rec.WriteString(" </INSDSeq>\n")
987
988 // send formatted record down channel
989 txt := rec.String()
990 out <- txt
991 rec.Reset()
992 // go to top of loop for next record
993 break
994 }
995
996 // read next sequence line
997
998 cols := strings.Fields(line)
999 if len(cols) > 0 && !IsAllDigits(cols[0]) {
1000 DisplayError("Unrecognized section %s", cols[0])
1001 }
1002
1003 for _, str := range cols {
1004
1005 if IsAllDigits(str) {
1006 continue
1007 }
1008
1009 // append letters to sequence
1010 seq.WriteString(str)
1011 }
1012
1013 // read next line and continue
1014 line = nextLine()
1015 row++
1016
1017 }
1018
1019 // continue to next record
1020 }
1021 }
1022
1023 // launch single converter goroutine
1024 go convertGenBank(inp, out)
1025
1026 return out
1027 }
1028
1029 // GenBanktoXML converts a GenBank flatfile to an XML string
1030 func GenBanktoXML(gbff string) string {
1031
1032 return StringToXML(gbff, GenBankConverter)
1033 }
1034
1035 // CreateGBConverters makes concurrent calls to GenBankConverter
1036 func CreateGBConverters(inp <-chan TextRecord) <-chan TextRecord {
1037
1038 if inp == nil {
1039 return nil
1040 }
1041
1042 out := make(chan TextRecord, chanDepth)
1043 if out == nil {
1044 DisplayError("Unable to create gb converter channel")
1045 os.Exit(1)
1046 }
1047
1048 gbConvert := func(wg *sync.WaitGroup, inp <-chan TextRecord, out chan<- TextRecord) {
1049
1050 // report when this matcher has no more records to process
1051 defer wg.Done()
1052
1053 convertOneGB := func(str string) string {
1054
1055 in := strings.NewReader(str)
1056
1057 gbcq := GenBankConverter(in)
1058 if out == nil {
1059 DisplayError("Unable to create gb converter channel")
1060 os.Exit(1)
1061 }
1062
1063 var rec strings.Builder
1064
1065 for res := range gbcq {
1066 rec.WriteString(res)
1067 }
1068
1069 txt := rec.String()
1070
1071 return txt
1072 }
1073
1074 // read partitioned XML from producer channel
1075 for curr := range inp {
1076
1077 txt := convertOneGB(curr.Text)
1078
1079 out <- TextRecord{Index: curr.Index, Text: txt}
1080 }
1081 }
1082
1083 var wg sync.WaitGroup
1084
1085 // launch multiple gb converter goroutines
1086 for range numServe {
1087 wg.Add(1)
1088 go gbConvert(&wg, inp, out)
1089 }
1090
1091 // launch separate anonymous goroutine to wait until all converters are done
1092 go func() {
1093 wg.Wait()
1094 close(out)
1095 }()
1096
1097 return out
1098 }