-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
genbank.go
1265 lines (1126 loc) · 41.8 KB
/
genbank.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Package genbank provides genbank parsers and writers.
GenBank is a flat text file format developed in the 1980s to annotate genetic
sequences, and has since become the standard for sharing annotated genetic
sequences.
This package provides a parser and writer to convert between the GenBank file
format and the more general Genbank struct.
*/
package genbank
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"github.com/koeng101/dnadesign/lib/transform"
)
/******************************************************************************
GBK specific IO related things begin here.
******************************************************************************/
var (
readFileFn = os.ReadFile
parseMultiNthFn = parseMultiNth
parseReferencesFn = parseReferences
)
// Genbank is the main struct for the Genbank file format.
type Genbank struct {
Meta Meta
Features []Feature
Sequence string // will be changed and include reader, writer, and byte slice.
}
// Meta holds the meta data for Genbank and other annotated sequence files.
type Meta struct {
Date string `json:"date"`
Definition string `json:"definition"`
Accession string `json:"accession"`
Version string `json:"version"`
Keywords string `json:"keywords"`
Organism string `json:"organism"`
Source string `json:"source"`
Taxonomy []string `json:"taxonomy"`
Origin string `json:"origin"`
Locus Locus `json:"locus"`
References []Reference `json:"references"`
BaseCount []BaseCount `json:"base_count"`
Other map[string]string `json:"other"`
Name string `json:"name"`
SequenceHash string `json:"sequence_hash"`
SequenceHashFunction string `json:"hash_function"`
}
// Feature holds the information for a feature in a Genbank file and other annotated sequence files.
type Feature struct {
Type string `json:"type"`
Description string `json:"description"`
Attributes map[string][]string `json:"attributes"`
SequenceHash string `json:"sequence_hash"`
SequenceHashFunction string `json:"hash_function"`
Sequence string `json:"sequence"`
Location Location `json:"location"`
ParentSequence *Genbank `json:"-"`
}
// Reference holds information for one reference in a Meta struct.
type Reference struct {
Authors string `json:"authors"`
Title string `json:"title"`
Journal string `json:"journal"`
PubMed string `json:"pub_med"`
Remark string `json:"remark"`
Range string `json:"range"`
Consortium string `json:"consortium"`
}
// Locus holds Locus information in a Meta struct.
type Locus struct {
Name string `json:"name"`
SequenceLength string `json:"sequence_length"`
MoleculeType string `json:"molecule_type"`
GenbankDivision string `json:"genbank_division"`
ModificationDate string `json:"modification_date"`
SequenceCoding string `json:"sequence_coding"`
Circular bool `json:"circular"`
}
// Location is a struct that holds the location of a feature.
type Location struct {
Start int `json:"start"`
End int `json:"end"`
Complement bool `json:"complement"`
Join bool `json:"join"`
FivePrimePartial bool `json:"five_prime_partial"`
ThreePrimePartial bool `json:"three_prime_partial"`
GbkLocationString string `json:"gbk_location_string"`
SubLocations []Location `json:"sub_locations"`
}
// BaseCount is a struct that holds the base counts for a sequence.
type BaseCount struct {
Base string
Count int
}
// Precompiled regular expressions:
var (
basePairRegex = regexp.MustCompile(` \d* \w{2} `)
circularRegex = regexp.MustCompile(` circular `)
modificationDateRegex = regexp.MustCompile(`\d{2}-[A-Z]{3}-\d{4}`)
partialRegex = regexp.MustCompile("<|>")
sequenceRegex = regexp.MustCompile("[^a-zA-Z]+")
)
// StoreFeatureSequences calls StoreSequence on all features.
// The resulting JSON is guaranteed to have useful Feature.Sequence values.
// Useful when exporting for downstream analysis, such as with json.Marshal.
func (sequence *Genbank) StoreFeatureSequences() error {
for i := range sequence.Features {
_, err := sequence.Features[i].StoreSequence()
if err != nil {
return err
}
}
return nil
}
// AddFeature adds a feature to a Genbank struct.
// NOTE: This method assumes feature is not referenced in another location
// as this only creates a shallow copy.
// If you intend to duplicate a feature from another Genbank and plan
// to modify in either location, it is recommended you first call feature.Copy()
// before passing as input to save yourself trouble.
func (sequence *Genbank) AddFeature(feature *Feature) error {
feature.ParentSequence = sequence
sequence.Features = append(sequence.Features, *feature)
return nil
}
// GetSequence returns the sequence of a feature.
func (feature Feature) GetSequence() (string, error) {
return getFeatureSequence(feature, feature.Location)
}
// StoreSequence infers and assigns the value of feature.Sequence
// if currently an empty string.
func (feature *Feature) StoreSequence() (string, error) {
if feature.Sequence != "" {
return feature.Sequence, nil
}
seq, err := getFeatureSequence(*feature, feature.Location)
if err == nil {
feature.Sequence = seq
}
return seq, err
}
// Copy creates deep copy of Feature, which supports safe duplication.
func (feature *Feature) Copy() Feature {
copy := *feature
copy.Location = CopyLocation(feature.Location)
copy.Attributes = NewMultiMap[string, string]()
ForEachKey(feature.Attributes, func(k string, v []string) {
copy.Attributes[k] = MapSlice(v, identity[string])
})
return copy
}
// CopyLocation creates deep copy of Location, which supports safe duplication
func CopyLocation(location Location) Location {
location.SubLocations = MapSlice(location.SubLocations, CopyLocation)
return location
}
// getFeatureSequence takes a feature and location object and returns a sequence string.
func getFeatureSequence(feature Feature, location Location) (string, error) {
var sequenceBuffer bytes.Buffer
parentSequence := feature.ParentSequence.Sequence
if len(location.SubLocations) == 0 {
sequenceBuffer.WriteString(parentSequence[location.Start:location.End])
} else {
for _, subLocation := range location.SubLocations {
sequence, err := getFeatureSequence(feature, subLocation)
if err != nil {
return "", err
}
sequenceBuffer.WriteString(sequence)
}
}
// reverse complements resulting string if needed.
sequenceString := sequenceBuffer.String()
if location.Complement {
sequenceString = transform.ReverseComplement(sequenceString)
}
return sequenceString, nil
}
// WriteTo implements the io.WriterTo interface on genbank records.
func (sequence *Genbank) WriteTo(w io.Writer) (int64, error) {
var writtenBytes int64
var newWrittenBytes int
var err error
locus := sequence.Meta.Locus
var shape string
if locus.Circular {
shape = "circular"
} else {
shape = "linear"
}
fivespace := generateWhiteSpace(subMetaIndex)
// building locus
locusData := locus.Name + fivespace + locus.SequenceLength + " bp" + fivespace + locus.MoleculeType + fivespace + shape + fivespace + locus.GenbankDivision + fivespace + locus.ModificationDate
locusString := "LOCUS " + locusData + "\n"
newWrittenBytes, err = w.Write([]byte(locusString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
// building other standard meta features
definitionString := buildMetaString("DEFINITION", sequence.Meta.Definition)
newWrittenBytes, err = w.Write([]byte(definitionString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
accessionString := buildMetaString("ACCESSION", sequence.Meta.Accession)
newWrittenBytes, err = w.Write([]byte(accessionString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
versionString := buildMetaString("VERSION", sequence.Meta.Version)
newWrittenBytes, err = w.Write([]byte(versionString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
keywordsString := buildMetaString("KEYWORDS", sequence.Meta.Keywords)
newWrittenBytes, err = w.Write([]byte(keywordsString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
sourceString := buildMetaString("SOURCE", sequence.Meta.Source)
newWrittenBytes, err = w.Write([]byte(sourceString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
organismString := buildMetaString(" ORGANISM", sequence.Meta.Organism)
newWrittenBytes, err = w.Write([]byte(organismString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
if len(sequence.Meta.Taxonomy) > 0 {
var taxonomyString strings.Builder
for i, taxonomyData := range sequence.Meta.Taxonomy {
taxonomyString.WriteString(taxonomyData)
if len(sequence.Meta.Taxonomy) == i+1 {
taxonomyString.WriteString(".")
} else {
taxonomyString.WriteString("; ")
}
}
newWrittenBytes, err = w.Write([]byte(buildMetaString("", taxonomyString.String())))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
// building references
// TODO: could use reflection to get keys and make more general.
for referenceIndex, reference := range sequence.Meta.References {
referenceString := buildMetaString("REFERENCE", fmt.Sprintf("%d %s", referenceIndex+1, reference.Range))
newWrittenBytes, err = w.Write([]byte(referenceString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
if reference.Authors != "" {
authorsString := buildMetaString(" AUTHORS", reference.Authors)
newWrittenBytes, err = w.Write([]byte(authorsString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
if reference.Title != "" {
titleString := buildMetaString(" TITLE", reference.Title)
newWrittenBytes, err = w.Write([]byte(titleString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
if reference.Journal != "" {
journalString := buildMetaString(" JOURNAL", reference.Journal)
newWrittenBytes, err = w.Write([]byte(journalString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
if reference.PubMed != "" {
pubMedString := buildMetaString(" PUBMED", reference.PubMed)
newWrittenBytes, err = w.Write([]byte(pubMedString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
if reference.Consortium != "" {
consrtmString := buildMetaString(" CONSRTM", reference.Consortium)
newWrittenBytes, err = w.Write([]byte(consrtmString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
}
// building other meta fields that are catch all
otherKeys := make([]string, 0, len(sequence.Meta.Other))
for key := range sequence.Meta.Other {
otherKeys = append(otherKeys, key)
}
for _, otherKey := range otherKeys {
otherString := buildMetaString(otherKey, sequence.Meta.Other[otherKey])
newWrittenBytes, err = w.Write([]byte(otherString))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
// start writing features section.
newWrittenBytes, err = w.Write([]byte("FEATURES Location/Qualifiers\n"))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
for _, feature := range sequence.Features {
newWrittenBytes, err = w.Write([]byte(BuildFeatureString(feature)))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
// start writing base count
if len(sequence.Meta.BaseCount) > 0 {
newWrittenBytes, err = w.Write([]byte("BASE COUNT "))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
for _, baseCount := range sequence.Meta.BaseCount {
newWrittenBytes, err = w.Write([]byte(strconv.Itoa(baseCount.Count) + " " + baseCount.Base + " "))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
newWrittenBytes, err = w.Write([]byte("\n"))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
// start writing sequence section.
newWrittenBytes, err = w.Write([]byte("ORIGIN\n"))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
// iterate over every character in sequence range.
for index, base := range sequence.Sequence {
// if 60th character add newline then whitespace and index number and space before adding next base.
if index%60 == 0 {
if index != 0 {
newWrittenBytes, err = w.Write([]byte("\n"))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
lineNumberString := strconv.Itoa(index + 1) // genbank indexes at 1 for some reason
leadingWhiteSpaceLength := 9 - len(lineNumberString) // <- I wish I was kidding
for i := 0; i < leadingWhiteSpaceLength; i++ {
newWrittenBytes, err = w.Write([]byte(" "))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
newWrittenBytes, err = w.Write([]byte(lineNumberString + " "))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
newWrittenBytes, err = w.Write([]byte{byte(base)})
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
// if base index is divisible by ten add a space (genbank convention)
} else if index%10 == 0 {
newWrittenBytes, err = w.Write([]byte(" "))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
newWrittenBytes, err = w.Write([]byte{byte(base)})
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
// else just add the base.
} else {
newWrittenBytes, err = w.Write([]byte{byte(base)})
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
}
}
// finish genbank file with "//" on newline (again a genbank convention)
newWrittenBytes, err = w.Write([]byte("\n//\n"))
writtenBytes += int64(newWrittenBytes)
if err != nil {
return writtenBytes, err
}
return writtenBytes, nil
}
// ParseError represents failures encountered while parsing,
// and pointers to it are fully compatable with the error interface.
type ParseError struct {
file string // the file origin
line string // the offending line
before bool // whether the error occurred before or on this line
lineNo int // the line number, 0 indexed
info string `default:"syntax error"` // description of the error type
wraps error // stores the error that led to this, if any
}
func (e ParseError) Error() string {
var out, loc string
if e.wraps == io.EOF {
out = "unexpected EOF"
if e.file != "" {
return fmt.Sprintf("%s in %s", out, e.file)
} else {
return out
}
}
if e.file == "" {
loc = fmt.Sprintf("line %d", e.lineNo)
} else {
loc = fmt.Sprintf("%s:%d", e.file, e.lineNo)
}
if e.before {
out = fmt.Sprintf("%s encountered before %s", e.info, loc)
} else {
out = fmt.Sprintf("%s encountered on %s: %s", e.info, loc, e.line)
}
if e.wraps != nil {
out = fmt.Sprintf("%s\nfrom %v", out, e.wraps)
}
return out
}
// defines state for the parser, and utility methods to modify
type parseLoopParameters struct {
newLocation bool
attribute string
attributeValue string
emptyAttribute bool
sequenceBuilder strings.Builder
parseStep string
genbank Genbank // since we are scanning lines we need a Genbank struct to store the data outside the loop.
feature Feature
features []Feature
metadataTag string
metadataData []string //this stutters but will remain to make it easier to batch rename variables when compared to parameters.metadataTag.
genbankStarted bool
currentLine string
prevline string
multiLineFeature bool
}
// method to init loop parameters
func (params *parseLoopParameters) init() {
params.newLocation = true
params.feature.Attributes = NewMultiMap[string, string]()
params.parseStep = "metadata"
params.genbankStarted = false
params.genbank.Meta.Other = make(map[string]string)
}
// save our completed attribute / qualifier string to the current feature
// useful as a wrap-up step from multiple states
func (params *parseLoopParameters) saveLastAttribute() {
newValue := params.attributeValue != ""
emptyType := params.feature.Type != ""
if newValue || emptyType {
if newValue {
Put(params.feature.Attributes, params.attribute, params.attributeValue)
}
params.features = append(params.features, params.feature)
// reset attribute state
params.attributeValue = ""
params.attribute = ""
params.feature = Feature{}
params.feature.Attributes = NewMultiMap[string, string]()
}
}
// Header is a blank struct, needed for compatibility with bio parsers. It contains nothing.
type Header struct{}
// WriteTo is a blank function, needed for compatibility with bio parsers. It doesn't do anything.
func (header *Header) WriteTo(w io.Writer) (int64, error) {
return 0, nil
}
// Parser is a genbank parser created on an io.Reader.
type Parser struct {
scanner bufio.Scanner
parameters parseLoopParameters
}
// Header returns nil,nil.
func (parser *Parser) Header() (Header, error) {
return Header{}, nil
}
// NewParser returns a Parser that uses r as the source
// from which to parse genbank formatted sequences.
func NewParser(r io.Reader, maxLineSize int) *Parser {
scanner := bufio.NewScanner(r)
buf := make([]byte, maxLineSize)
scanner.Buffer(buf, maxLineSize)
return &Parser{
scanner: *scanner,
}
}
// Next takes in a reader representing a multi gbk/gb/genbank file and outputs the next record
func (parser *Parser) Next() (Genbank, error) {
parser.parameters.init()
// Loop through each line of the file
for lineNum := 0; parser.scanner.Scan(); lineNum++ {
// get line from scanner and split it
line := parser.scanner.Text()
splitLine := strings.Split(strings.TrimSpace(line), " ")
prevline := parser.parameters.currentLine
parser.parameters.currentLine = line
parser.parameters.prevline = prevline
// keep scanning until we find the start of the first record
if !parser.parameters.genbankStarted {
// We detect the beginning of a new genbank file with "LOCUS"
locusFlag := strings.Contains(line, "LOCUS")
if locusFlag {
parser.parameters = parseLoopParameters{}
parser.parameters.init()
parser.parameters.genbank.Meta.Locus = parseLocus(line)
parser.parameters.genbankStarted = true
}
continue
}
// define parser state machine
switch parser.parameters.parseStep {
case "metadata":
// Handle empty lines
if len(line) == 0 {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, info: "unexpected empty metadata"}
}
// If we are currently reading a line, we need to figure out if it is a new meta line.
if string(line[0]) != " " || parser.parameters.metadataTag == "FEATURES" {
// If this is true, it means we are beginning a new meta tag. In that case, let's save
// the older data, and then continue along.
switch parser.parameters.metadataTag {
case "DEFINITION":
parser.parameters.genbank.Meta.Definition = parseMetadata(parser.parameters.metadataData)
case "ACCESSION":
parser.parameters.genbank.Meta.Accession = parseMetadata(parser.parameters.metadataData)
case "VERSION":
parser.parameters.genbank.Meta.Version = parseMetadata(parser.parameters.metadataData)
case "KEYWORDS":
parser.parameters.genbank.Meta.Keywords = parseMetadata(parser.parameters.metadataData)
case "SOURCE":
parser.parameters.genbank.Meta.Source, parser.parameters.genbank.Meta.Organism, parser.parameters.genbank.Meta.Taxonomy = getSourceOrganism(parser.parameters.metadataData)
case "REFERENCE":
// parseReferencesFn = parseReferences in genbank_test. We use Fn for testing purposes.
reference, err := parseReferencesFn(parser.parameters.metadataData)
if err != nil {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, before: true, wraps: err, info: "failed in parsing reference"}
}
parser.parameters.genbank.Meta.References = append(parser.parameters.genbank.Meta.References, reference)
case "FEATURES":
parser.parameters.parseStep = "features"
// We know that we are now parsing features, so lets initialize our first feature
parser.parameters.feature.Type = strings.TrimSpace(splitLine[0])
parser.parameters.feature.Location.GbkLocationString = strings.TrimSpace(splitLine[len(splitLine)-1])
parser.parameters.newLocation = true
continue
default:
if parser.parameters.metadataTag != "" {
parser.parameters.genbank.Meta.Other[parser.parameters.metadataTag] = parseMetadata(parser.parameters.metadataData)
}
}
parser.parameters.metadataTag = strings.TrimSpace(splitLine[0])
parser.parameters.metadataData = []string{strings.TrimSpace(line[len(parser.parameters.metadataTag):])}
} else {
parser.parameters.metadataData = append(parser.parameters.metadataData, line)
}
case "features":
baseCountFlag := strings.Contains(line, "BASE COUNT") // example string for BASE COUNT: "BASE COUNT 67070277 a 48055043 c 48111528 g 67244164 t 18475410 n"
if baseCountFlag {
fields := strings.Fields(line)
for countIndex := 2; countIndex < len(fields)-1; countIndex += 2 { // starts at two because we don't want to include "BASE COUNT" in our fields
count, err := strconv.Atoi(fields[countIndex])
if err != nil {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, wraps: err, info: "invalid base count"}
}
baseCount := BaseCount{
Base: fields[countIndex+1],
Count: count,
}
parser.parameters.genbank.Meta.BaseCount = append(parser.parameters.genbank.Meta.BaseCount, baseCount)
}
break
}
// Switch to sequence parsing
originFlag := strings.Contains(line, "ORIGIN") // we detect the beginning of the sequence with "ORIGIN"
contigFlag := strings.Contains(line, "CONTIG")
if originFlag || contigFlag {
parser.parameters.parseStep = "sequence"
parser.parameters.saveLastAttribute()
// add our features to the genbank
for _, feature := range parser.parameters.features {
// TODO: parse location when line is read, or track line number so error is localized
location, err := parseLocation(feature.Location.GbkLocationString)
if err != nil {
return Genbank{}, &ParseError{before: true, line: line, lineNo: lineNum, wraps: err, info: "invalid feature location"}
}
feature.Location = location
err = parser.parameters.genbank.AddFeature(&feature)
if err != nil {
return Genbank{}, &ParseError{before: true, line: line, lineNo: lineNum, wraps: err, info: "problem adding feature"}
}
}
if contigFlag {
parser.parameters.genbank.Meta.Other["CONTIG"] = parseMetadata(splitLine[1:])
}
continue
}
// check if current line contains anything but whitespace
trimmedLine := strings.TrimSpace(line)
if len(trimmedLine) == 0 {
continue
}
indent := countLeadingSpaces(parser.parameters.currentLine)
// determine if current line is a new top level feature
if indent == 0 {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, info: "unexpected metadata when parsing feature"}
} else if indent < countLeadingSpaces(parser.parameters.prevline) || parser.parameters.prevline == "FEATURES" {
parser.parameters.saveLastAttribute()
parser.parameters.feature = Feature{}
parser.parameters.feature.Attributes = NewMultiMap[string, string]()
// An initial feature line looks like this: `source 1..2686` with a type separated by its location
if len(splitLine) < 2 {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, info: "malformed feature"}
}
parser.parameters.feature.Type = strings.TrimSpace(splitLine[0])
parser.parameters.feature.Location.GbkLocationString = strings.TrimSpace(splitLine[len(splitLine)-1])
parser.parameters.multiLineFeature = false // without this we can't tell if something is a multiline feature or multiline qualifier
} else if !strings.Contains(parser.parameters.currentLine, "/") { // current line is continuation of a feature or qualifier (sub-constituent of a feature)
// if it's a continuation of the current feature, add it to the location
if !strings.Contains(parser.parameters.currentLine, "\"") && (countLeadingSpaces(parser.parameters.currentLine) > countLeadingSpaces(parser.parameters.prevline) || parser.parameters.multiLineFeature) {
parser.parameters.feature.Location.GbkLocationString += strings.TrimSpace(line)
parser.parameters.multiLineFeature = true // without this we can't tell if something is a multiline feature or multiline qualifier
} else { // it's a continued line of a qualifier
removeAttributeValueQuotes := strings.Replace(trimmedLine, "\"", "", -1)
parser.parameters.attributeValue = parser.parameters.attributeValue + removeAttributeValueQuotes
}
} else if strings.Contains(parser.parameters.currentLine, "/") { // current line is a new qualifier
trimmedCurrentLine := strings.TrimSpace(parser.parameters.currentLine)
if trimmedCurrentLine[0] != '/' { // if we have an exception case, like (adenine(1518)-N(6)/adenine(1519)-N(6))-
parser.parameters.attributeValue = parser.parameters.attributeValue + trimmedCurrentLine
continue
}
// save our completed attribute / qualifier string to the current feature
if parser.parameters.attributeValue != "" || parser.parameters.emptyAttribute {
Put(parser.parameters.feature.Attributes, parser.parameters.attribute, parser.parameters.attributeValue)
parser.parameters.emptyAttribute = false
}
parser.parameters.attributeValue = ""
splitAttribute := strings.Split(line, "=")
trimmedSpaceAttribute := strings.TrimSpace(splitAttribute[0])
removedForwardSlashAttribute := strings.Replace(trimmedSpaceAttribute, "/", "", 1)
parser.parameters.attribute = removedForwardSlashAttribute
var removeAttributeValueQuotes string
if len(splitAttribute) == 1 { // handle case of ` /pseudo `, which has no text
removeAttributeValueQuotes = ""
parser.parameters.emptyAttribute = true
} else { // this is normally triggered
removeAttributeValueQuotes = strings.Replace(splitAttribute[1], "\"", "", -1)
}
parser.parameters.attributeValue = removeAttributeValueQuotes
parser.parameters.multiLineFeature = false // without this we can't tell if something is a multiline feature or multiline qualifier
} else {
return Genbank{}, &ParseError{line: line, lineNo: lineNum, info: "invalid feature"}
}
case "sequence":
if len(line) < 2 { // throw error if line is malformed
return Genbank{}, &ParseError{line: line, lineNo: lineNum, info: "too short line found while parsing genbank sequence"}
} else if line[0:2] == "//" { // end of sequence
parser.parameters.genbank.Sequence = parser.parameters.sequenceBuilder.String()
parser.parameters.genbankStarted = false
parser.parameters.sequenceBuilder.Reset()
return parser.parameters.genbank, nil
} else { // add line to total sequence
parser.parameters.sequenceBuilder.WriteString(sequenceRegex.ReplaceAllString(line, ""))
}
default:
return Genbank{}, fmt.Errorf("Unknown parse step: %s", parser.parameters.parseStep)
}
}
return Genbank{}, io.EOF
}
func countLeadingSpaces(line string) int {
return len(line) - len(strings.TrimLeft(line, " "))
}
func parseMetadata(metadataData []string) string {
var outputMetadata string
if len(metadataData) == 0 {
return "."
}
for _, data := range metadataData {
outputMetadata = outputMetadata + strings.TrimSpace(data) + " "
}
outputMetadata = outputMetadata[:len(outputMetadata)-1] // Remove trailing whitespace
return outputMetadata
}
func parseReferences(metadataData []string) (Reference, error) {
var reference Reference
var err error
rangeIndex := strings.Index(metadataData[0], "(")
if rangeIndex != -1 {
reference.Range = metadataData[0][rangeIndex:]
}
var referenceKey string
var referenceValue string
if len(metadataData) == 1 {
return Reference{}, fmt.Errorf("Got reference with no additional information")
}
referenceKey = strings.Split(strings.TrimSpace(metadataData[1]), " ")[0]
referenceValue = strings.TrimSpace(metadataData[1][len(referenceKey)+2:])
for index := 2; index < len(metadataData); index++ {
if len(metadataData[index]) > 3 {
if metadataData[index][3] != ' ' {
err = reference.addKey(referenceKey, referenceValue)
if err != nil {
return reference, err
}
referenceKey = strings.Split(strings.TrimSpace(metadataData[index]), " ")[0]
referenceValue = strings.TrimSpace(metadataData[index][len(referenceKey)+2:])
} else {
// Otherwise, simply append the next metadata.
referenceValue = referenceValue + " " + strings.TrimSpace(metadataData[index])
}
}
}
err = reference.addKey(referenceKey, referenceValue)
if err != nil {
return reference, err
}
return reference, nil
}
func (reference *Reference) addKey(referenceKey string, referenceValue string) error {
switch referenceKey {
case "AUTHORS":
reference.Authors = referenceValue
case "TITLE":
reference.Title = referenceValue
case "JOURNAL":
reference.Journal = referenceValue
case "PUBMED":
reference.PubMed = referenceValue
case "REMARK":
reference.Remark = referenceValue
case "CONSRTM":
reference.Consortium = referenceValue
default:
return fmt.Errorf("ReferenceKey not in [AUTHORS, TITLE, JOURNAL, PUBMED, REMARK, CONSRTM]. Got: %s", referenceKey)
}
return nil
}
var genBankMoleculeTypes = []string{
"DNA",
"genomic DNA",
"genomic RNA",
"mRNA",
"tRNA",
"rRNA",
"other RNA",
"other DNA",
"transcribed RNA",
"viral cRNA",
"unassigned DNA",
"unassigned RNA",
}
// used in parseLocus function though it could be useful elsewhere.
var genbankDivisions = []string{
"PRI", //primate sequences
"ROD", //rodent sequences
"MAM", //other mamallian sequences
"VRT", //other vertebrate sequences
"INV", //invertebrate sequences
"PLN", //plant, fungal, and algal sequences
"BCT", //bacterial sequences
"VRL", //viral sequences
"PHG", //bacteriophage sequences
"SYN", //synthetic sequences
"UNA", //unannotated sequences
"EST", //EST sequences (expressed sequence tags)
"PAT", //patent sequences
"STS", //STS sequences (sequence tagged sites)
"GSS", //GSS sequences (genome survey sequences)
"HTG", //HTG sequences (high-throughput genomic sequences)
"HTC", //unfinished high-throughput cDNA sequencing
"ENV", //environmental sampling sequences
}
// TODO rewrite with proper error handling.
// parses locus from provided string.
func parseLocus(locusString string) Locus {
locus := Locus{}
locusSplit := strings.Split(strings.TrimSpace(locusString), " ")
var filteredLocusSplit []string
for i := range locusSplit {
if locusSplit[i] != "" {
filteredLocusSplit = append(filteredLocusSplit, locusSplit[i])
}
}
locus.Name = filteredLocusSplit[1]
// sequence length and coding
baseSequenceLength := basePairRegex.FindString(locusString)
if baseSequenceLength != "" {
splitBaseSequenceLength := strings.Split(strings.TrimSpace(baseSequenceLength), " ")
if len(splitBaseSequenceLength) == 2 {
locus.SequenceLength = splitBaseSequenceLength[0]
locus.SequenceCoding = splitBaseSequenceLength[1]
}
}
// molecule type
for _, moleculeType := range genBankMoleculeTypes {
moleculeRegex, _ := regexp.Compile(moleculeType)
match := string(moleculeRegex.Find([]byte(locusString)))
if match != "" {
locus.MoleculeType = match
break
}
}
// circularity flag
if circularRegex.Match([]byte(locusString)) {
locus.Circular = true
}
// genbank division
for _, genbankDivision := range genbankDivisions {
genbankDivisionRegex, _ := regexp.Compile(genbankDivision)
match := string(genbankDivisionRegex.Find([]byte(locusString)))
if match != "" {
locus.GenbankDivision = match
break
}
}
// ModificationDate
locus.ModificationDate = modificationDateRegex.FindString(locusString)
return locus
}
// indices for random points of interests on a gbk line.
const subMetaIndex = 5
const qualifierIndex = 21
func getSourceOrganism(metadataData []string) (string, string, []string) {
source := strings.TrimSpace(metadataData[0])
var organism string
var taxonomy []string
for iterator := 1; iterator < len(metadataData); iterator++ {
dataLine := metadataData[iterator]
headString := strings.Split(strings.TrimSpace(dataLine), " ")[0]
if headString == "ORGANISM" {
index := strings.Index(dataLine, `ORGANISM`)
organism = strings.TrimSpace(dataLine[index+len("ORGANISM"):])
continue
}
for _, taxonomyData := range strings.Split(strings.TrimSpace(dataLine), ";") {
taxonomyDataTrimmed := strings.TrimSpace(taxonomyData)
// Taxonomy ends with a ".", which we check for here
if len(taxonomyDataTrimmed) > 1 {
if taxonomyDataTrimmed[len(taxonomyDataTrimmed)-1] == '.' {
taxonomyDataTrimmed = taxonomyDataTrimmed[:len(taxonomyDataTrimmed)-1]
}
taxonomy = append(taxonomy, taxonomyDataTrimmed)
}
}
}
return source, organism, taxonomy
}
func parseLocation(locationString string) (Location, error) {
var location Location
location.GbkLocationString = locationString
if !strings.ContainsAny(locationString, "(") { // Case checks for simple expression of x..x
if !strings.ContainsAny(locationString, ".") { //Case checks for simple expression x
position, err := strconv.Atoi(partialRegex.ReplaceAllString(locationString, ""))
if err != nil {
return Location{}, err