-
Notifications
You must be signed in to change notification settings - Fork 8
/
align.go
2273 lines (2071 loc) · 69.3 KB
/
align.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 align
import (
"bytes"
"errors"
"fmt"
"log"
"math"
"math/rand"
"sort"
"strings"
"unicode"
"github.com/armon/go-radix"
"github.com/evolbioinfo/goalign/io"
)
// Alignment represents a set of aligned sequences (multiple Sequence Alignment)
type Alignment interface {
SeqBag
AddGaps(rate, lenprop float64)
Append(Alignment) error // Appends alignment sequences to this alignment
AvgAllelesPerSite() float64
BuildBootstrap(frac float64) Alignment // Bootstrap alignment
CharStatsSite(site int) (map[uint8]int, error)
Clone() (Alignment, error)
CodonAlign(ntseqs SeqBag) (codonAl *align, err error)
// Remove identical patterns/sites and return number of occurence
// of each pattern (order of patterns/sites may have changed)
Compress() []int
// concatenates the given alignment with this alignment
Concat(Alignment) error
// Computes the majority consensus of the given alignemnt
// To do so, it takes the majority character at each alignment site
// if ignoreGaps is true, then gaps are not taken into account for majority computation (except if only Gaps)
// if ignoreNs is true, then Ns are not taken into account for majority computation (except if only Ns)
Consensus(ignoreGaps, ignoreNs bool) *align
// Compares all sequences to the first one and counts all differences per sequence
//
// - alldiffs: The set of all differences that have been seen at least once
// - diffs : The number of occurences of each difference, for each sequence
// Sequences are ordered as the original alignment. Differences are
// written as REFNEW, ex: diffs["AC"]=12 .
CountDifferences() (alldiffs []string, diffs []map[string]int)
// Compares all sequences to the first one and replace identical characters with .
DiffWithFirst()
Entropy(site int, removegaps bool) (float64, error) // Entropy of the given site
// Positions of potential frameshifts
// if startinggapsasincomplete is true, then considers gaps as the beginning
// as incomplete sequence, then take the right phase
Frameshifts(startingGapsAsIncomplete bool) []struct{ Start, End int }
// Returns informative positions of the alignment. Informative positions
// are sites that contain at least two characters that occur at least twice each
// X, N and GAPS are not considered in this definition
InformativeSites() (sites []int)
// Positions of potential stop in frame
// if startinggapsasincomplete is true, then considers gaps as the beginning
// as incomplete sequence, then take the right phase
Stops(startingGapsAsIncomplete bool, geneticode int) (stops []int, err error)
Length() int // Length of the alignment
// maskreplace defines the replacing character. If maskreplace is "", then, masked characters
// are replaced by "N" or "X" depending on the alphabet. Orherwise:
// 1) if maskreplace is AMBIG: just like ""
// 2) if maskreplace is MAJ: Replacing character is most frequent character of the column
// 3) if maskreplace is GAP: Replacing character is a GAP
// if nogap is true, then Mask will not replace gaps with the replacement character
// if noref is true, then does not replace the character if it is the same as the reference sequences (only if refseq is specified).
Mask(refseq string, start, length int, maskreplace string, nogap, noref bool) error // Masks given positions
// Masks unique mutations in the given aligment (not the gaps).
// If refseq is not "" then masks unique characters if
// 1) they are different from the given reference sequence
// 2) or if the reference is a GAP
// maskreplace defines the replacing character. If maskreplace is "", then, masked characters
// are replaced by "N" or "X" depending on the alphabet. Orherwise:
// 1) if maskreplace is AMBIG: just like ""
// 2) if maskreplace is MAJ: Replacing character is most frequent character of the column
// 3) if maskreplace is GAP: Replacing character is a GAP
MaskUnique(refseq string, maskreplace string) error
// Masks mutations that appear less or equal than the given number of max occurences in their columns (not the gaps).
// If refseq is not "" then masks these characters if
// 1) they are different from the given reference sequence
// 2) or if the reference is a GAP
// maskreplace defines the replacing character. If maskreplace is "", then, masked characters
// are replaced by "N" or "X" depending on the alphabet. Orherwise:
// 1) if maskreplace is AMBIG: just like ""
// 2) if maskreplace is MAJ: Replacing character is most frequent character of the column
// 3) if maskreplace is GAP: Replacing character is a GAP
MaskOccurences(refseq string, maxOccurence int, maskreplace string) error
MaxCharStats(excludeGaps, excludeNs bool) (out []uint8, occur []int, total []int)
Mutate(rate float64) // Adds uniform substitutions in the alignment (~sequencing errors)
NbVariableSites() int // Nb of variable sites
// Number of Gaps in each sequence that are unique in their alignment site
NumGapsUniquePerSequence(countProfile *CountProfile) (numuniques []int, numnew []int, numboth []int, err error)
// returns the number of characters in each sequence that are unique in their alignment site (gaps or others)
// It does not take into account 'N' and '-' as unique mutations
NumMutationsUniquePerSequence(profile *CountProfile) (numuniques []int, numnew []int, nummuts []int, err error)
Pssm(log bool, pseudocount float64, normalization int) (pssm map[uint8][]float64, err error) // Normalization: PSSM_NORM_NONE, PSSM_NORM_UNIF, PSSM_NORM_DATA
Rarefy(nb int, counts map[string]int) (Alignment, error) // Take a new rarefied sample taking into accounts weights
RandSubAlign(length int, consecutive bool) (Alignment, error) // Extract a random subalignment with given length from this alignment
Recombine(rate float64, lenprop float64)
// converts coordinates on the given sequence to coordinates on the alignment
RefCoordinates(name string, refstart, refend int) (alistart, aliend int, err error)
// converts sites on the given sequence to coordinates on the alignment
RefSites(name string, sites []int) (refsites []int, err error)
// Removes sequences having >= cutoff gaps, returns number of removed sequences
RemoveGapSeqs(cutoff float64, ignoreNs bool) int
// Removes sequences having >= cutoff character, returns number of removed sequences
RemoveCharacterSeqs(c uint8, cutoff float64, ignoreCase, ignoreGaps, ignoreNs bool) int
// Removes sites having >= cutoff gaps, returns the number of consecutive removed sites at start and end of alignment
RemoveGapSites(cutoff float64, ends bool) (first, last int, kept, removed []int)
// Removes sites having >= cutoff character, returns the number of consecutive removed sites at start and end of alignment
RemoveCharacterSites(c uint8, cutoff float64, ends bool, ignoreCase, ignoreGaps, ignoreNs bool) (first, last int, kept, removed []int)
// Removes sites having >= cutoff of the main character at these sites, returns the number of consecutive removed sites at start and end of alignment
RemoveMajorityCharacterSites(cutoff float64, ends, ignoreGaps, ignoreNs bool) (first, last int, kept, removed []int)
// Replaces match characters (.) by their corresponding characters on the first sequence
ReplaceMatchChars()
Sample(nb int) (Alignment, error) // generate a sub sample of the sequences
ShuffleSites(rate float64, roguerate float64, randroguefirst bool) []string
SimulateRogue(prop float64, proplen float64) ([]string, []string) // add "rogue" sequences
SiteConservation(position int) (int, error) // If the site is conserved:
Split(part *PartitionSet) ([]Alignment, error) //Splits the alignment given the paritions in argument
SubAlign(start, length int) (Alignment, error) // Extract a subalignment from this alignment
SelectSites(sites []int) (Alignment, error) // Extract givens sites from the alignment
InverseCoordinates(start, length int) (invstarts, invlengths []int, err error)
InversePositions(sites []int) (invsites []int, err error)
Swap(rate float64)
Transpose() (Alignment, error) // Output sequences are made of sites and output sites are sequences
TrimSequences(trimsize int, fromStart bool) error
}
type align struct {
seqbag
length int // Length of alignment
}
// AlignChannel is used for iterating over alignments
type AlignChannel struct {
Achan chan Alignment
Err error
}
// NewAlign initializes a new alignment
func NewAlign(alphabet int) *align {
switch alphabet {
case AMINOACIDS, NUCLEOTIDS, UNKNOWN:
// OK
case BOTH:
alphabet = NUCLEOTIDS
default:
io.ExitWithMessage(errors.New("unexpected sequence alphabet type"))
}
return &align{
seqbag{
make(map[string]*seq),
make([]*seq, 0, 100),
IGNORE_NONE,
alphabet},
-1,
}
}
// AlphabetFromString converts the alphabet name to its code
// If the alphabet name is not known, returns align.UNKNOWN
func AlphabetFromString(alphabet string) int {
switch strings.ToLower(alphabet) {
case "dna", "rna", "nucleotide":
return NUCLEOTIDS
case "protein":
return AMINOACIDS
default:
return UNKNOWN
}
}
// AddSequence Adds a sequence to this alignment
func (a *align) AddSequence(name string, sequence string, comment string) error {
err := a.AddSequenceChar(name, []uint8(sequence), comment)
return err
}
// AddSequenceChar adds a sequence from its uint8 representation.
// If a.ignoreidentical is true, then it won't add the sequence if
// a sequence with the same name AND same sequence
// already exists in the alignment
func (a *align) AddSequenceChar(name string, sequence []uint8, comment string) error {
s, ok := a.seqmap[name]
idx := 0
tmpname := name
// If the sequence name already exists
// and ignoreidentical is true, then we ignore this sequence
if ok && a.ignoreidentical == IGNORE_NAME {
log.Print(fmt.Sprintf("Warning: sequence name \"%s\" already exists in alignment, ignoring", name))
return nil
}
// If the sequence name already exists with the same sequence
// and ignoreidentical is true, then we ignore this sequence
if ok && a.ignoreidentical == IGNORE_SEQUENCE && s.SameSequence(sequence) {
log.Print(fmt.Sprintf("Warning: sequence \"%s\" already exists in alignment with the same sequence, ignoring", name))
return nil
}
/* If the sequence name already exists, we add a 4 digit index at the end and print a warning on stderr */
for ok {
idx++
log.Print(fmt.Sprintf("Warning: sequence \"%s\" already exists in alignment, renamed in \"%s_%04d\"", tmpname, name, idx))
tmpname = fmt.Sprintf("%s_%04d", name, idx)
_, ok = a.seqmap[tmpname]
/*return errors.New("Sequence " + name + " already exists in alignment")*/
}
if a.length != -1 && a.length != len(sequence) {
return errors.New("Sequence " + tmpname + " does not have same length as other sequences")
}
a.length = len(sequence)
seq := NewSequence(tmpname, sequence, comment)
a.seqmap[tmpname] = seq
a.seqs = append(a.seqs, seq)
return nil
}
// Clear removes all the sequences from the alignment
func (a *align) Clear() {
a.seqbag.Clear()
a.length = -1
}
// Length returns the current length of the alignment
func (a *align) Length() int {
return a.length
}
// Shuffles vertically rate sites of the alignment
// randomly
// rate must be >=0 and <=1
// Then, take roguerate proportion of the taxa, and will shuffle rate sites among the
// remaining intact sites
// randroguefirst: If true, then with a given seed, rogues will always be the same with all alignments
// having sequences in the same order. It may not be the case if false, especially when alignemnts
// have different lengths.
// Output: List of tax names that are more shuffled than others (length=roguerate*nbsequences)
func (a *align) ShuffleSites(rate float64, roguerate float64, randroguefirst bool) []string {
var sitepermutation, taxpermutation []int
if rate < 0 || rate > 1 {
io.ExitWithMessage(errors.New("shuffle site rate must be >=0 and <=1"))
}
if roguerate < 0 || roguerate > 1 {
io.ExitWithMessage(errors.New("shuffle rogue rate must be >=0 and <=1"))
}
nbSitesToShuffle := int(rate * float64(a.Length()))
nbRogueSitesToShuffle := int(rate * (1.0 - rate) * (float64(a.Length())))
nbRogueSeqToShuffle := int(roguerate * float64(a.NbSequences()))
if randroguefirst {
taxpermutation = rand.Perm(a.NbSequences())
sitepermutation = rand.Perm(a.Length())
} else {
sitepermutation = rand.Perm(a.Length())
taxpermutation = rand.Perm(a.NbSequences())
}
rogues := make([]string, nbRogueSeqToShuffle)
if (nbRogueSitesToShuffle + nbSitesToShuffle) > a.Length() {
io.ExitWithMessage(fmt.Errorf("too many sites to shuffle (%d+%d>%d)",
nbRogueSitesToShuffle, nbSitesToShuffle, a.Length()))
}
var temp uint8
for i := 0; i < nbSitesToShuffle; i++ {
site := sitepermutation[i]
var n int = a.NbSequences()
for n > 1 {
r := rand.Intn(n)
n--
temp = a.seqs[n].sequence[site]
a.seqs[n].sequence[site] = a.seqs[r].sequence[site]
a.seqs[r].sequence[site] = temp
}
}
// We shuffle more sites for "rogue" taxa
for i := 0; i < nbRogueSitesToShuffle; i++ {
site := sitepermutation[i+nbSitesToShuffle]
for r := 0; r < nbRogueSeqToShuffle; r++ {
j := rand.Intn(r + 1)
seq1 := a.seqs[taxpermutation[r]]
seq2 := a.seqs[taxpermutation[j]]
seq1.sequence[site], seq2.sequence[site] = seq2.sequence[site], seq1.sequence[site]
rogues[r] = seq1.name
}
}
return rogues
}
// RemoveGapSites Removes positions constituted of [cutoff*100%,100%] Gaps
// Exception fo a cutoff of 0: does not remove positions with 0% gaps
// Cutoff must be between 0 and 1, otherwise set to 0.
// 0 means that positions with > 0 gaps will be removed
// other cutoffs : ]0,1] mean that positions with >= cutoff gaps will be removed
//
// If ends is true: then only removes consecutive positions that match the cutoff
// from start or from end of alignment.
// Example with a cutoff of 0.3 and ends and with the given proportion of gaps:
// 0.4 0.5 0.1 0.5 0.6 0.1 0.8 will remove positions 0,1 and 6
//
// Returns the number of consecutive removed sites at start and end of alignment and the indexes of
// the remaining positions
func (a *align) RemoveGapSites(cutoff float64, ends bool) (first, last int, kept, rm []int) {
return a.RemoveCharacterSites(GAP, cutoff, ends, false, false, false)
}
// RemoveCharacterSites Removes positions constituted of [cutoff*100%,100%] of the given character
// Exception fo a cutoff of 0: does not remove positions with 0% of this character
// Cutoff must be between 0 and 1, otherwise set to 0.
// 0 means that positions with > 0 of the given character will be removed
// other cutoffs : ]0,1] mean that positions with >= cutoff of this character will be removed
//
// if ignoreCase then the search is case insensitive
// if ignoreGaps then gaps are ignored in the % computation
// if ignoreNs then N/n/X/x (depending on alphabet) are ignored in the % computation
//
// If ends is true: then only removes consecutive positions that match the cutoff
// from start or from end of alignment.
// Example with a cutoff of 0.3 and ends and with the given proportion of this character:
// 0.4 0.5 0.1 0.5 0.6 0.1 0.8 will remove positions 0,1 and 6
//
// Returns the number of consecutive removed sites at start and end of alignment and the indexes of
// the remaining positions
func (a *align) RemoveCharacterSites(c uint8, cutoff float64, ends bool, ignoreCase, ignoreGaps, ignoreNs bool) (first, last int, kept, rm []int) {
var nbchars int
var total int
kept = make([]int, 0)
rm = make([]int, 0)
if cutoff < 0 || cutoff > 1 {
cutoff = 0
}
toremove := make([]int, 0, a.Length())
// To remove only positions with this character at start and ends positions
firstcontinuous := -1
lastcontinuous := a.Length()
lenBk := a.Length()
all := ALL_AMINO
if a.Alphabet() == AMINOACIDS {
all = ALL_NUCLE
}
allc := unicode.ToLower(all)
//log.Println("Before computing toremove")
for site := 0; site < a.Length(); site++ {
nbchars = 0
total = 0
for seq := 0; seq < a.NbSequences(); seq++ {
if (a.seqs[seq].sequence[site] == c) || (ignoreCase && unicode.ToLower(rune(a.seqs[seq].sequence[site])) == unicode.ToLower(rune(c))) {
nbchars++
}
// If it's a gap and we ignore gaps, or if it's a N and we ignore N, then we do not count that
// nt/aa in the total
if !((ignoreGaps && a.seqs[seq].sequence[site] == GAP) ||
(ignoreNs && (a.seqs[seq].sequence[site] == uint8(all) || a.seqs[seq].sequence[site] == uint8(allc)))) {
total++
}
}
if (cutoff > 0.0 && float64(nbchars) >= cutoff*float64(total)) || (cutoff == 0 && nbchars > 0) {
toremove = append(toremove, site)
if site == firstcontinuous+1 {
firstcontinuous++
}
if lastcontinuous == a.Length() {
lastcontinuous = site
}
} else {
lastcontinuous = a.Length()
}
}
//log.Println("Before removing")
/* Now we remove positions */
sort.Ints(toremove)
nbremoved := 0
for seq := 0; seq < a.NbSequences(); seq++ {
nbremoved = 0
nbpotentialremove := 0
newseq := make([]uint8, 0, a.Length()-len(toremove))
for i := 0; i < a.Length(); i++ {
removed := (nbpotentialremove < len(toremove) && i == toremove[nbpotentialremove])
if removed {
nbpotentialremove++
}
if removed && (!ends || i >= lastcontinuous || i <= firstcontinuous) {
nbremoved++
if seq == 0 {
// We do that once for first sequence (all removed sites are the same for all sequences)
rm = append(rm, i)
}
} else {
newseq = append(newseq, a.seqs[seq].sequence[i])
if seq == 0 {
// We do that once for first sequence (all removed sites are the same for all sequences)
kept = append(kept, i)
}
}
}
a.seqs[seq].sequence = newseq
}
a.length -= nbremoved
//log.Println("Done")
return firstcontinuous + 1, lenBk - lastcontinuous, kept, rm
}
// RemoveMajorityCharacterSites Removes positions constituted of [cutoff*100%,100%] of the most
// abundant character in these sites.
// Exception fo a cutoff of 0: does not remove positions with 0% of the most abundant character
// Cutoff must be between 0 and 1, otherwise set to 0.
// 0 means that positions with > 0 of the given character will be removed
// other cutoffs : ]0,1] mean that positions with >= cutoff of the most abundant character will be removed
//
// If ends is true: then only removes consecutive positions that match the cutoff
// from start or from end of alignment.
// Example with a cutoff of 0.3 and ends and with the given proportion of this character:
// 0.4 0.5 0.1 0.5 0.6 0.1 0.8 will remove positions 0,1 and 6
//
// Returns the number of consecutive removed sites at start and end of alignment and the indexes of the
// remaining positions
func (a *align) RemoveMajorityCharacterSites(cutoff float64, ends, ignoreGaps, ignoreNs bool) (first, last int, kept, rm []int) {
_, occur, total := a.MaxCharStats(ignoreGaps, ignoreNs)
kept = make([]int, 0)
rm = make([]int, 0)
length := a.Length()
toremove := make([]int, 0, 10)
// To remove only positions with this character at start and ends positions
firstcontinuous := -1
lastcontinuous := a.Length()
for site := 0; site < length; site++ {
if (cutoff > 0.0 && float64(occur[site]) >= cutoff*float64(total[site])) || (cutoff == 0 && occur[site] > 0) {
toremove = append(toremove, site)
if site == firstcontinuous+1 {
firstcontinuous++
}
if lastcontinuous == a.Length() {
lastcontinuous = site
}
} else {
lastcontinuous = a.Length()
}
}
/* Now we remove positions */
sort.Ints(toremove)
nbremoved := 0
for seq := 0; seq < a.NbSequences(); seq++ {
nbremoved = 0
nbpotentialremove := 0
newseq := make([]uint8, 0, a.Length()-len(toremove))
for i := 0; i < a.Length(); i++ {
removed := (nbpotentialremove < len(toremove) && i == toremove[nbpotentialremove])
if removed {
nbpotentialremove++
}
if removed && (!ends || i >= lastcontinuous || i <= firstcontinuous) {
nbremoved++
if seq == 0 {
// We do that once for first sequence (all removed sites are the same for all sequences)
rm = append(rm, i)
}
} else {
newseq = append(newseq, a.seqs[seq].sequence[i])
if seq == 0 {
// We do that once for first sequence (all removed sites are the same for all sequences)
kept = append(kept, i)
}
}
}
a.seqs[seq].sequence = newseq
}
a.length -= nbremoved
return firstcontinuous + 1, length - lastcontinuous, kept, rm
}
// RefCoordinates converts coordinates on the given sequence to coordinates on the alignment.
// Coordinates on the given sequence corresponds to the sequence without gaps. Output coordinates
// on the alignent consider gaps.
//
// It returns an error if the sequence does not exist or if the coordinates are outside the ref
// sequence (<0 or > sequence length without gaps)
// Parameters:
// - name: The name of the sequence to take as reference
// - refstart: The start coordinate to convert (on the ref sequence, 0-based)
// - reflen: The length of the ref sequence to consider from refstart
func (a *align) RefCoordinates(name string, refstart, reflen int) (alistart, alilen int, err error) {
var exists bool
var seq []uint8
var tmpi int
var site uint8
var ngaps int
if seq, exists = a.GetSequenceChar(name); !exists {
err = fmt.Errorf("sequence %s does not exist in the alignment", name)
return
}
if refstart < 0 {
err = fmt.Errorf("start on reference sequence must be > 0 : %d", refstart)
return
}
if reflen <= 0 {
err = fmt.Errorf("reference length must be > 0 : %d", reflen)
return
}
alistart = 0
alilen = 0
//look for start
tmpi = -1
for _, site = range seq {
if site != GAP {
tmpi++
} else {
ngaps++
}
if tmpi < refstart {
alistart++
} else {
alilen++
if tmpi >= refstart+reflen-1 {
break
}
}
}
if refstart+reflen > len(seq)-ngaps {
err = fmt.Errorf("start + Length (%d + %d) on reference sequence falls outside the sequence", refstart, reflen)
}
return
}
// RefSites converts coordinates on the given sequence to coordinates on the alignment.
// Coordinates on the given sequence corresponds to the sequence without gaps. Output coordinates
// on the alignent consider gaps.
//
// It returns an error if the sequence does not exist or if the coordinates are outside the ref
// sequence (<0 or > sequence length without gaps)
// Parameters:
// - name: The name of the sequence to take as reference
// - sites: The positions to convert (on the ref sequence, 0-based)
func (a *align) RefSites(name string, sites []int) (refsites []int, err error) {
var exists bool
var seq []uint8
var tmpi int
var site uint8
var ngaps int
var isite int
if seq, exists = a.GetSequenceChar(name); !exists {
err = fmt.Errorf("Sequence %s does not exist in the alignment", name)
return
}
mappos := make(map[int]bool)
for _, s := range sites {
if s < 0 {
err = fmt.Errorf("site on reference sequence must be > 0 : %d", s)
return
}
if s >= a.Length() {
err = fmt.Errorf("site is outside alignment : %d", s)
return
}
mappos[s] = true
}
//look for start
tmpi = -1
for isite, site = range seq {
if site != GAP {
tmpi++
if _, ok := mappos[tmpi]; ok {
refsites = append(refsites, isite)
}
} else {
ngaps++
}
}
return
}
// Removes sequences constituted of [cutoff*100%,100%] Gaps
// Exception fo a cutoff of 0: does not remove sequences with 0% gaps
// Cutoff must be between 0 and 1, otherwise set to 0.
// 0 means that sequences with > 0 gaps will be removed
// other cutoffs : ]0,1] mean that sequences with >= cutoff gaps will be removed
//
// Returns the number of removed sequences
func (a *align) RemoveGapSeqs(cutoff float64, ignoreNs bool) int {
return a.RemoveCharacterSeqs(GAP, cutoff, false, false, ignoreNs)
}
// RemoveCharacterSeqs Removes sequences constituted of [cutoff*100%,100%] of the given character
// Exception fo a cutoff of 0: does not remove sequences with 0% of this character
// Cutoff must be between 0 and 1, otherwise set to 0.
// 0 means that sequences with > 0 of the given character will be removed
// other cutoffs : ]0,1] mean that positions with >= cutoff of this character will be removed
//
// if ignoreCase then the search is case insensitive
// if ignoreGaps is true, then gaps are not taken into account
// if ignoreNs is true, then Ns are not taken into account
//
// Returns the number of removed sequences
func (a *align) RemoveCharacterSeqs(c uint8, cutoff float64, ignoreCase, ignoreGaps, ignoreNs bool) int {
var nbseqs int
var total int
if cutoff < 0 || cutoff > 1 {
cutoff = 0
}
oldseqs := a.seqs
length := a.Length()
a.Clear()
nbremoved := 0
all := uint8(ALL_NUCLE)
if a.Alphabet() == AMINOACIDS {
all = uint8(ALL_AMINO)
}
allc := uint8(unicode.ToLower(rune(all)))
for _, seq := range oldseqs {
nbseqs = 0
total = 0
for site := 0; site < length; site++ {
if (seq.sequence[site] == c) || (ignoreCase && unicode.ToLower(rune(seq.sequence[site])) == unicode.ToLower(rune(c))) {
nbseqs++
}
// If we exclude gaps and it is a gap: we do nothing
// or if we exclude Ns and it is a N: we do nothing
if !(ignoreGaps && seq.sequence[site] == uint8(GAP)) && !(ignoreNs && (seq.sequence[site] == all || seq.sequence[site] == allc)) {
total++
}
}
if (cutoff > 0.0 && float64(nbseqs) >= cutoff*float64(total)) || (cutoff == 0 && nbseqs > 0) {
nbremoved++
} else {
a.AddSequenceChar(seq.name, seq.sequence, seq.comment)
}
}
return nbremoved
}
// Swaps a rate of the sequences together
// takes rate/2 seqs and swap a part of them with the other
// rate/2 seqs at a random position
// if rate < 0 : does nothing
// if rate > 1 : does nothing
func (a *align) Swap(rate float64) {
var nb_to_shuffle, nb_sites int
var pos int
var tmpchar uint8
var seq1, seq2 *seq
if rate < 0 || rate > 1 {
return
}
nb_sites = a.Length()
nb_to_shuffle = (int)(rate * float64(a.NbSequences()))
permutation := rand.Perm(a.NbSequences())
for i := 0; i < int(nb_to_shuffle/2); i++ {
// We take a random position in the sequences and swap both
pos = rand.Intn(nb_sites)
seq1 = a.seqs[permutation[i]]
seq2 = a.seqs[permutation[i+(int)(nb_to_shuffle/2)]]
for pos < nb_sites {
tmpchar = seq1.sequence[pos]
seq1.sequence[pos] = seq2.sequence[pos]
seq2.sequence[pos] = tmpchar
pos++
}
}
}
// Replace an old string in sequences by a new string
// It may be a regexp
//
// - If it changes the length of the sequences, then returns an error and the returned alignment
// is changed anyway
// - If the regex is malformed, returns an error
func (a *align) Replace(old, new string, regex bool) (err error) {
if err = a.seqbag.Replace(old, new, regex); err != nil {
return
}
// Verify that sequences still have same length
a.IterateChar(func(name string, s []uint8) bool {
if len(s) != a.Length() {
err = fmt.Errorf("replace should not change the length of aligned sequences")
return true
}
return false
})
return
}
// Replaces match characters (.) by their corresponding characters on the first sequence
//
// If the correspongind character in the first sequence is also a ".", then leaves it unchanged.
func (a *align) ReplaceMatchChars() {
if a.NbSequences() <= 1 {
return
}
ref := a.seqs[0]
for seq := 1; seq < a.NbSequences(); seq++ {
for site := 0; site < a.Length(); site++ {
if ref.sequence[site] != POINT && a.seqs[seq].sequence[site] == POINT {
a.seqs[seq].sequence[site] = ref.sequence[site]
}
}
}
}
// Translates the alignment, and update the length of
// the alignment
func (a *align) Translate(phase int, geneticcode int) (err error) {
err = a.seqbag.Translate(phase, geneticcode)
if len(a.seqs) > 0 {
a.length = len(a.seqs[0].sequence)
} else {
a.length = -1
}
return
}
// Recombines a rate of the sequences to another sequences
// takes rate/2 seqs and copy/paste a portion of them to the other
// rate/2 seqs at a random position
// if rate < 0 : does nothing
// if rate > 1 : does nothing
// prop must be <= 0.5 because it will recombine x% of seqs based on other x% of seqs
func (a *align) Recombine(prop float64, lenprop float64) {
var seq1, seq2 *seq
if prop < 0 || prop > 0.5 {
return
}
if lenprop < 0 || lenprop > 1 {
return
}
nb := int(prop * float64(a.NbSequences()))
lentorecomb := int(lenprop * float64(a.Length()))
permutation := rand.Perm(a.NbSequences())
// We take a random position in the sequences between min and max
for i := 0; i < nb; i++ {
pos := rand.Intn(a.Length() - lentorecomb + 1)
seq1 = a.seqs[permutation[i]]
seq2 = a.seqs[permutation[i+nb]]
for j := pos; j < pos+lentorecomb; j++ {
seq1.sequence[j] = seq2.sequence[j]
}
}
}
// Add prop*100% gaps to lenprop*100% of the sequences
// if prop < 0 || lenprop<0 : does nothing
// if prop > 1 || lenprop>1 : does nothing
func (a *align) AddGaps(lenprop float64, prop float64) {
if prop < 0 || prop > 1 {
return
}
if lenprop < 0 || lenprop > 1 {
return
}
nb := int(prop * float64(a.NbSequences()))
nbgaps := int(lenprop * float64(a.Length()))
permseqs := rand.Perm(a.NbSequences())
// We take a random position in the sequences between min and max
for i := 0; i < nb; i++ {
permsites := rand.Perm(a.Length())
seq := a.seqs[permseqs[i]]
for j := 0; j < nbgaps; j++ {
seq.sequence[permsites[j]] = GAP
}
}
}
func (a *align) Append(al Alignment) (err error) {
al.IterateAll(func(name string, sequence []uint8, comment string) bool {
err = a.AddSequenceChar(name, sequence, comment)
return err != nil
})
return
}
// Add substitutions uniformly to the alignment
// if rate < 0 : does nothing
// if rate > 1 : rate=1
// It does not apply to gaps or other special characters
func (a *align) Mutate(rate float64) {
if rate <= 0 {
return
}
if rate > 1 {
rate = 1
}
r := 0.0
newchar := 0
leng := a.Length()
nb := a.NbSequences()
// We take a random position in the sequences between min and max
for i := 0; i < nb; i++ {
seq := a.seqs[i]
for j := 0; j < leng; j++ {
r = rand.Float64()
// We mutate only if rand is <= rate && character is not a gap
// or a special character.
// It takes a random nucleotide or amino acid uniformly
if r <= rate && seq.sequence[j] != GAP && seq.sequence[j] != POINT && seq.sequence[j] != OTHER {
if a.Alphabet() == AMINOACIDS {
newchar = rand.Intn(len(stdaminoacid))
seq.sequence[j] = stdaminoacid[newchar]
} else {
newchar = rand.Intn(len(stdnucleotides))
seq.sequence[j] = stdnucleotides[newchar]
}
}
}
}
}
// Simulate rogue taxa in the alignment:
// take the proportion prop of sequences as rogue taxa => R
// For each t in R
// * We shuffle the alignment sites of t
// Output: List of rogue sequence names, and List of intact sequence names
func (a *align) SimulateRogue(prop float64, proplen float64) ([]string, []string) {
var seq *seq
if prop < 0 || prop > 1.0 {
return nil, nil
}
if proplen < 0 || proplen > 1.0 {
return nil, nil
}
if proplen == 0 {
prop = 0.0
}
nb := int(prop * float64(a.NbSequences()))
permutation := rand.Perm(a.NbSequences())
seqlist := make([]string, nb)
intactlist := make([]string, a.NbSequences()-nb)
len := int(proplen * float64(a.Length()))
// For each chosen rogue sequence
for r := 0; r < nb; r++ {
seq = a.seqs[permutation[r]]
seqlist[r] = seq.name
sitesToShuffle := rand.Perm(a.Length())[0:len]
// we Shuffle some sequence sites
for i := range sitesToShuffle {
j := rand.Intn(i + 1)
seq.sequence[sitesToShuffle[i]], seq.sequence[sitesToShuffle[j]] = seq.sequence[sitesToShuffle[j]], seq.sequence[sitesToShuffle[i]]
}
}
for nr := nb; nr < a.NbSequences(); nr++ {
seq = a.seqs[permutation[nr]]
intactlist[nr-nb] = seq.name
}
return seqlist, intactlist
}
// Trims alignment sequences.
// If fromStart, then trims from the start, else trims from the end
// If trimsize >= sequence or trimsize < 0 lengths, then throw an error
func (a *align) TrimSequences(trimsize int, fromStart bool) error {
if trimsize < 0 {
return errors.New("trim size must not be < 0")
}
if trimsize >= a.Length() {
return errors.New("Trim size must be < alignment length (" + fmt.Sprintf("%d", a.Length()) + ")")
}
for _, seq := range a.seqs {
if fromStart {
seq.sequence = seq.sequence[trimsize:len(seq.sequence)]
} else {
seq.sequence = seq.sequence[0 : len(seq.sequence)-trimsize]
}
}
a.length = a.length - trimsize
return nil
}
// Samples randomly a subset of the sequences
// And returns this new alignment
// If nb < 1 or nb > nbsequences returns nil and an error
func (a *align) Sample(nb int) (al Alignment, err error) {
var sampleSeqBag *seqbag
var ali *align
if sampleSeqBag, err = a.sampleSeqBag(nb); err != nil {
return
}
if ali, err = seqBagToAlignment(sampleSeqBag); err != nil {
return
}
al = ali
return
}
/*
Each sequence in the alignment has an associated number of occurence. The sum s of the counts
represents the number of sequences in the underlying initial dataset.
The goal is to downsample (rarefy) the initial dataset, by sampling n sequences
from s (n<s), and taking the alignment corresponding to this new sample, i.e by
taking only unique (different) sequences from it.
Parameters are:
* nb: the number of sequences to sample from the underlying full dataset (different
from the number of sequences in the output alignment)
* counts: counts associated to each sequence (if the count of a sequence is missing, it
is considered as 0, if the count of an unkown sequence is present, it will return an error).
Sum of counts of all sequences must be > n.
*/
func (a *align) Rarefy(nb int, counts map[string]int) (al Alignment, err error) {
var rarefySeqBag *seqbag
var ali *align
if rarefySeqBag, err = a.rarefySeqBag(nb, counts); err != nil {
return
}
if ali, err = seqBagToAlignment(rarefySeqBag); err != nil {
return
}
al = ali
return
}
// BuildBootstrap builds a bootstrap alignment
// if frac is < 1.0, it is a partial bootstrap as is phylip seqboot,
// which means that the sites are sampled from the full alignment with
// replacement, but the output alignment length is a fraction of the
// original alignment.
// (see https://evolution.genetics.washington.edu/phylip/doc/seqboot.html)
func (a *align) BuildBootstrap(frac float64) (boot Alignment) {
if frac <= 0 || frac > 1 {
frac = 1.0
}
alength := a.Length()
n := int(frac * float64(alength))
boot = NewAlign(a.alphabet)
indices := make([]int, n)
var buf []uint8
for i := 0; i < n; i++ {
indices[i] = rand.Intn(alength)
}
for _, seq := range a.seqs {
buf = make([]uint8, n)
for i, indice := range indices {
buf[i] = seq.sequence[indice]
}
boot.AddSequenceChar(seq.name, buf, seq.Comment())
}
return
}
// Returns the distribution of characters at a given site
// if the site index is outside alignment, returns an error
func (a *align) CharStatsSite(site int) (outmap map[uint8]int, err error) {
outmap = make(map[uint8]int)