Debian Codegraph @

eutils/gcode.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: gcode.go
26 //
27 // Author: Jonathan Kans
28 //
29 // ==========================================================================
30
31 package eutils
32
33 import (
34 "fmt"
35 "maps"
36 "os"
37 "slices"
38 "strings"
39 )
40
41 // When a new genetic code is added, update the raw genetic code tables below,
42 // recompile, run 'transmute -degenerate > gdata.go' to generate new data tables,
43 // replace the old gdata.go source code file with the new version, and then
44 // recompile again to bring all executables up to date.
45
46 // bases are ncbi4na bit flags: A 0, C 1, G 2, T 4
47
48 const (
49 // tgca
50 baseGap = iota // 0 - - 0000
51 baseA // 1 A A 0001
52 baseC // 2 C C 0010
53 baseM // 3 M AC 0011
54 baseG // 4 G G 0100
55 baseR // 5 R AG 0101
56 baseS // 6 S CG 0110
57 baseV // 7 V ACG 0111
58 baseT // 8 T T 1000
59 baseW // 9 W AT 1001
60 baseY // 10 Y CT 1010
61 baseH // 11 H ACT 1011
62 baseK // 12 K GT 1100
63 baseD // 13 D AGT 1101
64 baseB // 14 B CGT 1110
65 baseN // 15 N ACGT 1111
66 )
67
68 // Base
69 // 1 TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGG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Alternative start codons may encode Leucine, Isoleucine, or Valine during
104 // elongation, but a separate initiator tRNA always inserts Methionine (or
105 // formyl-Methionine (fMet) in bacteria) the start of translation.
106
107 // The sncbieaaCode field was expanded to include potential translation
108 // termination codons, indicated by asterisks, upon discovery of ciliate
109 // genetic codes without dedicated stop codons.
110
111 // Base
112 // 1 TTTTTTTTTTTTTTTTCCCCCCCCCCCCCCCCAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGG
113 // 2 TTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGGTTTTCCCCAAAAGGGG
114 // 3 TCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAGTCAG
115
116 var sncbieaaCode = map[int]string{
117 1: "---M------**--*----M---------------M----------------------------",
118 2: "----------**--------------------MMMM----------**---M------------",
119 3: "----------**----------------------MM---------------M------------",
120 4: "--MM------**-------M------------MMMM---------------M------------",
121 5: "---M------**--------------------MMMM---------------M------------",
122 6: "--------------*--------------------M----------------------------",
123 9: "----------**-----------------------M---------------M------------",
124 10: "----------**-----------------------M----------------------------",
125 11: "---M------**--*----M------------MMMM---------------M------------",
126 12: "----------**--*----M---------------M----------------------------",
127 13: "---M------**----------------------MM---------------M------------",
128 14: "-----------*-----------------------M----------------------------",
129 15: "----------*---*--------------------M----------------------------",
130 16: "----------*---*--------------------M----------------------------",
131 21: "----------**-----------------------M---------------M------------",
132 22: "------*---*---*--------------------M----------------------------",
133 23: "--*-------**--*-----------------M--M---------------M------------",
134 24: "---M------**-------M---------------M---------------M------------",
135 25: "---M------**-----------------------M---------------M------------",
136 26: "----------**--*----M---------------M----------------------------",
137 27: "--------------*--------------------M----------------------------",
138 28: "----------**--*--------------------M----------------------------",
139 29: "--------------*--------------------M----------------------------",
140 30: "--------------*--------------------M----------------------------",
141 31: "----------**-----------------------M----------------------------",
142 32: "---M------*---*----M------------MMMM---------------M------------",
143 33: "---M-------*-------M---------------M---------------M------------",
144 }
145
146 var genCodeNames = map[int]string{
147 1: "Standard",
148 2: "Vertebrate Mitochondrial",
149 3: "Yeast Mitochondrial",
150 4: "Mold Mitochondrial; Protozoan Mitochondrial; Coelenterate Mitochondrial; Mycoplasma; Spiroplasma",
151 5: "Invertebrate Mitochondrial",
152 6: "Ciliate Nuclear; Dasycladacean Nuclear; Hexamita Nuclear",
153 9: "Echinoderm Mitochondrial; Flatworm Mitochondrial",
154 10: "Euplotid Nuclear",
155 11: "Bacterial, Archaeal and Plant Plastid",
156 12: "Alternative Yeast Nuclear",
157 13: "Ascidian Mitochondrial",
158 14: "Alternative Flatworm Mitochondrial",
159 15: "Blepharisma Macronuclear",
160 16: "Chlorophycean Mitochondrial",
161 21: "Trematode Mitochondrial",
162 22: "Scenedesmus obliquus Mitochondrial",
163 23: "Thraustochytrium Mitochondrial",
164 24: "Rhabdopleuridae Mitochondrial",
165 25: "Candidate Division SR1 and Gracilibacteria",
166 26: "Pachysolen tannophilus Nuclear",
167 27: "Karyorelict Nuclear",
168 28: "Condylostoma Nuclear",
169 29: "Mesodinium Nuclear",
170 30: "Peritrich Nuclear",
171 31: "Blastocrithidia Nuclear",
172 32: "Balanophoraceae Plastid",
173 33: "Cephalodiscidae Mitochondrial",
174 }
175
176 // finite state machine into lookup table for simultaneous two-strand translation
177
178 func correctGenCode(genCode int) int {
179
180 switch genCode {
181 case 0:
182 genCode = 1
183 case 7:
184 genCode = 4
185 case 8:
186 genCode = 1
187 }
188
189 return genCode
190 }
191
192 // GenCodeName returns full name of genetic code
193 func GenCodeName(genCode int) string {
194
195 genCode = correctGenCode(genCode)
196
197 return genCodeNames[genCode]
198 }
199
200 // SetCodonState initializes a state from three nucleotide letters
201 func SetCodonState(ch1, ch2, ch3 int) int {
202
203 if ch1 < 0 || ch1 > 255 || ch2 < 0 || ch2 > 255 || ch3 < 0 || ch3 > 255 {
204 return 0
205 }
206
207 return 256*baseToIdx[ch1] + 16*baseToIdx[ch2] + baseToIdx[ch3]
208 }
209
210 // GetCodonFromState returns the three-letter codon from the state value
211 func GetCodonFromState(state int) string {
212
213 if state < 0 || state > 4095 {
214 return ""
215 }
216
217 upperToBase := "-ACMGRSVTWYHKDBN"
218
219 ch3 := upperToBase[state&15]
220 state = state >> 4
221 ch2 := upperToBase[state&15]
222 state = state >> 4
223 ch1 := upperToBase[state&15]
224
225 str := string(ch1) + string(ch2) + string(ch3)
226
227 return str
228 }
229
230 // NextCodonState uses the old state plus the new letter
231 func NextCodonState(state, ch int) int {
232
233 if state < 0 || state > 4095 {
234 return 0
235 }
236
237 return nextState[state] + baseToIdx[ch]
238 }
239
240 // RevCompState finds the state for the last three bases on the minus strand
241 func RevCompState(state int) int {
242
243 if state < 0 || state > 4095 {
244 return 0
245 }
246
247 return rvCpState[state]
248 }
249
250 // translation codon lookup functions
251
252 // GetCodonResidue returns the amino acid for the state representing the current codon
253 func GetCodonResidue(genCode, state int) int {
254
255 genCode = correctGenCode(genCode)
256
257 if state < 0 || state > 4095 {
258 return 'X'
259 }
260
261 // look for override in alternative genetic code
262 gc, ok := aminoAcidMaps[genCode]
263 if ok {
264 aa, ok := gc[state]
265 if ok {
266 return aa
267 }
268 }
269
270 if genCode != 1 {
271 // now fetch residue from standard genetic code
272 gc, ok = aminoAcidMaps[1]
273 if ok {
274 aa, ok := gc[state]
275 if ok {
276 return aa
277 }
278 }
279 }
280
281 // no entry in either map defaults to unknown residue X
282 return 'X'
283 }
284
285 // GetStartResidue returns the amino acid for the first codon
286 func GetStartResidue(genCode, state int) int {
287
288 genCode = correctGenCode(genCode)
289
290 if state < 0 || state > 4095 {
291 return '-'
292 }
293
294 gc, ok := orfStartMaps[genCode]
295 if ok {
296 aa, ok := gc[state]
297 if ok {
298 return aa
299 }
300 }
301
302 return '-'
303 }
304
305 // GetStopResidue returns the amino acid for the last codon
306 func GetStopResidue(genCode, state int) int {
307
308 genCode = correctGenCode(genCode)
309
310 if state < 0 || state > 4095 {
311 return '-'
312 }
313
314 gc, ok := orfStopMaps[genCode]
315 if ok {
316 aa, ok := gc[state]
317 if ok {
318 return aa
319 }
320 }
321
322 return '-'
323 }
324
325 // IsOrfStart returns true for a start codon
326 func IsOrfStart(genCode, state int) bool {
327
328 genCode = correctGenCode(genCode)
329
330 if state < 0 || state > 4095 {
331 return false
332 }
333
334 return GetStartResidue(genCode, state) == 'M'
335 }
336
337 // IsOrfStop returns true for a stop codon
338 func IsOrfStop(genCode, state int) bool {
339
340 genCode = correctGenCode(genCode)
341
342 if state < 0 || state > 4095 {
343 return false
344 }
345
346 return GetStopResidue(genCode, state) == '*'
347 }
348
349 // IsATGStart returns true for an ATG start codon
350 func IsATGStart(genCode, state int) bool {
351
352 genCode = correctGenCode(genCode)
353
354 const ATGState = 388
355
356 if state < 0 || state > 4095 {
357 return false
358 }
359
360 return IsOrfStart(genCode, state) && state == ATGState
361 }
362
363 // IsAltStart returns true for a non-ATG start codon
364 func IsAltStart(genCode, state int) bool {
365
366 genCode = correctGenCode(genCode)
367
368 const ATGState = 388
369
370 if state < 0 || state > 4095 {
371 return false
372 }
373
374 return IsOrfStart(genCode, state) && state != ATGState
375 }
376
377 // TranslateCdRegion converts a single coding region to a protein sequence
378 func TranslateCdRegion(seq string, genCode, frame int, includeStop, doEveryCodon, removeTrailingX, is5primeComplete, is3primeComplete bool, between string) string {
379
380 genCode = correctGenCode(genCode)
381
382 usableSize := len(seq) - frame
383 mod := usableSize % 3
384 length := usableSize / 3
385 checkStart := is5primeComplete && frame == 0
386
387 aa := 0
388 state := 0
389 // start_state := 0
390 firstTime := true
391
392 // look up fully-resolved precomputed genetic code array
393 genCodeTable, ok := genCodeMaps[genCode]
394 if !ok {
395 genCodeTable = genCodeMaps[1]
396 }
397
398 pos := frame
399
400 var aminos []string
401
402 // first codon has extra logic, process separately
403 if length > 0 {
404
405 // loop through first codon to initialize state
406 for range 3 {
407
408 // internal version of NextCodonState without value reality check
409 ch := int(seq[pos])
410 state = nextState[state] + baseToIdx[ch]
411 // state = NextCodonState(state, int(seq[pos]))
412 pos++
413 }
414
415 // start_state = state
416
417 // save first translated amino acid
418 if checkStart {
419 aa = GetStartResidue(genCode, state)
420 } else {
421 aa = GetCodonResidue(genCode, state)
422 }
423
424 aminos = append(aminos, string(rune(aa)))
425
426 firstTime = false
427 }
428
429 // start at offset 1, continue with rest of sequence
430 for i := 1; i < length; i++ {
431
432 // loop through next triplet codon
433 for range 3 {
434
435 // internal version of NextCodonState without value reality check
436 ch := int(seq[pos])
437 state = nextState[state] + baseToIdx[ch]
438 // state = NextCodonState(state, int(seq[pos]))
439 pos++
440 }
441
442 // save translated amino acid
443 aa = int(genCodeTable[state])
444 // aa = GetCodonResidue(genCode, state)
445
446 aminos = append(aminos, string(rune(aa)))
447
448 firstTime = false
449 }
450
451 if mod > 0 {
452
453 var last []string
454
455 k := 0
456 for ; k < mod; k++ {
457 ch := int(seq[pos])
458 state = NextCodonState(state, ch)
459 pos++
460 last = append(last, string(rune(ch)))
461 }
462
463 for ; k < 3; k++ {
464 state = NextCodonState(state, int('N'))
465 last = append(last, "N")
466 }
467
468 if firstTime {
469 // start_state = state
470 }
471
472 // save translated amino acid
473 ch := GetCodonResidue(genCode, state)
474
475 aa = 0
476 if firstTime && checkStart {
477 aa = GetStartResidue(genCode, state)
478 } else if ch != 'X' {
479 aa = GetCodonResidue(genCode, state)
480 }
481
482 if aa != 0 {
483 aminos = append(aminos, string(rune(aa)))
484 }
485 }
486
487 txt := strings.Join(aminos, between)
488
489 // check for stop codon that normally encodes an amino acid
490 if aa != '*' && includeStop && mod > 0 && len(txt) > 0 && is3primeComplete {
491
492 aa = GetStopResidue(genCode, state)
493 if aa == '*' {
494 rgt := len(txt) - 1
495 txt = txt[:rgt] + "*"
496 }
497 }
498
499 if doEveryCodon {
500
501 // read through all stop codons
502
503 } else if includeStop {
504
505 idx := strings.Index(txt, "*")
506 if idx >= 0 && idx+1 < len(txt) {
507 txt = txt[:idx+1]
508 }
509
510 } else {
511
512 idx := strings.Index(txt, "*")
513 if idx >= 0 {
514 txt = txt[:idx]
515 }
516 }
517
518 if removeTrailingX {
519
520 for strings.HasSuffix(txt, "X") || strings.HasSuffix(txt, "*") {
521 txt = strings.TrimRight(txt, "*")
522 txt = strings.TrimRight(txt, "X")
523 }
524 }
525
526 return txt
527 }
528
529 // TranslateAllFrames produces six-frame translation in a single pass
530 func TranslateAllFrames(seq string, genCode int, circular, orf bool) []string {
531
532 var arry []string
533
534 if len(seq) < 6 {
535 return nil
536 }
537
538 // strings.Builder.WriteByte is inlined by the compiler
539 var forward [3]strings.Builder
540 var reverse [3]strings.Builder
541
542 genCode = correctGenCode(genCode)
543
544 // look up fully-resolved precomputed genetic code array
545 genCodeTable, ok := genCodeMaps[genCode]
546 if !ok {
547 genCodeTable = genCodeMaps[1]
548 }
549
550 if orf {
551 // orf option flags start codon states with upper-case amino acid letters
552 gc, ok := orfStartMaps[genCode]
553 if ok {
554 tmp := []byte(strings.ToLower(genCodeTable))
555 // single variable range on map gives index (state), not value (amino acid)
556 for state := range gc {
557 tmp[state] = genCodeTable[state]
558 }
559 // replace original with case-modified version
560 genCodeTable = string(tmp)
561 }
562 }
563
564 state := 0
565
566 // prime state table with first two nucleotides
567 for _, ch := range seq[:2] {
568 state = nextState[state] + baseToIdx[int(ch)]
569 }
570
571 frame := 0
572
573 // sending a slice does not copy the original data
574 translateThreeFrames := func(subseq string) {
575
576 // use local copies of state and frame for speed
577 st := state
578 fr := frame
579
580 for _, ch := range subseq {
581
582 // codon to residue for plus strand
583 st = nextState[st] + baseToIdx[int(ch)]
584 forward[fr].WriteByte(genCodeTable[st])
585
586 // reverse-complemented codon to residue for minus strand
587 rv := rvCpState[st]
588 reverse[fr].WriteByte(genCodeTable[rv])
589
590 // cycle through three reading frames on each strand
591 fr++
592 if fr > 2 {
593 // reset frame
594 fr = 0
595 }
596 }
597
598 // update state and frame closure variables
599 state = st
600 frame = fr
601 }
602
603 // process remainder of sequence through finite state machine
604 translateThreeFrames(seq[2:])
605
606 trunc := 0
607
608 if circular {
609
610 // feed in first two bases used to prime state machine
611 translateThreeFrames(seq[:2])
612
613 // calculate final length
614 for fr := range 3 {
615 ln := forward[fr].Len()
616 if ln > trunc {
617 trunc = ln
618 }
619 }
620
621 // translate two more bases, then truncate all to final length
622 translateThreeFrames(seq[2:4])
623
624 // for 10-base circular molecule, third frame needs two additional
625 // bases beyond the primer to generate all possible codons
626 // ATG TTT CTG A|AT G
627 // TGT TTC TGA| ATG
628 // GTT TCT GA|A TGT
629 }
630
631 // write translations from plus strand codons in all three frames
632 for frame := range 3 {
633 tmp := forward[frame].String()
634 if trunc > 0 && len(tmp) > trunc {
635 arry = append(arry, tmp[:trunc])
636 } else {
637 arry = append(arry, tmp[:])
638 }
639 }
640
641 // need to reverse the order of residues translated on minus strand from
642 // reverse-complemented codons but proceeding in 3' to 5' direction
643 for frame := range 3 {
644 tmp := reverse[frame].String()
645 if trunc > 0 && len(tmp) > trunc {
646 arry = append(arry, ReverseString(tmp[:trunc]))
647 } else {
648 arry = append(arry, ReverseString(tmp[:]))
649 }
650 }
651
652 /*
653 combining circular and orf flags should provide enough information to allow
654 reconstruction of coding region spanning origin of circular molecules, such
655 as plasmids, mitochondria, or (most) bacterial chromosomes
656 */
657
658 return arry
659 }
660
661 // NucProtCodonReport displays triplet codons above the translated amino acid
662 func NucProtCodonReport(nuc, prt string, frame int, threeLetter bool) string {
663
664 usableSize := len(nuc) - frame
665 mod := usableSize % 3
666 length := usableSize / 3
667
668 if length < 1 {
669 return ""
670 }
671
672 pos := frame
673 lag := pos
674
675 var codons []string
676
677 for range length {
678 pos += 3
679 codons = append(codons, nuc[lag:pos])
680 lag = pos
681 }
682
683 if mod > 0 {
684
685 var last []string
686
687 k := 0
688 for ; k < mod; k++ {
689 ch := int(nuc[pos])
690 pos++
691 last = append(last, string(rune(ch)))
692 }
693
694 lag = pos
695
696 for ; k < 3; k++ {
697 last = append(last, "N")
698 }
699
700 cdn := strings.Join(last, "")
701 codons = append(codons, cdn)
702 }
703
704 var buffer strings.Builder
705 cumulative := 0
706
707 for len(codons) > 0 || len(prt) > 0 {
708 k := 0
709 for ; k < 15 && len(codons) > 0; k++ {
710 cdn := codons[0]
711 codons = codons[1:]
712 buffer.WriteString(cdn)
713 buffer.WriteString(" ")
714 }
715 cumulative += k
716 for ; k < 15; k++ {
717 buffer.WriteString(" ")
718 }
719 num := fmt.Sprintf("%6d", cumulative)
720 buffer.WriteString(num)
721 buffer.WriteString("\n")
722 k = 0
723 for ; k < 15 && len(prt) > 0; k++ {
724 res := string(prt[0])
725 prt = prt[1:]
726 if threeLetter {
727 res = aaTo3[res]
728 } else {
729 res = " " + res + " "
730 }
731 buffer.WriteString(res)
732 buffer.WriteString(" ")
733 }
734 buffer.WriteString("\n\n")
735 }
736
737 txt := buffer.String()
738
739 return txt
740 }
741
742 // PrintGeneticCodeTables prints a tab-delimited table of all genetic codes
743 func PrintGeneticCodeTables() {
744
745 keys := slices.Sorted(maps.Keys(ncbieaaCode))
746
747 for _, id := range keys {
748 fmt.Fprintf(os.Stdout, "%d\t%s\t%s\t%s\n", id, ncbieaaCode[id], sncbieaaCode[id], genCodeNames[id])
749 }
750 }
751
752 const gdataHeading = "" +
753 `// ===========================================================================
754 //
755 // PUBLIC DOMAIN NOTICE
756 // National Center for Biotechnology Information (NCBI)
757 //
758 // This software/database is a "United States Government Work" under the
759 // terms of the United States Copyright Act. It was written as part of
760 // the author's official duties as a United States Government employee and
761 // thus cannot be copyrighted. This software/database is freely available
762 // to the public for use. The National Library of Medicine and the U.S.
763 // Government do not place any restriction on its use or reproduction.
764 // We would, however, appreciate having the NCBI and the author cited in
765 // any work or product based on this material.
766 //
767 // Although all reasonable efforts have been taken to ensure the accuracy
768 // and reliability of the software and data, the NLM and the U.S.
769 // Government do not and cannot warrant the performance or results that
770 // may be obtained by using this software or data. The NLM and the U.S.
771 // Government disclaim all warranties, express or implied, including
772 // warranties of performance, merchantability or fitness for any particular
773 // purpose.
774 //
775 // ===========================================================================
776 //
777 // File Name: gdata.go
778 //
779 // Author: transmute -degenerate > gdata.go
780 //
781 // ==========================================================================`
782
783 // GenerateGeneticCodeMaps regenerates static protein translation maps
784 func GenerateGeneticCodeMaps() {
785
786 fmt.Fprintf(os.Stdout, "%s\n\n", gdataHeading)
787
788 fmt.Fprintf(os.Stdout, "package eutils\n\n")
789
790 // generate baseToIdx for source code
791
792 var baseToIdx [256]int
793
794 upperToBase := "-ACMGRSVTWYHKDBN"
795 lowerToBase := "-acmgrsvtwyhkdbn"
796
797 // illegal characters map to 0
798 for i := range 256 {
799 baseToIdx[i] = baseGap
800 }
801
802 // map iupacna alphabet to int
803 for i := baseGap; i <= baseN; i++ {
804 ch := upperToBase[i]
805 baseToIdx[int(ch)] = i
806 ch = lowerToBase[i]
807 baseToIdx[int(ch)] = i
808 }
809 baseToIdx['U'] = baseT
810 baseToIdx['u'] = baseT
811 baseToIdx['X'] = baseN
812 baseToIdx['x'] = baseN
813
814 // also map ncbi4na alphabet to int
815 for i := baseGap; i <= baseN; i++ {
816 baseToIdx[i] = i
817 }
818
819 fmt.Fprintf(os.Stdout, "var baseToIdx = [256]int{\n")
820 for i := 0; i < 256; i += 16 {
821 prefix := "\t"
822 for j := range 16 {
823 fmt.Fprintf(os.Stdout, "%s%4d,", prefix, baseToIdx[i+j])
824 prefix = " "
825 }
826 fmt.Fprintf(os.Stdout, "\n")
827 }
828 fmt.Fprintf(os.Stdout, "}\n\n")
829
830 // populate nextState and rvCpState arrays
831
832 var nextState [4096]int
833 var rvCpState [4096]int
834
835 baseToComp := "-TGKCYSBAWRDMHVN"
836
837 // states 0 through 4095 are triple letter states (---, --A, ..., NNT, NNN)
838 for i, st := baseGap, 0; i <= baseN; i++ {
839 for j, nx := baseGap, 0; j <= baseN; j++ {
840 for k := baseGap; k <= baseN; k++ {
841 nextState[st] = nx
842 p := baseToIdx[int(baseToComp[k])]
843 q := baseToIdx[int(baseToComp[j])]
844 r := baseToIdx[int(baseToComp[i])]
845 rvCpState[st] = int(256*p + 16*q + r)
846 st++
847 nx += 16
848 }
849 }
850 }
851
852 // NextCodonState indexes through nextState array and adds base* value
853 fmt.Fprintf(os.Stdout, "var nextState = [4096]int{\n")
854 for i := 0; i < 4096; i += 16 {
855 prefix := "\t"
856 for j := range 16 {
857 fmt.Fprintf(os.Stdout, "%s%4d,", prefix, nextState[i+j])
858 prefix = " "
859 }
860 fmt.Fprintf(os.Stdout, "\n")
861 }
862 fmt.Fprintf(os.Stdout, "}\n\n")
863
864 // RevCompState is a direct index to the reverse complement of a state
865 fmt.Fprintf(os.Stdout, "var rvCpState = [4096]int{\n")
866 for i := 0; i < 4096; i += 16 {
867 prefix := "\t"
868 for j := range 16 {
869 fmt.Fprintf(os.Stdout, "%s%4d,", prefix, rvCpState[i+j])
870 prefix = " "
871 }
872 fmt.Fprintf(os.Stdout, "\n")
873 }
874 fmt.Fprintf(os.Stdout, "}\n\n")
875
876 // translation table structure
877 type TransTable struct {
878 aminoAcid [4096]int
879 orfStart [4096]int
880 orfStop [4096]int
881 }
882
883 // create translation table for given genetic code
884 newTransTable := func(genCode int) *TransTable {
885
886 tbl := new(TransTable)
887 if tbl == nil {
888 DisplayError("Unable to allocate translation table for genetic code %d", genCode)
889 os.Exit(1)
890 }
891
892 // genetic code number corrections
893 if genCode == 7 {
894 genCode = 4
895 } else if genCode == 8 {
896 genCode = 1
897 } else if genCode == 0 {
898 genCode = 1
899 }
900
901 // return if unable to find ncbieaa and sncbieaa strings
902 ncbieaa, ok := ncbieaaCode[genCode]
903 if !ok {
904 DisplayError("Genetic code %d does not exist", genCode)
905 os.Exit(1)
906 }
907 sncbieaa, ok := sncbieaaCode[genCode]
908 if !ok {
909 DisplayError("Genetic code %d does not exist", genCode)
910 os.Exit(1)
911 }
912
913 // also check length of ncbieaa and sncbieaa strings
914 if len(ncbieaa) != 64 || len(sncbieaa) != 64 {
915 DisplayError("Genetic code %d length mismatch", genCode)
916 os.Exit(1)
917 }
918
919 // ambiguous codons map to unknown amino acid or not start
920 for i := range 4096 {
921 tbl.aminoAcid[i] = int('X')
922 tbl.orfStart[i] = int('-')
923 tbl.orfStop[i] = int('-')
924 }
925
926 var expansions = [4]int{baseA, baseC, baseG, baseT}
927 // T = 0, C = 1, A = 2, G = 3
928 var codonIdx = [9]int{0, 2, 1, 0, 3, 0, 0, 0, 0}
929
930 // lookup amino acid for each codon in genetic code table
931 for i, st := baseGap, 0; i <= baseN; i++ {
932 for j := baseGap; j <= baseN; j++ {
933 for k := baseGap; k <= baseN; k++ {
934
935 aa := 0
936 orf := 0
937 goOn := true
938
939 // expand ambiguous IJK nucleotide symbols into component bases XYZ
940 for p := 0; p < 4 && goOn; p++ {
941 x := expansions[p]
942 if (x & i) != 0 {
943 for q := 0; q < 4 && goOn; q++ {
944 y := expansions[q]
945 if (y & j) != 0 {
946 for r := 0; r < 4 && goOn; r++ {
947 z := expansions[r]
948 if (z & k) != 0 {
949
950 // calculate offset in genetic code string
951
952 // the T = 0, C = 1, A = 2, G = 3 order is
953 // necessary because the genetic code
954 // strings are presented in TCAG order
955 cd := 16*codonIdx[x] + 4*codonIdx[y] + codonIdx[z]
956
957 // lookup amino acid for codon XYZ
958 ch := int(ncbieaa[cd])
959 if aa == 0 {
960 aa = ch
961 } else if aa != ch {
962 // allow Asx (Asp or Asn) and Glx (Glu or Gln)
963 if (aa == 'B' || aa == 'D' || aa == 'N') && (ch == 'D' || ch == 'N') {
964 aa = 'B'
965 } else if (aa == 'Z' || aa == 'E' || aa == 'Q') && (ch == 'E' || ch == 'Q') {
966 aa = 'Z'
967 } else if (aa == 'J' || aa == 'I' || aa == 'L') && (ch == 'I' || ch == 'L') {
968 aa = 'J'
969 } else {
970 aa = 'X'
971 }
972 }
973
974 // lookup translation start flag
975 ch = int(sncbieaa[cd])
976 if orf == 0 {
977 orf = ch
978 } else if orf != ch {
979 orf = 'X'
980 }
981
982 // drop out of loop as soon as answer is known
983 if aa == 'X' && orf == 'X' {
984 goOn = false
985 }
986 }
987 }
988 }
989 }
990 }
991 }
992
993 // assign amino acid
994 if aa != 0 {
995 tbl.aminoAcid[st] = aa
996 }
997 // assign orf start/stop
998 if orf == '*' {
999 tbl.orfStop[st] = orf
1000 } else if orf != 0 && orf != '-' && orf != 'X' {
1001 tbl.orfStart[st] = orf
1002 }
1003
1004 st++
1005 }
1006 }
1007 }
1008
1009 return tbl
1010 }
1011
1012 // generate aminoAcidMaps, orfStartMaps, and orfStopMaps for source code
1013
1014 // sort genetic code keys in numerical order
1015 keys := slices.Sorted(maps.Keys(sncbieaaCode))
1016
1017 tbl := newTransTable(1)
1018 if tbl == nil {
1019 DisplayError("newTransTable failed")
1020 return
1021 }
1022
1023 fmt.Fprintf(os.Stdout, "// standard genetic code [1] shows only non-X residues,\n")
1024 fmt.Fprintf(os.Stdout, "// remaining tables show differences from the standard\n\n")
1025 fmt.Fprintf(os.Stdout, "var aminoAcidMaps = map[int]map[int]int{\n")
1026
1027 spaces := ""
1028 fmt.Fprintf(os.Stdout, "\t1: {\n")
1029 for i := range 4096 {
1030 aa := tbl.aminoAcid[i]
1031 if aa != 0 && aa != 'X' {
1032 if i < 10 {
1033 spaces = " "
1034 } else if i < 100 {
1035 spaces = " "
1036 } else if i < 1000 {
1037 spaces = " "
1038 } else {
1039 spaces = ""
1040 }
1041 fmt.Fprintf(os.Stdout, "\t\t%d:%s '%c', // %s\n", i, spaces, aa, GetCodonFromState(i))
1042 }
1043 }
1044 fmt.Fprintf(os.Stdout, "\t},\n")
1045
1046 for _, id := range keys {
1047
1048 // skip standard code
1049 if id == 1 {
1050 continue
1051 }
1052
1053 tb := newTransTable(id)
1054 if tb == nil {
1055 DisplayWarning("newTransTable failed for code %d, skipping", id)
1056 continue
1057 }
1058
1059 spaces = ""
1060 fmt.Fprintf(os.Stdout, "\t%d: {\n", id)
1061 for i := range 4096 {
1062 aa := tbl.aminoAcid[i]
1063 nw := tb.aminoAcid[i]
1064 if aa == nw {
1065 continue
1066 }
1067 // allow 'X' to override specific amino acid in standard code
1068 if aa != 0 {
1069 if i < 10 {
1070 spaces = " "
1071 } else if i < 100 {
1072 spaces = " "
1073 } else if i < 1000 {
1074 spaces = " "
1075 } else {
1076 spaces = ""
1077 }
1078 fmt.Fprintf(os.Stdout, "\t\t%d:%s '%c', // %s\n", i, spaces, nw, GetCodonFromState(i))
1079 }
1080 }
1081 fmt.Fprintf(os.Stdout, "\t},\n")
1082 }
1083
1084 fmt.Fprintf(os.Stdout, "}\n\n")
1085
1086 // continue with start and stop tables, but all are instantiated
1087
1088 fmt.Fprintf(os.Stdout, "// start and stop tables show all relevant entries for each genetic code\n\n")
1089 fmt.Fprintf(os.Stdout, "var orfStartMaps = map[int]map[int]int{\n")
1090
1091 for _, id := range keys {
1092
1093 tb := newTransTable(id)
1094 if tb == nil {
1095 DisplayWarning("newTransTable failed for code %d, skipping", id)
1096 continue
1097 }
1098
1099 spaces = ""
1100 fmt.Fprintf(os.Stdout, "\t%d: {\n", id)
1101 for i := range 4096 {
1102 aa := tb.orfStart[i]
1103 if aa != 0 && aa != '*' && aa != '-' && aa != 'X' {
1104 if i < 10 {
1105 spaces = " "
1106 } else if i < 100 {
1107 spaces = " "
1108 } else if i < 1000 {
1109 spaces = " "
1110 } else {
1111 spaces = ""
1112 }
1113 fmt.Fprintf(os.Stdout, "\t\t%d:%s '%c', // %s\n", i, spaces, aa, GetCodonFromState(i))
1114 }
1115 }
1116 fmt.Fprintf(os.Stdout, "\t},\n")
1117 }
1118
1119 fmt.Fprintf(os.Stdout, "}\n\n")
1120
1121 fmt.Fprintf(os.Stdout, "var orfStopMaps = map[int]map[int]int{\n")
1122
1123 for _, id := range keys {
1124
1125 tb := newTransTable(id)
1126 if tb == nil {
1127 DisplayWarning("newTransTable failed for code %d, skipping", id)
1128 continue
1129 }
1130
1131 spaces = ""
1132 fmt.Fprintf(os.Stdout, "\t%d: {\n", id)
1133 for i := range 4096 {
1134 aa := tb.orfStop[i]
1135 if aa == '*' {
1136 if i < 10 {
1137 spaces = " "
1138 } else if i < 100 {
1139 spaces = " "
1140 } else if i < 1000 {
1141 spaces = " "
1142 } else {
1143 spaces = ""
1144 }
1145 fmt.Fprintf(os.Stdout, "\t\t%d:%s '%c', // %s\n", i, spaces, aa, GetCodonFromState(i))
1146 }
1147 }
1148 fmt.Fprintf(os.Stdout, "\t},\n")
1149 }
1150
1151 fmt.Fprintf(os.Stdout, "}\n\n")
1152
1153 // finish with instantiated genetic code arrays
1154
1155 fmt.Fprintf(os.Stdout, "// genetic code arrays for performance for each genetic code\n\n")
1156 fmt.Fprintf(os.Stdout, "var genCodeMaps = map[int]string{\n")
1157
1158 for _, id := range keys {
1159
1160 tb := newTransTable(id)
1161 if tb == nil {
1162 DisplayWarning("newTransTable failed for code %d, skipping", id)
1163 continue
1164 }
1165
1166 fmt.Fprintf(os.Stdout, "\t%d: ", id)
1167 if id < 10 {
1168 fmt.Fprintf(os.Stdout, " ")
1169 }
1170 for i := 0; i < 4096; i += 64 {
1171 if i > 0 {
1172 fmt.Fprintf(os.Stdout, "\t\t")
1173 }
1174 fmt.Fprintf(os.Stdout, "\"")
1175 for j := range 64 {
1176 aa := tb.aminoAcid[i+j]
1177 fmt.Fprintf(os.Stdout, "%c", aa)
1178 }
1179 fmt.Fprintf(os.Stdout, "\"")
1180 if i < 4032 {
1181 fmt.Fprintf(os.Stdout, " +")
1182 } else {
1183 fmt.Fprintf(os.Stdout, ",")
1184 }
1185 fmt.Fprintf(os.Stdout, "\n")
1186 }
1187 }
1188
1189 fmt.Fprintf(os.Stdout, "}\n")
1190
1191 /*
1192 // print codon to state table for reference
1193
1194 for _, ch1 := range upperToBase {
1195 for _, ch2 := range upperToBase {
1196 for _, ch3 := range upperToBase {
1197 st := SetCodonState(int(ch1), int(ch2), int(ch3))
1198 fmt.Fprintf(os.Stderr, "%c%c%c\t%d\n", ch1, ch2, ch3, st)
1199 }
1200 }
1201 }
1202 */
1203 }