-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseq_stat_2pop.cpp
1316 lines (1121 loc) · 46.2 KB
/
seq_stat_2pop.cpp
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
/**
g++ -g /home/benoitnabholz/Progr/C++/popgen/seq_stat_2pop/seq_stat_2pop.cpp -o ./seq_stat_2pop \
-DVIRTUAL_COV=yes -Wall \
-I$HOME/local/bpp/dev/include -L$HOME/local/bpp/dev/lib64 \
-lbpp-popgen -lbpp-phyl -lbpp-seq -lbpp-core
g++ --static -std=c++14 -g ~/pCloudDrive/Progr/C++/popgen/seq_stat_2pop/seq_stat_2pop.cpp -o ~/bin/seq_stat_2pop -DVIRTUAL_COV=yes -Wall -I$HOME/local/bpp/dev/include -L$HOME/local/bpp/dev/lib -lbpp-phyl -lbpp-popgen -lbpp-seq -lbpp-core -Wdeprecated
strip ~/bin/seq_stat_2pop
g++ --static -std=c++14 -g ~/pCloudDrive/Progr/C++/popgen/seq_stat_2pop/seq_stat_2pop.cpp -o ~/bin/seq_stat_2pop -DVIRTUAL_COV=yes -Wall -lbpp-phyl -lbpp-popgen -lbpp-seq -lbpp-core -Wdeprecated
strip ~/bin/seq_stat_2pop
*
**/
#include <Bpp/Seq/Site.h>
#include <Bpp/Seq/SiteTools.h>
#include <Bpp/Seq/StringSequenceTools.h>
#include <Bpp/Seq/CodonSiteTools.h>
#include <Bpp/Seq/Alphabet/DNA.h>
#include <Bpp/Seq/Alphabet/AlphabetTools.h>
#include <Bpp/Seq/Container/SiteContainerIterator.h>
#include <Bpp/Seq/Alphabet/AlphabetTools.h>
#include <Bpp/Seq/Sequence.h>
#include <Bpp/Seq/SequenceTools.h>
#include <Bpp/Seq/Container/SiteContainerIterator.h>
#include <Bpp/Seq/CodonSiteTools.h>
#include <Bpp/Seq/GeneticCode/StandardGeneticCode.h>
#include <Bpp/Seq/Container/VectorSequenceContainer.h>
#include <Bpp/Seq/Io/Fasta.h>
#include <Bpp/Seq/Io/Phylip.h>
#include <Bpp/Seq/Container/SiteContainerIterator.h>
#include <Bpp/PopGen/SequenceStatistics.h>
#include <Bpp/PopGen/PolymorphismSequenceContainerTools.h>
#include <Bpp/PopGen/PolymorphismSequenceContainer.h>
#include <Bpp/Numeric/VectorTools.h>
#include <unistd.h>
#include <cstdlib>
#include <cmath>
#include <iostream>
using namespace std;
using namespace bpp;
/********************************************************************/
bool isSeqGapOrUnresolvedOnly(const Sequence& seq)
{
// Main loop : for all characters in site
for (unsigned int i = 0; i < seq.size(); i++)
{
if (!(seq.getAlphabet()->isGap(seq[i]) || seq.getAlphabet()->isUnresolved(seq[i]))) return false;
}
return true;
}
/********************************************************************/
bool hasGapOrUnresolvedOnly2(const Site& site)
{
// Main loop : for all characters in site
for (unsigned int i = 0; i < site.size(); i++)
{
if (site.getAlphabet()->isGap(site[i]) || site.getAlphabet()->isUnresolved(site[i])) return true;
}
return false;
}
/************************************************************************************************/
double varTajima83(const PolymorphismSequenceContainer& psc)
{
unsigned int n = psc.getNumberOfSequences();
vector <double> vpi;
for(unsigned int i = 0; i < n; i++){
for(unsigned int j = i; j < n; j++){
if(i == j)
continue;
PolymorphismSequenceContainer * tmpPsc = new PolymorphismSequenceContainer(psc.getAlphabet());
tmpPsc->addSequence(psc.getSequence(i));
tmpPsc->addSequence(psc.getSequence(j));
vpi.push_back(SequenceStatistics::tajima83( *tmpPsc, true ) / double (PolymorphismSequenceContainerTools::getNumberOfCompleteSites(*tmpPsc, false)));
delete tmpPsc;
}
}
return VectorTools::var<double, double>(vpi);
}
/******************************************************************************/
double meanNumberOfSynonymousPositions2(const Site & site, const GeneticCode & gc, double ratio)
throw (AlphabetException, AlphabetMismatchException, EmptySiteException)
{
//Alphabet checking
if(!AlphabetTools::isCodonAlphabet(site.getAlphabet()))
throw AlphabetException("CodonSiteTools::meanNumberOfSynonymousPositions: alphabet is not CodonAlphabet", site.getAlphabet());
if(site.getAlphabet()->getAlphabetType() != gc.getSourceAlphabet()->getAlphabetType())
throw AlphabetMismatchException("CodonSiteTools::meanNumberOfSynonymousPositions: site and genetic code have not the same codon alphabet.", site.getAlphabet(), gc.getSourceAlphabet());
//Empty site checking
if(site.size() == 0)
throw EmptySiteException("CodonSiteTools::meanNumberOfSynonymousPositions: Incorrect specified site", &site);
//Computation
double NbSyn=0;
map<int,double> freq;
SiteTools::getFrequencies(site, freq);
for(map<int,double>::iterator it = freq.begin(); it != freq.end(); it++)
{
NbSyn += (it->second)*CodonSiteTools::numberOfSynonymousPositions(it->first, gc, ratio);
}
return NbSyn;
}
/******************************************************************************/
double meanSynonymousSitesNumber2(const PolymorphismSequenceContainer& psc, const GeneticCode& gc, double ratio, bool gapflag)
{
double S = 0.;
ConstSiteIterator* si = NULL;
if (gapflag)
si = new CompleteSiteContainerIterator(psc);
else
si = new SimpleSiteContainerIterator(psc);
const Site* site = 0;
while(si->hasMoreSites()) {
site = si->nextSite();
// creat a site without gap or unresolved site
Site siteSg = Site(site->getAlphabet());
for(unsigned int s = 0; s < site->size(); s++){
if (!site->getAlphabet()->isGap(site->getValue(s)) && !site->getAlphabet()->isUnresolved(site->getValue(s)))
siteSg.addElement(site->getValue(s));
}
S += CodonSiteTools::meanNumberOfSynonymousPositions(siteSg, gc, ratio);
}
delete si;
return S;
}
/******************************************************************************/
bool isSynonymousPolymorphic2(const Site & site, const GeneticCode & gc)
throw (AlphabetException, AlphabetMismatchException, EmptySiteException)
{
//Alphabet checking
if(!AlphabetTools::isCodonAlphabet(site.getAlphabet()))
throw AlphabetException("CodonSiteTools::isSynonymousPolymorphic: alphabet is not CodonAlphabet", site.getAlphabet());
if(site.getAlphabet()->getAlphabetType() != gc.getSourceAlphabet()->getAlphabetType())
throw AlphabetMismatchException("CodonSiteTools::isSynonymousPolymorphic: site and genetic code have not the same codon alphabet.", site.getAlphabet(), gc.getSourceAlphabet());
//Empty site checking
if(site.size() == 0)
throw EmptySiteException("CodonSiteTools::isSynonymousPolymorphic: Incorrect specified site", &site);
// Global polymorphism checking
if (SiteTools::isConstant(site)) return false;
// Synonymous polymorphism checking
vector<int> prot;
int first_aa = -1;
for(unsigned int i = 0; i < site.size(); i++) {
if(site.getAlphabet()->isUnresolved(site[i]) || site.getAlphabet()->isGap(site[i])){
continue;
}
if(first_aa == -1){
first_aa = gc.translate(site[i]);
continue;
}
int aa = gc.translate(site[i]);
if (aa != first_aa) return false;
}
return true;
}
/******************************************************************************/
/** in CodonSiteTools **/
double piSynonymous3(const Site & site, const GeneticCode & gc, bool minchange)
throw (AlphabetException, AlphabetMismatchException, EmptySiteException)
{
//Alphabet checking
if(!AlphabetTools::isCodonAlphabet(site.getAlphabet()))
throw AlphabetException("CodonSiteTools::piSynonymous: alphabet is not CodonAlphabet", site.getAlphabet());
if(site.getAlphabet()->getAlphabetType() != gc.getSourceAlphabet()->getAlphabetType())
throw AlphabetMismatchException("CodonSiteTools::piSynonymous3: site and genetic code have not the same codon alphabet.", site.getAlphabet(), gc.getSourceAlphabet());
//Empty site checking
if(site.size() == 0)
throw EmptySiteException("CodonSiteTools::piSynonymous3: Incorrect specified site", &site);
//General polymorphism checking
if (SiteTools::isConstant(site)) return 0;
//Computation
map<int,double> freq;
SiteTools::getFrequencies(site, freq);
double pi = 0;
for(map<int,double>::iterator it1 = freq.begin(); it1 != freq.end(); it1++)
{
for(map<int,double>::iterator it2 = freq.begin(); it2 != freq.end(); it2++) {
//if(site.getAlphabet()->isUnresolved(it2 -> first) || site.getAlphabet()->isGap(it2 -> first) || site.getAlphabet()->isUnresolved(it1 -> first) || site.getAlphabet()->isGap(it1 -> first)){
//continue;
//}
pi += (it1 -> second) * (it2 -> second) * (CodonSiteTools::numberOfSynonymousDifferences(it1->first,it2->first,gc,minchange));
}
}
unsigned int n = site.size();
return pi * n / (n - 1);
}
/******************************************************************************/
/******************************************************************************/
/** in CodonSiteTools **/
double piNonSynonymous3(const Site & site, const GeneticCode & gc, bool minchange)
throw (AlphabetException, AlphabetMismatchException, EmptySiteException)
{
//Alphabet checking
if(!AlphabetTools::isCodonAlphabet(site.getAlphabet()))
throw AlphabetException("CodonSiteTools::piNonSynonymous3: alphabet is not CodonAlphabet", site.getAlphabet());
if(site.getAlphabet()->getAlphabetType() != gc.getSourceAlphabet()->getAlphabetType())
throw AlphabetMismatchException("CodonSiteTools::piNonSynonymous3: site and genetic code have not the same codon alphabet.", site.getAlphabet(), gc.getSourceAlphabet());
//Empty site checking
if(site.size() == 0)
throw EmptySiteException("CodonSiteTools::piNonSynonymous3: Incorrect specified site", &site);
//General polymorphism checking
if(SiteTools::isConstant(site)) return 0;
if(isSynonymousPolymorphic2(site,gc)) return 0;
//Computation
map<int,double> freq;
CodonSiteTools::getFrequencies(site, freq);
const CodonAlphabet * ca = dynamic_cast<const CodonAlphabet *>(site.getAlphabet());
double pi = 0;
for(map<int,double>::iterator it1 = freq.begin(); it1 != freq.end(); it1++) {
for(map<int,double>::iterator it2 = freq.begin(); it2 != freq.end(); it2++) {
/** manual modification here **/
//if(site.getAlphabet()->isUnresolved(it2 -> first) || site.getAlphabet()->isGap(it2 -> first) || site.getAlphabet()->isUnresolved(it1 -> first) || site.getAlphabet()->isGap(it1 -> first)){
// continue;
//}
unsigned int nbtot = CodonSiteTools::numberOfDifferences(it1->first,it2->first, *ca);
double nbsyn = CodonSiteTools::numberOfSynonymousDifferences(it1->first, it2 -> first, gc, minchange);
pi += (it1 -> second) * (it2 -> second) * (nbtot - nbsyn);
}
}
unsigned int n = site.size();
return pi * n / (n - 1);
}
/******************************************************************************/
/** in SequenceStatistics **/
double piSynonymous2(const PolymorphismSequenceContainer& psc, const GeneticCode& gc, bool minchange, bool gapflag)
{
double S = 0.;
ConstSiteIterator* si = 0;
if (gapflag)
si = new CompleteSiteContainerIterator(psc);
else
si = new SimpleSiteContainerIterator(psc);
const Site* site = 0;
while(si->hasMoreSites()) {
site = si->nextSite();
// creat a site without gap or unresolved site
Site siteSg = Site(site->getAlphabet());
for(unsigned int s = 0; s < site->size(); s++){
if (!site->getAlphabet()->isGap(site->getValue(s)) && !site->getAlphabet()->isUnresolved(site->getValue(s)))
siteSg.addElement(site->getValue(s));
}
S += piSynonymous3(siteSg, gc, minchange);
}
delete si;
return S;
}
/******************************************************************************/
/** SequenceStatistics **/
double piNonSynonymous2(const PolymorphismSequenceContainer& psc, const GeneticCode& gc, bool minchange, bool gapflag)
{
double S = 0.;
ConstSiteIterator* si = 0;
if (gapflag)
si = new CompleteSiteContainerIterator(psc);
else
si = new SimpleSiteContainerIterator(psc);
const Site* site = 0;
while(si->hasMoreSites()) {
site = si->nextSite();
// creat a site without gap or unresolved site
Site siteSg = Site(site->getAlphabet());
for(unsigned int s = 0; s < site->size(); s++){
if (!site->getAlphabet()->isGap(site->getValue(s)) && !site->getAlphabet()->isUnresolved(site->getValue(s)))
siteSg.addElement(site->getValue(s));
}
S += piNonSynonymous3(siteSg, gc, minchange);
}
delete si;
return S;
}
/******************************************************************************/
bool isSingleton(const Site& site) {
bool sing = false;
map<int, unsigned long int> states_count;
SymbolListTools::getCounts(site, states_count);
for (map<int, unsigned long int>::iterator it = states_count.begin() ; it != states_count.end() ; it++)
{
if(site.getAlphabet()->isUnresolved(it->first) || site.getAlphabet()->isGap(it->first))
continue;
if (it->second == 1)
{
sing = true;
break;
}
}
return sing;
}
/******************************************************************************/
/****************** remove singleton *****************************************/
PolymorphismSequenceContainer * removeSingletion(const PolymorphismSequenceContainer& psc)
{
PolymorphismSequenceContainer *NoSingPsc = new PolymorphismSequenceContainer(psc.getNumberOfSequences(), psc.getAlphabet());
for(unsigned int i = 0; i < psc.getNumberOfSites(); i++)
{
Site site = psc.getSite(i);
if(SiteTools::isConstant(site))
{
NoSingPsc->addSite(site);
continue;
}
map< int, unsigned long int > counts;
CodonSiteTools::getCounts(site, counts);
bool singleton = false;
for(map<int, unsigned long int>::iterator it = counts.begin(); it != counts.end(); it++)
{
if(site.getAlphabet()->isUnresolved(it->first) || site.getAlphabet()->isGap(it->first))
continue;
if(it->second == 1)
{
singleton = true;
}
}
if(!singleton)
NoSingPsc->addSite(site);
}
return NoSingPsc;
}
/******************************************************************************/
int getVariant(const Site& sitePol, const Site& siteMon){
if(!SiteTools::isConstant(siteMon, true))
throw ("Problem getVariant : siteMon is polymorphic");
int alleleM = -1;
int c = 0;
while(alleleM < 0 || alleleM > 3){
alleleM = siteMon.getValue(c);
c++;
}
for(unsigned int i = 0; i < sitePol.size(); i++){
int alleleP = sitePol.getValue(i);
if(sitePol.getAlphabet()->isGap(alleleP) || sitePol.getAlphabet()->isUnresolved(alleleP))
continue;
if(alleleP != alleleM)
return alleleP;
}
throw ("Problem getVariant");
return -1; // should never arrived here
}
/*****************************************************************/
double getGCThirdCodonPosition(const Sequence & seq, bool ignoreUnresolved=true, bool ignoreGap=true)
{
const Alphabet * alphabet = seq.getAlphabet();
if (!AlphabetTools::isNucleicAlphabet(alphabet)){
cout << "getGCThirdCodonPosition. Method only works on nucleotides." << endl;
return 0;
}
unsigned int l = seq.size();
double gc = 0;
double total = 0;
unsigned int j = l/3;
for( unsigned int k=1; k<=j; k ++){
unsigned int entier = k * 3;
unsigned int pos = entier-1;
int state = seq.getValue(pos);
if (state > -1) { // not a gap
if (state == 1 || state == 2) { // G or C
gc++;
total++;
} else if (state == 0 || state == 3) { // A, T or U
total++;
} else { // Unresolved character
if (!ignoreUnresolved) {
total++;
switch(state) {
case(7): gc++; break;// G or C
case(4): gc+=0.5; break;// A or C
case(5): gc+=0.5; break;// A or G
case(6): gc+=0.5; break;// C or T
case(9): gc+=0.5; break;// G or T
case(10): gc+=2./3.; break;// A or C or G
case(11): gc+=1./3.; break;// A or C or T
case(12): gc+=1./3.; break;// A or G or T
case(13): gc+=2./3.; break;// C or G or T
case(14): gc+=0.5; break;// A or C or G or T
}
}
}
} else {
if (!ignoreGap) total++;
}
}
return total != 0 ? gc/total : 0;
}
/********************************************************************/
/** Compute the mean number of differences between an outgroup sequence (seqOut)
* and several ingroup sequences (PolymorphismSequenceContainer)
*
* This take into account the potentially shared polymorphism
*
**/
/********************************************************************/
double computeMeanNumberOfDifference(const PolymorphismSequenceContainer& psc, BasicSequence seqOut, unsigned int minNumSites){
vector <double> diff;
double meanDiff;
for(unsigned int i = 0; i < psc.getNumberOfSequences(); i++){
const Sequence& seq1 = psc.getSequence(i);
/** check number of complete site before computing the divergence **/
PolymorphismSequenceContainer * tmpSc = new PolymorphismSequenceContainer(seqOut.getAlphabet());
tmpSc->addSequence(seq1);
tmpSc->addSequence(seqOut);
SiteContainer * tmpComp = SiteContainerTools::getCompleteSites(*tmpSc);
if(tmpComp->getNumberOfSites() > minNumSites){
/** compute the divergence **/
double d = SiteContainerTools::computeSimilarity(seqOut, seq1, true, "no gap", true)*tmpComp->getNumberOfSites();
diff.push_back(d);
// cout << d << endl;
}
delete tmpSc;
delete tmpComp;
}
meanDiff = VectorTools::mean<double, double>(diff);
return meanDiff;
}
/********************************************************************/
vector <double> computeMeanSynonymousAndNonSynonymousDifferences(const PolymorphismSequenceContainer& psc,
const Sequence& seqOut, const GeneticCode& gc, double tvts){
vector <double> diffNS, diffN, diffS;
double NSS;
for(unsigned int i = 0; i < psc.getNumberOfSequences(); i++){
const Sequence& seq1 = psc.getSequence(i);
/** check number of complete site before computing the divergence **/
PolymorphismSequenceContainer * tmpSc = new PolymorphismSequenceContainer(seqOut.getAlphabet());
tmpSc->addSequence(seq1);
tmpSc->addSequence(seqOut);
SiteContainer * tmpComp = SiteContainerTools::getCompleteSites(*tmpSc);
NSS = meanSynonymousSitesNumber2(*tmpComp,gc,tvts, false);
//if(tmpComp->getNumberOfSites() > 15){
double dS = SequenceStatistics::numberOfSynonymousSubstitutions(*tmpComp, gc, 0.0);
diffS.push_back(dS);
double dN = SequenceStatistics::numberOfSynonymousSubstitutions(*tmpComp, gc, 0.0);
diffN.push_back(dN);;
//}
delete tmpSc;
delete tmpComp;
}
diffNS.push_back(VectorTools::mean<double, double>(diffN));
diffNS.push_back(VectorTools::mean<double, double>(diffS));
diffNS.push_back(NSS);
return diffNS;
}
/********************************************************************/
/** PiInter : compute the Tajima's Pi between population ************/
/********************************************************************/
double PiInter(const PolymorphismSequenceContainer& psc, unsigned int id1, unsigned int id2)
{
vector<double> vdiff;
double piInter;
PolymorphismSequenceContainer *Pop1 = PolymorphismSequenceContainerTools::extractGroup(psc, id1);
PolymorphismSequenceContainer *Pop2 = PolymorphismSequenceContainerTools::extractGroup(psc, id2);
SiteContainerTools::changeUnresolvedCharactersToGaps (*Pop1);
SiteContainerTools::changeUnresolvedCharactersToGaps (*Pop2);
unsigned int N, totLength, meanLength = 0;
N = totLength = meanLength = 0;
for(unsigned int i = 0; i<Pop1->getNumberOfSequences(); i++){
const Sequence &s1 = Pop1->getSequence(i);
for(unsigned int j = 0; j<Pop2->getNumberOfSequences(); j++){
N++;
const Sequence &s2 = Pop2->getSequence(j);
vdiff.push_back(SiteContainerTools::computeSimilarity(s1,s2,true,"no gap",true));
totLength += SequenceTools::getNumberOfPositionsWithoutGap(s1,s2);
}
}
piInter = (VectorTools::sum(vdiff) / N)*(totLength/N);
delete Pop1;
delete Pop2;
return piInter;
}
/********************************************************************************** ****************/
/** Fst from eq. 3 of Hudson, Slatkin and Maddison 1992 Genetics 132:153 ****************************************/
/******************************************************************************** ******************/
/*
double FstHudson92(const PolymorphismSequenceContainer& psc, unsigned int id1, unsigned int id2, bool gapflag)
{
vector<double> vdiff;
double piIntra1, piIntra2, meanPiIntra, piInter, Fst;
PolymorphismSequenceContainer *Pop1 = PolymorphismSequenceContainerTools::extractGroup(psc, id1);
PolymorphismSequenceContainer *Pop2 = PolymorphismSequenceContainerTools::extractGroup(psc, id2);
piIntra1 = SequenceStatistics::tajima83(*Pop1, gapflag);
piIntra2 = SequenceStatistics::tajima83(*Pop2, gapflag);
meanPiIntra = (piIntra1+piIntra2)/2;
unsigned int N = 0;
for(unsigned int i = 0; i<Pop1->getNumberOfSequences(); i++){
const Sequence &s1 = Pop1->getSequence(i);
for(unsigned int j = 0; j<Pop2->getNumberOfSequences(); j++){
N++;
const Sequence &s2 = Pop2->getSequence(j);
vdiff.push_back(SiteContainerTools::computeSimilarity(s1,s2,true,"no gap",true));
}
}
piInter = (VectorTools::sum(vdiff) / N)*psc.getNumberOfSites();
Fst = 1.0 - meanPiIntra/piInter;
delete Pop1;
delete Pop2;
return Fst;
}
* */
double FstHudson92(const PolymorphismSequenceContainer& psc, unsigned int id1, unsigned int id2, bool gapflag)
{
vector<double> vdiff;
double piIntra1, piIntra2, meanPiIntra, piInter, Fst;
PolymorphismSequenceContainer *Pop1 = PolymorphismSequenceContainerTools::extractGroup(psc, id1);
PolymorphismSequenceContainer *Pop2 = PolymorphismSequenceContainerTools::extractGroup(psc, id2);
piIntra1 = SequenceStatistics::tajima83(*Pop1, false);
piIntra2 = SequenceStatistics::tajima83(*Pop2, false);
meanPiIntra = (piIntra1+piIntra2)/2;
piInter = PiInter(psc, id1, id2);
Fst = 1.0 - meanPiIntra/piInter;
delete Pop1;
delete Pop2;
return Fst;
}
/********************************************************************************** ****************/
/** Nei 1982 Fst = (Pi Total - Pi intra) / Pi Total ***************************************/
/** Pi intra could be weighted mean or not
* with w = 1.* n_x/(n_x + n_y) and meanPiIntra = w*p_x + (1-w)*p_y
* no weighted is w = 0.5
******************/
double FstNei82(const PolymorphismSequenceContainer& psc, unsigned int id1, unsigned int id2, bool weightedPiIntra, bool gapflag)
{
vector<double> vdiff;
double piTotal, piIntra1, piIntra2, meanPiIntra, Fst;
double w = 0.5;
/** select ingroup sequences **/
SequenceSelection ss;
PolymorphismSequenceContainer* psci = dynamic_cast<PolymorphismSequenceContainer*>(psc.clone());
for (unsigned int i = 0; i < psc.getNumberOfSequences(); i++){
if (psc.getGroupId(i) != id1 && psc.getGroupId(i) != id2)
ss.push_back(i);
}
for (unsigned int i = ss.size(); i > 0; i--){
psci->getGroupId(i-1);
psci->deleteSequence(ss[i - 1]);
}
piTotal = SequenceStatistics::tajima83(*psci, gapflag);
PolymorphismSequenceContainer *Pop1 = PolymorphismSequenceContainerTools::extractGroup(psc, id1);
PolymorphismSequenceContainer *Pop2 = PolymorphismSequenceContainerTools::extractGroup(psc, id2);
piIntra1 = SequenceStatistics::tajima83(*Pop1, gapflag);
piIntra2 = SequenceStatistics::tajima83(*Pop2, gapflag);
if(weightedPiIntra){
int n_x = Pop1->getNumberOfSequences();
int n_y = Pop2->getNumberOfSequences();
w = 1.* n_x/(n_x + n_y);
}
//cout << w << endl;
meanPiIntra = w * piIntra1 + w * piIntra2;
Fst = 1 - meanPiIntra/piTotal;
delete Pop1;
delete Pop2;
delete psci;
return Fst;
}
/************************************************************************************************/
bool isGapOrUnresolvedOnly2(const Site& site)
{
// Main loop : for all characters in site
for (unsigned int i = 0; i < site.size(); i++)
{
if (!site.getAlphabet()->isGap(site[i]) && !site.getAlphabet()->isUnresolved(site[i])) return false;
}
return true;
}
/**************************************************************************************************/
size_t getNumberOfTransitions2(const PolymorphismSequenceContainer& psc)
{
size_t nbT = 0;
ConstSiteIterator* si = new SimpleSiteContainerIterator(psc);
const Site* site = 0;
while (si->hasMoreSites())
{
site = si->nextSite();
// creat a site without gap or unresolved site
Site siteSg = Site(site->getAlphabet());
for(unsigned int s = 0; s < site->size(); s++){
if (!site->getAlphabet()->isGap(site->getValue(s)) && !site->getAlphabet()->isUnresolved(site->getValue(s))){
siteSg.addElement(site->getValue(s));
}
}
// if (SiteTools::isConstant(*site) || SiteTools::isTriplet(*site)) continue;
if (SiteTools::getNumberOfDistinctCharacters(siteSg) != 2)
continue;
int state1 = (*site)[0];
int state2 = (*site)[0];
for (size_t i = 1; i < site->size(); i++)
{
if (state1 != (*site)[i])
{
state2 = (*site)[i];
break;
}
}
if(((state1 == 0 && state2 == 2) || (state1 == 2 && state2 == 0)) ||
((state1 == 1 && state2 == 3) || (state1 == 3 && state2 == 1)))
{
nbT++;
}
}
delete si;
return nbT;
}
/** **********************************************************************************************/
/********************************************************************/
/** Number of Fixed, Private and Shared polymorphism between population *******/
/** */
/********************************************************************/
vector<int> NumberOfDifferenceBetweenPopulations(const PolymorphismSequenceContainer& psc, unsigned int id1, unsigned int id2)
{
vector<int> vdiff;
PolymorphismSequenceContainer *Pop1 = PolymorphismSequenceContainerTools::extractGroup(psc, id1);
PolymorphismSequenceContainer *Pop2 = PolymorphismSequenceContainerTools::extractGroup(psc, id2);
SiteContainerTools::changeUnresolvedCharactersToGaps (*Pop1);
SiteContainerTools::changeUnresolvedCharactersToGaps (*Pop2);
int Fixed = 0;
int PrivatePop1 = 0;
int PrivatePop2 = 0;
int Shared = 0;
for(unsigned int i = 0; i < psc.getNumberOfSites(); i++){
const Site& site = psc.getSite(i);
const Site& sitePop1 = Pop1->getSite(i);
const Site& sitePop2 = Pop2->getSite(i);
string ok = "no";
if(!SiteTools::isConstant(site, true, true)){
if(SiteTools::isConstant(sitePop1, true, true) && SiteTools::isConstant(sitePop2, true, true)){
Fixed++;
ok = "ok";
}
if(!SiteTools::isConstant(sitePop1, true, true) && SiteTools::isConstant(sitePop2, true, true)){
PrivatePop1++;
ok = "ok";
}
if(SiteTools::isConstant(sitePop1, true, true) && !SiteTools::isConstant(sitePop2, true, true)){
PrivatePop2++;
ok = "ok";
}
if(!SiteTools::isConstant(sitePop1, true, true) && !SiteTools::isConstant(sitePop2, true, true)){
//cout << "Shared " << i << endl;
Shared++;
ok = "ok";
}
if( ok == "no" ){
cout << site.toString() << endl;
}
}
}
vdiff.push_back(Fixed);
vdiff.push_back(PrivatePop1);
vdiff.push_back(PrivatePop2);
vdiff.push_back(Shared);
delete Pop1;
delete Pop2;
return vdiff;
}
/** **********************************************************************************************/
int main (int argc, char* argv[]){
try{
if (argc == 1 || argc < 13)
{
cout << "\n#####################";
cout << "\nVersion 1.1\n";
cout << "\n##### USAGE :\n";
cout << "\nseq_stat_2pop -seq [listSeq] -f [phylip or fasta] -coding [coding or non-coding] -tvts [tv/ts ratio for computing NSS] -pop1 [prefix_pop1] -pop2 [prefix_pop2] -outgroup [prefix_out] -o [out file]\n" << endl;
cout << "### Statistics :" << endl;
cout << "\tSize : Size of the alignment (bp)" << endl;
cout << "\tS_Pop : Number of polymorphic site" << endl;
cout << "\tPi_Pop : Tajima's estimator of nucleotides diversity" << endl;
cout << "\tW_Pop : Watterson's estimator of nucleotides diversity" << endl;
cout << "\tD_Pop : Tajima's D" << endl;
cout << "\tDxy or Pi between : Average number of pairwise differences between sequences from two populations, excluding all comparisons between sequences within populations (Nei 1987; Cruickshank & Hahn, 2014)" << endl;
cout << "\tFstHud : Fst computed as 1 - mean_Pi_Intra_Pop / Pi Between (or Dxy) (Hudson et al. 1992 Genetics 132:153 eq. 3)" << endl;
cout << "\tFstNei : Fst computed as 1 - mean_Pi_Intra_Pop / Pi Total (Nei 1982)" << endl;
cout << "\tFstNei_weighted : weigth by the sample size of each population with w = 1.* n_x/(n_x + n_y) and meanPiIntra = w*p_x + (1-w)*p_y" << endl;
cout << "\tFstNei_unweighted : with w = 0.5 and meanPiIntra = w*p_x + (1-w)*p_y" << endl;
cout << "\tPiTotal : Nucleotides diversity" << endl;
cout << "\tTs_Pop : Number of transition" << endl;
cout << "\tgc : GC content" << endl;
cout << "\tsizeOut : Size of outgroup sequence excluding gap and unresolved site (bp)" << endl;
cout << "\tdivOut : Mean divergence between outgroup sequence and population n°2" << endl;
cout << "### Statistics for coding sequences only :" << endl;
cout << "\tPS_Pop : Nucleotide diversity of synonymous sites" << endl;
cout << "\tPN_Pop : Nucleotide diversity of non-synonymous sites" << endl;
cout << "\tgc3 : GC content at the third codon position" << endl;
cout << "\tNSS_Pop : Number of synonymous site" << endl;
cout << "\tdiv_Syn_Out : Mean synonymous divergence between outgroup sequence and population n°2" << endl;
cout << "\tdiv_NonSyn_Out : Mean non-synonymous divergence between outgroup sequence and population n°2\n\n" << endl;
return 0;
}
string listName, format, typeAlg, outF, coding, pop1, pop2, outgroup;
double tvts;
/*************************************************************/
/** read command line **/
/*************************************************************/
int i = 1;
while (i < argc){
string s = argv[i];
if (s == "-seq") {
i++;
if (i == argc) {
cerr << "error in command: seq <listFile>\n";
cerr << '\n';
exit(1);
}
listName = argv[i];
}
if (s == "-f") {
i++;
if (i == argc) {
cerr << "error in command: -f <phylip or fasta>\n";
cerr << '\n';
exit(1);
}
format = argv[i];
}
if (s == "-coding") {
i++;
if (i == argc) {
cerr << "error in command: -coding <coding or non-coding>\n";
cerr << '\n';
exit(1);
}
coding = argv[i];
}
if (s == "-tvts") {
i++;
if (i == argc) {
cerr << "error in command: -tvts <double tvts>\n";
cerr << '\n';
exit(1);
}
tvts = TextTools::toDouble(argv[i]);
}
if (s == "-pop1") {
i++;
if (i == argc) {
cerr << "error in command: -pop1 <prefix pop1>\n";
cerr << '\n';
exit(1);
}
pop1 = argv[i];
}
if (s == "-pop2") {
i++;
if (i == argc) {
cerr << "error in command: -pop2 <prefix pop2>\n";
cerr << '\n';
exit(1);
}
pop2 = argv[i];
}
if (s == "-outgroup") {
i++;
if (i == argc) {
cerr << "error in command: -outgroup <prefix outgroup>\n";
cerr << '\n';
exit(1);
}
outgroup = argv[i];
}
if (s == "-o") {
i++;
if (i == argc) {
cerr << "error in command: -o <outFile>\n";
cerr << '\n';
exit(1);
}
outF = argv[i];
}
i++;
}
if(!FileTools::fileExists( listName )) {
cerr << "ERROR!!! File " << listName << " does not exists." << endl;
exit(-1);
}
ifstream Filelist (listName.c_str(), ios::in);
ofstream Fileout (outF.c_str(), ios::out);
if(coding == "coding"){
Fileout << "name\tsize\t";
Fileout << "S_Pop1\tS_Pop2\tPi_Pop1\tPi_Pop2\tW_Pop1\tW_Pop2\tD_Pop1\tD_Pop2\tDxy\tPiTotal\tFstHud\tFstNei_weighted\tFstNei_unweighted\t";
Fileout << "Ts_Pop1\tTs_Pop2\t";
Fileout << "PS_Pop1\tPN_Pop1\tNSS_Pop1\tPS_Pop2\tPN_Pop2\tNSS_Pop2\t";
Fileout << "gc3\tNumberOfStop\tInFrameStop\tsizeOut1\tsizeOut2\tdivOut1\tdivOut2\tNSS_Out1\tdiv_NonSyn_Out1\tdiv_Syn_Out1\tNSS_Out2\tdiv_NonSyn_Out2\tdiv_Syn_Out2" << endl;
}
if(coding == "non-coding"){
Fileout << "name\tsize\t";
Fileout << "S_Pop1\tS_Pop2\tPi_Pop1\tPi_Pop2\tW_Pop1\tW_Pop2\tD_Pop1\tD_Pop2\tDxy\tPiTotal\tFstHud\tFstNei_weighted\tFstNei_unweighted\t";
Fileout << "gc\tsizeOut1\tsizeOut2\tdivOut1\tdivOut2\tFixed\tPrivatePop1\tPrivatePop2\tShared" << endl;
}
while (!Filelist.eof ()){
string nomfic = FileTools::getNextLine(Filelist);
cout << nomfic << endl;
if(TextTools::isEmpty(nomfic)){
continue;
}
if(!FileTools::fileExists( nomfic )) {
cerr << "ERROR!!! File " << nomfic << " does not exists." << endl;
exit(-1);
}
double FstHud, FstNei_w, FstNei_uw;
const NucleicAlphabet * alpha = new DNA();
const CodonAlphabet *codonAlpha = new CodonAlphabet(alpha);
const GeneticCode *GC = new StandardGeneticCode(alpha);
VectorSequenceContainer * seqCont = NULL;
Phylip * PhySeq = new Phylip(true, true);
Fasta * FstSeq = new Fasta(10000000);
if(format == "phylip"){
seqCont = PhySeq->readAlignment(nomfic , alpha);
}
if(format == "fasta"){
seqCont = FstSeq->readAlignment(nomfic , alpha);
}
VectorSiteContainer *sitec = new VectorSiteContainer( *seqCont );
PolymorphismSequenceContainer * psc1 = new PolymorphismSequenceContainer( *sitec);
/** set variables for statistic **/
double diffOut1, diffOut2;
unsigned int Size, S_Pop2, S_Pop1;
unsigned int sizeSeqOut1 = 0;
unsigned int sizeSeqOut2 = 0;
double PiPop1, PiPop2, WPop1, WPop2, TajimaDPop1, TajimaDPop2, Dxy, piTotal;
if(coding == "coding"){
/*************************************************************/
/** convert alphabet and remove stop codon **/
/*************************************************************/
PolymorphismSequenceContainer * pscCodon = new PolymorphismSequenceContainer(codonAlpha);
SequenceContainerTools::convertAlphabet(*psc1, *pscCodon);
PolymorphismSequenceContainer * pscFinal = new PolymorphismSequenceContainer(pscCodon->getNumberOfSequences(), codonAlpha);
pscFinal->setSequencesNames(psc1->getSequencesNames(), false);
/** record stop codon **/
unsigned int numberOfStopCodon = 0;
string InFrameStop ="no";
for(unsigned int i = 0; i < pscCodon->getNumberOfSites(); i++) {
Site site = pscCodon->getSite(i);
if(CodonSiteTools::hasStop(site, *GC)){
numberOfStopCodon++;
if(i < pscCodon->getNumberOfSites()-1){
InFrameStop = "yes";
}
continue;
}
pscFinal->addSite(site);
}
/** Split dataset in population **/
string Pop1, Pop2, Out;
Pop1 = Pop2 = Out = "no";
for(unsigned int i = 0; i < pscFinal->getNumberOfSequences(); i ++){
if(TextTools::hasSubstring(pscFinal->getSequence(i).getName(), pop1)){
Pop1 = "yes";
pscFinal->setGroupId(i, 1);
continue;
}
if(TextTools::hasSubstring(pscFinal->getSequence(i).getName(), pop2)){
Pop2 = "yes";
pscFinal->setGroupId(i, 2);
continue;
}
if(TextTools::hasSubstring(pscFinal->getSequence(i).getName(), outgroup)){
Out = "yes";
pscFinal->setGroupId(i, 3);
continue;
}
// if sequence has not been assigned in any group it is put group number 4.
cout << "Warning : sequence " << psc1->getSequence(i).getName() << " is neither ingroup nor outgroup" << endl;
psc1->setGroupId(i,4);
}
PolymorphismSequenceContainer * pscPop1 = PolymorphismSequenceContainerTools::extractGroup (*pscFinal, 1);
PolymorphismSequenceContainer * pscPop2 = PolymorphismSequenceContainerTools::extractGroup (*pscFinal, 2);
/** create nucleotides alignment **/
PolymorphismSequenceContainer * pscPop1Nuc = new PolymorphismSequenceContainer(alpha);
SequenceContainerTools::convertAlphabet(*pscPop1, *pscPop1Nuc);