-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathstate.cpp
1666 lines (1543 loc) · 56.8 KB
/
state.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
#include <algorithm>
#include "state.h"
#include "rng.h"
#include "fsxml.h"
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;
namespace fines
{
State::State(Data *d,int npop,vector<double> bvec,double a,int betamodel,double corfactor,Data *d2,int datainference,int modeltype)
{
this->modeltype=modeltype;
dlength=d2;
this->datainference=datainference;
setdataused();
this->betamodel=betamodel;
this->corfactor=corfactor;
hyperprior=bvec;
data=d;
vector<string> unames,names;// unique population names
if(npop==-1) npop=getDim(); //-1 means the number of individuals
else if(npop==-2){ // -2 means try to infer from labels
for(long i=0;i<getDim();i++) {
names.push_back(data->getnames(i));
names.back()=removeNumbers(names.back());
}
unames=names; // get the vector of unique names
sort (unames.begin(),unames.end() , less<string>());
vector<string>::iterator it=unique (unames.begin(),unames.end() );
unames.resize( it - unames.begin() );
npop=unames.size();
}
if(npop<=0) throw(std::string("Bad initial population!"));
indinp.resize(npop,vector<int>());
psize.resize(npop,0);
for(int i=0;i<getDim();i++) {
if(getDim()==npop) ind.push_back(i);
else if(unames.size()>0){
for(unsigned long j=0;j<unames.size();j++) if(names[i]==unames[j]){
ind.push_back(j);
j=unames.size();
}
}else ind.push_back(RandomInteger(0,npop-1));
psize[ind[i]]+=data->nindiv(i);
indinp[ind[i]].push_back(i);
}
for(unsigned int i=0;i<psize.size();i++) if(psize[i]==0) removePop(i);
createParams(a);
}
State::State(Data *d,FsXml *infile,vector<double> bvec,double a,int betamodel,double corfactor,bool readp,Data *d2,int datainference,int modeltype)
{
this->modeltype=modeltype;
dlength=d2;
this->datainference=datainference;
this->betamodel=betamodel;
this->corfactor=corfactor;
setdataused();
hyperprior=bvec;
data=d;
alpha=a;
readState(getFromFile(infile,readp));
createParams(getAlpha());
//cout<<setprecision (12)<< "Approx log-likelihood="<<getApproxLogLikelihood()<<endl;
}
State::State(Data *d,std::string stringin,vector<double> bvec,double a,int betamodel,bool isfile,double corfactor,Data *d2,int datainference,int modeltype)
{
dlength=d2;
this->modeltype=modeltype;
this->datainference=datainference;
this->betamodel=betamodel;
this->corfactor=corfactor;
setdataused();
hyperprior=bvec;
data=d;
string statestr;
size_t found;
if(isfile){// its a file but not a valid state file
ifstream file;
file.open(stringin.data());//Open file
if(!file.good()) throw(std::string("Invalid file!"));
string curline;
/* while (1){
getline(file,curline);//Read next line from file
found=curline.find_first_of('<');
if(curline.length()>5+found) if(curline.substr(found,5).compare("<Pop>")==0) statestr=curline;
if (file.eof()) break;
}
file.close();//Close file
if(statestr.length()==0) throw(std::string("Population tag not found!"));*/
while (1){
getline(file,curline);//Read next line from file
found=curline.find_first_of('(');
if(found!=string::npos) statestr=curline;
if (file.eof()) break;
}
file.close();//Close file
if(statestr.length()==0) throw(std::string("Population tag not found!"));
// cout<<"Using state "<<statestr.c_str()<<endl;
}else statestr=stringin;
readState(statestr);
createParams(a);
}
State::State(State *in)
{
copyState(in);
}
State::State(Data *d,std::vector< std::vector<double> > *vecin,bool mergerule, double mergeval,std::vector<double> bvec,double a,int betamodel,double corfactor,Data *d2,int datainference,int modeltype)
{
this->modeltype=modeltype;
dlength=d2;
this->datainference=datainference;
this->betamodel=betamodel;
this->corfactor=corfactor;
setdataused();
hyperprior=bvec;
data=d;
// create a state with all individuals separate
indinp.resize(getDim(),vector<int>());
psize.resize(getDim(),0);
for(int i=0;i<getDim();i++) {
ind.push_back(i);
psize[ind[i]]+=data->nindiv(i);
indinp[ind[i]].push_back(i);
}
// and apply the merging algorithm to them according to the pairwise coincidences
createParams(a);
mergeOnCoincidence(vecin,mergerule,mergeval);
}
std::string State::getFromFile(FsXml *infile,bool readparams)
{
string ret;
std::streampos sp=infile->tellg();
while(1) {
string res=infile->getLine();
if(res.find("<Pop>")!=string::npos){
ret=res;
}
if(readparams){
if(res.find("<beta>")!=string::npos)setBetaFromString(res);
if(res.find("<alpha>")!=string::npos)setAlphaFromString(res);
if(res.find("<delta>")!=string::npos)setDeltaFromString(res);
if(res.find("<F>")!=string::npos)setFFromString(res);
}
if (infile->eof() || res.find("</Iteration>")!=string::npos) break;
}
infile->seekg(sp);
return(ret);
}
void State::mergeOnCoincidence(std::vector< std::vector<double> > *vecin,bool mergerule, double mergeval)
{
if(mergerule) {
for(unsigned int c1=0;c1<vecin->size();c1++) {
for(unsigned int c2=c1+1;c2<vecin->at(c1).size();c2++) {
if(vecin->at(c1)[c2] > mergeval && getPop(c1)!=getPop(c2)) {
merge(getPop(c1),getPop(c2));}
}
}
}
}
void State::createParams(double a){
mergepreva=-1;mergeprevb=-1;mergenewab=-1;
alpha=a;
sumbeta=0.0;
beta=vector<double>();
if(betamodel==BETAMOD_F || betamodel==BETAMOD_F2 || betamodel==BETAMOD_F2_COPYMAT) {
if(hyperprior.size()<4) throw(string("Param creation error: beta has wrong size for model!"));
if(hyperprior[0]<=-1) throw(string("Param creation error: fixed beta must be in the (0,1) range!"));
if((hyperprior[0]>0 && hyperprior[2]<0) || (hyperprior[1]>0 && hyperprior[3]<0)) throw(string("Param creation error: hyperpriors for beta must all be positive."));
}
if(betamodel==BETAMOD_COPYMAT || betamodel==BETAMOD_F2_COPYMAT){// only initialise once
int offset=0;
if(betamodel==BETAMOD_F2_COPYMAT)offset=4;
copyPrior=vector< vector<double> >(data->getDim(),vector<double>(data->getDim(),0));
if((int)hyperprior.size()<data->getDim()*data->getDim()){cerr<<"matrix too small:"<<hyperprior.size()<<"<"<<data->getDim()*data->getDim()<<endl;throw(string("Invalid beta matrix"));}
for(int c1=0;c1<data->getDim();c1++) {
for(int c2=0;c2<data->getDim();c2++) {
copyPrior[c1][c2]=hyperprior[c1*data->getDim()+c2+offset];
}
}
}
for(unsigned int i=0;i<psize.size();i++) {// one entry per population in these priors
if(betamodel==BETAMOD_F){
if(hyperprior[0]>0) betaF.push_back(sampleBetaP(0,0)); else betaF.push_back(-hyperprior[0]);
if(hyperprior[1]>0) delta.push_back(sampleBetaP(1,0)); else delta.push_back(-hyperprior[1]);
}else if(betamodel==BETAMOD_F2 || betamodel==BETAMOD_F2_COPYMAT) {
if(i==0 && delta.size()==0) {
betaF.push_back(sampleBetaP(0,0));///**** UNDESIREABLE TO DO THIS WHEN GENERATING TREES
delta.push_back(sampleBetaP(1,0));
}
}else{
beta.push_back(fabs(hyperprior[0]));
sumbeta+=fabs(hyperprior[0]);
}
}
popX=vector<vector<double> >();
for(unsigned int a=0;a<psize.size();a++) {
popX.push_back(vector<double>());
for(unsigned int b=0;b<psize.size();b++) {
popX.back().push_back(calcSumXab(a,b));
}
}
if(uselengths) {
popL=vector<vector<double> >();
poplogLpi=vector<vector<double> >();
poplogLgamma=vector<vector<double> >();
for(unsigned int a=0;a<psize.size();a++) {
popL.push_back(vector<double>());
poplogLpi.push_back(vector<double>());
poplogLgamma.push_back(vector<double>());
for(unsigned int b=0;b<psize.size();b++) {
popL.back().push_back(calcSumLab(a,b));
poplogLpi.back().push_back(calcSumlogLpi(a,b));
poplogLgamma.back().push_back(calcSumlogLgamma(a,b));
}
}
vector<double> hyperlen=getLengthHyperPrior();
for(int c1=0;c1<NUMHYPERPARAMLENGTH;c1++) if(hyperlen[c1]>0) priorLengths.push_back(sampleBetaP(c1,1));else priorLengths.push_back(fabs(hyperlen[c1]));
}
if(usesums) {
muvec=vector<double>(data->getDim(),0);
for(unsigned int c1=0;c1<muvec.size();c1++) muvec[c1]=calcMu(c1);
vector<double> hyperlen2=getTotalChunksHyperPrior();
for(int c1=0;c1<NUMHYPERPARAMTOTLENGTH;c1++){
if(hyperlen2[c1]>0) priorMeanSizes.push_back(sampleBetaP(c1,2)); else priorMeanSizes.push_back(fabs(hyperlen2[c1]));
}
}
verbose=false;
}
void State::readState(std::string statein)
{
indinp=vector<vector<int> >();
psize=vector<int>();
ind=vector<int>(getDim(),-1);
int popon=-1;
size_t found=statein.find_first_of("(),"), pos=0;
while(found!=string::npos){
if(statein.at(pos)=='(') {
popon++;
indinp.push_back(vector<int>());
psize.push_back(0);
if(found==0) found=statein.find_first_of("(),",pos+1);
}
if(statein.at(pos)=='(' || statein.at(pos)==',') {
int indiv=data->getIndex(statein.substr(pos+1,found-pos-1));
if(indiv<0) {
cerr<<"Individual "<<statein.substr(pos+1,found-pos-1).c_str()<<" not recognised!"<<endl;
cerr<<"Options are: ";
for(int c1=0;c1<getDim();c1++)cerr<<data->getnames(c1)<<" ";
cerr<<endl;
throw(std::string("State creation error: name not found!"));
}
ind[indiv]=popon;
psize.back()+=data->nindiv(indiv);
indinp.back().push_back(indiv);
}
pos=found;
found=statein.find_first_of("(),",pos+1);
}
for(int i=0;i<getDim();i++) if(ind[i]<0) {
cerr<<"Error: Individual "<<i<<" named "<<data->getnames(i)<<" not found in state input string."<<endl;
throw(std::string("State creation error"));
}
}
void State::copyState(State *in)
{
data=in->data;
psize=in->psize;
ind=in->ind;
dlength=in->dlength;
usecounts=in->usecounts;
uselengths=in->uselengths;
usesums=in->usesums;
datainference=in->datainference;
alpha=in->alpha;
hyperprior=in->hyperprior;
beta=in->beta;
betaF=in->betaF;
delta=in->delta;
betamodel=in->betamodel;
corfactor=in->corfactor;
sumbeta=in->sumbeta;
priorLengths=in->priorLengths;
verbose=in->verbose;
popX=in->popX;
popL=in->popL;
poplogLpi=in->poplogLpi;
poplogLgamma=in->poplogLgamma;
copyPrior=in->copyPrior;
for(unsigned int a=0;a<popX.size();a++) popX[a]=in->popX[a];
if(uselengths) {
for(unsigned int a=0;a<popL.size();a++) {
popL[a]=in->popL[a];
poplogLpi[a]=in->poplogLpi[a];
poplogLgamma[a]=in->poplogLgamma[a];
}
}
indinp=in->indinp;
for(unsigned int a=0;a<indinp.size();a++) indinp[a]=in->indinp[a];
diagmod=in->diagmod;
epopsize=in->epopsize;
muvec=in->muvec;
priorMeanSizes=in->priorMeanSizes;
mergepreva=in->mergepreva;mergeprevb=in->mergeprevb;mergenewab=in->mergenewab;
modeltype=in->modeltype;
}
void State::removePop(int lose,int keep)
{
// update super individual properties
if(keep>=0 && diagmod.size()>0 && epopsize.size()>0) {
diagmod[keep]+=diagmod[lose];
// epopsize[keep]=(2.0*psize[lose]*psize[keep])/(psize[lose]+psize[keep]);
epopsize[keep]=(2.0*psize[lose]*psize[keep])/(psize[lose]+psize[keep]);
//epopsize[keep]=sumXab(keep,keep) + sumXab(lose,lose);//sumXab(lose,keep) + sumXab(keep,lose)
epopsize.erase(epopsize.begin() + lose);
diagmod.erase(diagmod.begin() + lose);
}
// update the individuals and populations
if(keep>=0) {
for(unsigned int a=0;a<indinp[lose].size();a++) indinp[keep].push_back(indinp[lose][a]);
psize[keep]+=psize[lose];
}
indinp.erase(indinp.begin() + lose);
for(unsigned int i=0;i<ind.size();i++) {
if(ind[i]==lose && keep>=0) ind[i]=keep;
else if(ind[i]==lose && keep<0) throw(std::string("No replacement population supplied!"));
else if(ind[i]>lose) ind[i]--;
}
// update the population copy counts
if(keep>=0) {
for(unsigned int a=0;a<psize.size();a++) {
popX[a][keep]+=popX[a][lose];
popX[keep][a]+=popX[lose][a];
}
popX[keep][keep]+=popX[lose][lose];
if(uselengths){
for(unsigned int a=0;a<psize.size();a++) {
popL[a][keep]+=popL[a][lose];
popL[keep][a]+=popL[lose][a];
poplogLpi[a][keep]+=poplogLpi[a][lose];
poplogLpi[keep][a]+=poplogLpi[lose][a];
poplogLgamma[a][keep]+=poplogLgamma[a][lose];
poplogLgamma[keep][a]+=poplogLgamma[lose][a];
}
popL[keep][keep]+=popL[lose][lose];
poplogLpi[keep][keep]+=poplogLpi[lose][lose];
poplogLgamma[keep][keep]+=poplogLgamma[lose][lose];
}
}
for(unsigned int a=0;a<psize.size();a++) {popX[a].erase(popX[a].begin() + lose);}
popX.erase(popX.begin() + lose);
if(uselengths){
for(unsigned int a=0;a<psize.size();a++) {
popL[a].erase(popL[a].begin() + lose);
poplogLpi[a].erase(poplogLpi[a].begin() + lose);
poplogLgamma[a].erase(poplogLgamma[a].begin() + lose);
}
popL.erase(popL.begin() + lose);
poplogLpi.erase(poplogLpi.begin() + lose);
poplogLgamma.erase(poplogLgamma.begin() + lose);
}
// update the other vectors
psize.erase(psize.begin() + lose);
if(betamodel==BETAMOD_F){
betaF.erase(betaF.begin()+lose);
delta.erase(delta.begin()+lose);
}else if(betamodel==BETAMOD_F2_COPYMAT){
// nothing to do
}else if(betamodel!=BETAMOD_F2 && betamodel!=BETAMOD_F2_COPYMAT){
sumbeta-=beta[lose];
beta.erase(beta.begin()+lose);
}
}
void State::moveInd(int i,int popto){
int popfrom=getPop(i);
popX[popto][popto]+=X(i,i);// self copying gets counted twice
popX[popfrom][popfrom]+=X(i,i);
popX[popto][popfrom]-=X(i,i);// self copying gets counted twice
popX[popfrom][popto]-=X(i,i);
for(unsigned int a=0;a<psize.size();a++) {
double sxa=sumX(i,a),say=sumY(a,i);
popX[a][popto]+=say;
popX[popto][a]+=sxa;
popX[a][popfrom]-=say;
popX[popfrom][a]-=sxa;
if(uselengths) {
double sxa=sumLx(i,a),say=sumLy(a,i);
popL[a][popto]+=say;
popL[popto][a]+=sxa;
popL[a][popfrom]-=say;
popL[popfrom][a]-=sxa;
sxa=sumlogLpix(i,a);say=sumlogLpiy(a,i);
poplogLpi[a][popto]+=say;
poplogLpi[popto][a]+=sxa;
poplogLpi[a][popfrom]-=say;
poplogLpi[popfrom][a]-=sxa;
sxa=sumlogLgammax(i,a);say=sumlogLgammay(a,i);
poplogLgamma[a][popto]+=say;
poplogLgamma[popto][a]+=sxa;
poplogLgamma[a][popfrom]-=say;
poplogLgamma[popfrom][a]-=sxa;
}
}
// move the individual between the two population lists
int found=-1;
for(unsigned int a=0;a<indinp[popfrom].size();a++){
if(indinp[popfrom][a]==i) {found=a;break;}
}
if(found<0) {
cerr<<"ERROR: population missing its individual!"<<endl;
setprint(&cout);
for(unsigned int a=0;a<indinp.size();a++) {
cout<<"Pop "<<a<<": ";
for(unsigned int b=0;b<indinp[a].size();b++) cout<<indinp[a][b]<<",";
cout<<endl;
}
throw(std::string("Individual not found in its population!"));
}
indinp[popto].push_back(i);
indinp[popfrom].erase(indinp[popfrom].begin()+found);
// update the population sizes and individuals record of its pop
psize[popto]+=data->nindiv(i);
psize[popfrom]-=data->nindiv(i);
ind[i]=popto;
}
void State::setIntendedSplit(int i, int j){
mergepreva=i;
mergeprevb=j;
mergenewab=mergepreva; // this population is kept
};
void State::merge(int a,int b)
{
if(a==b) {cerr<<"Error in state:merge - merging identical populations!"<<endl;throw(string("Merging identical populations!"));}
int keep=min(a,b);
int lose=max(a,b);
vector<int> tmp=getIndInPop(keep);
if(tmp.size()>0) mergepreva=tmp[0];
tmp=getIndInPop(lose);
if(tmp.size()>0) mergeprevb=tmp[0];
mergenewab=mergepreva; // this population is kept
/* cout<<"Merging Pop "<<ind[mergepreva]<<":";
vector<int> indina=getIndInPop(ind[mergepreva]);
for(int i =0;i<indina.size();i++) cout<<indina[i]<<",";
cout<<endl;
cout<<"With Pop "<<ind[mergeprevb]<<":";
vector<int> indinb=getIndInPop(ind[mergeprevb]);
for(int i =0;i<indinb.size();i++) cout<<indinb[i]<<",";
cout<<endl;*/
removePop(lose,keep);
/* cout<<"To make Pop "<<ind[mergenewab]<<":";
vector<int> indinab=getIndInPop(ind[mergenewab]);
for(int i =0;i<indinab.size();i++) cout<<indinab[i]<<",";
cout<<endl; */
}
int State::addEmptyPop()
{
// add beta
if(betamodel==BETAMOD_F){
betaF.push_back(sampleBetaP(0,0)); //***
delta.push_back(sampleBetaP(1,0)); //***
}else if(betamodel!=BETAMOD_F2){
double avep=0.0;
for(unsigned int i=0;i<beta.size();i++) avep+=beta[i]/(double)beta.size();
beta.push_back(avep);
sumbeta+=avep;
}
// add to popX
for(unsigned int a=0;a<psize.size();a++) {
popX[a].push_back(0);
}
popX.push_back(vector<double>(psize.size()+1,0));
if(uselengths){
for(unsigned int a=0;a<psize.size();a++) {
popL[a].push_back(0);
poplogLpi[a].push_back(0);
poplogLgamma[a].push_back(0);
}
popL.push_back(vector<double>(psize.size()+1,0));
poplogLpi.push_back(vector<double>(psize.size()+1,0));
poplogLgamma.push_back(vector<double>(psize.size()+1,0));
}
// add to popsize
indinp.push_back(vector<int>());
psize.push_back(0);
return(psize.size()-1);// returns the index of the new pop
}
double State::probOfSplitSAMS(int i, int j, State * relstate)
{
// verbose=true;
bool valid=true;
int a=ind[i],b=ind[j];// get the initial populations
if(verbose) cout<<"Merging pops of individuals "<<i<<","<<j<<" in populations "<<a<<","<<b<<"; testing the split probability."<<endl;
double logpofsplit=0.0;
// move i and j to new populations
moveInd(i,addEmptyPop());
moveInd(j,addEmptyPop());
// apply the PCA automerge
//if(pca!=NULL) valid=testPcaAuto(a,b,i,j,pca->getDist(i,j),pca);
//if(logpofsplit<0) return(logpofsplit); // -INFINITY, i.e. impossible to get the split this way
// but can't return yet since we need a completed merge to get a valid state
// later will implement forcing this merge...
// List the other individuals
vector<int> olda=getIndInPop(a);
vector<int> oldb=getIndInPop(b);
vector<int> opop=olda;
opop.insert (opop.end(),oldb.begin(),oldb.end());
vector<int> frompop;
for(unsigned int c1=0;c1<olda.size();c1++) frompop.push_back(0);
for(unsigned int c1=0;c1<oldb.size();c1++) frompop.push_back(1);
// permute the list
rpermute(&opop,&frompop);
// do the merge
merge(a,b);// merge the populations
if(getPlength(a)==0) removePop(a);
if(getPlength(b)==0) removePop(b);
if(opop.size()==0) return(0.0);// there was only two individuals
int opindex=ind[opop[0]]; //original population index
a=ind[i],b=ind[j];
// Do the split
for(unsigned int k=0;k<opop.size();k++) {
// get the probabilities of the current state
double oldlptoi=posteriorSetProbPartial(ind[i],relstate);
double oldlptoj=posteriorSetProbPartial(ind[j],relstate);
double oldlp0=posteriorSetProbPartial(opindex,relstate);
// move individual and get new probabilities
moveInd(opop[k],ind[i]);
double lptoi=posteriorSetProbPartial(ind[i],relstate)+posteriorSetProbPartial(opindex,relstate)-oldlptoi-oldlp0;
double psizetoi=(double)psize[ind[i]];
//if(verbose) {cout<<"trying to move "<<data->getnames(opop[k])<<" to pop "<<ind[i]<<": " <<psizetoi<<" + log "<<lptoi <<endl;}
// move individual to the other population and get probabilities
moveInd(opop[k],ind[j]);
double lptoj=posteriorSetProbPartial(ind[j],relstate)+posteriorSetProbPartial(opindex,relstate)-oldlptoj-oldlp0;
double psizetoj=(double)psize[ind[j]];
//if(verbose) {cout<<"trying to move "<<data->getnames(opop[k])<<" to pop "<<ind[j]<<": " <<psizetoj<<" + log "<<lptoj <<endl;}
// evaluate the probability of each move.
// NOTE: r < Aa/(Aa+Bb) => 1/r > 1 + Bb/Aa = 1 + (b/a)*exp(log(B)-log(A))
/////////////////////////////****************
double lpi=-log(1.0 +(psizetoj/psizetoi)*exp(lptoj-lptoi));
double lpj=-log(1.0 +(psizetoi/psizetoj)*exp(lptoi-lptoj));
// lpi=-log(0.5);
// lpj=-log(0.5);
if(verbose) cout<<"trying to move "<<data->getnames(opop[k])<<" to pop "<<ind[i]<<": " <<psizetoi<<" + "<<lptoi <<endl;
if(frompop[k]==0) {
if(verbose) cout<<"Moved to "<<ind[i]<<endl;
logpofsplit+=lpi;
moveInd(opop[k],ind[i]);
}else {
if(verbose) cout<<"Moved to "<<ind[j]<<endl;
logpofsplit+=lpj;
moveInd(opop[k],ind[j]);
}
}
removePop(opindex);
if(valid) return(logpofsplit);
return(-DBL_MAX);
}
double State::splitSAMS(int i, int j,bool greedy, State * relstate)
{
if(i==j) {cerr<<"WARNING: Tried to split a single individual!"<<endl;return(0);}
if(ind[i]!=ind[j]) {cerr<<"WARNING: Tried to split individuals in different populations!"<<endl;return(0);}
int opindex=ind[i]; //original population index
// move i and j to new populations
vector<int> opop=getIndInPop(opindex);
if(verbose) {cout<<"Splitting pop "<<opindex<<" containing:";
for(unsigned int c1=0;c1<opop.size();c1++) cout<<data->getnames(opop[c1])<<",";
cout<<endl; setprint(&cout);}
// move and create new populations
moveInd(i,addEmptyPop());
moveInd(j,addEmptyPop());
// permute the rest of the individuals
//if(pca!=NULL) movePcaAuto(opindex,i,j,pca->getDist(i,j),pca);
opop=getIndInPop(opindex);
if(opop.size()>0) rpermute(&opop);
if(verbose) cout<<"SEEDING WITH "<<data->getnames(i)<<" and "<<data->getnames(j)<<endl;
double logpofsplit=0.0;
for(unsigned int k=0;k<opop.size();k++) {
double lpi=0;
double lpj=0;
// obtain the probabilities of the initial populations
double oldlptoi=posteriorSetProbPartial(ind[i],relstate);
double oldlptoj=posteriorSetProbPartial(ind[j],relstate);
double oldlp0=posteriorSetProbPartial(opindex,relstate);
// move and get new probabilities
moveInd(opop[k],ind[i]);
double lptoi=posteriorSetProbPartial(ind[i],relstate)-oldlptoi+posteriorSetProbPartial(opindex,relstate)-oldlp0;
double psizetoi=(double)psize[ind[i]];
if(verbose) cout<<"trying to move "<<data->getnames(opop[k])<<" to pop "<<ind[i]<<": " <<psizetoi<<" + log "<<lptoi <<endl;
// move to other population and get new probabilities
moveInd(opop[k],ind[j]);
double lptoj=posteriorSetProbPartial(ind[j],relstate)-oldlptoj+posteriorSetProbPartial(opindex,relstate)-oldlp0;
double psizetoj=(double)psize[ind[j]];
//if(verbose) cout<<"trying to move "<<data->getnames(opop[k])<<" to pop "<<ind[j]<<": " <<psizetoj<<" + "<<lptoj <<endl;
// calculate the probabilities
// NOTE: r < Aa/(Aa+Bb) => 1/r > 1 + Bb/Aa = 1 + (b/a)*exp(log(B)-log(A))
/////////////////////////////****************
lpi=-log(1.0 +(psizetoj/psizetoi)*exp(lptoj-lptoi));
lpj=-log(1.0 +(psizetoi/psizetoj)*exp(lptoi-lptoj));
// lpi=-log(0.5);
// lpj=-log(0.5);
if(verbose) cout<<"Prob of pop "<<ind[i]<<"="<<lpi<<" and of pop "<<ind[j]<<"="<<lpj<<endl;
if(greedy) {
if(lpi>log(0.5000001) || (lpi>log(0.499999) &&rnd()<0.5)) {
moveInd(opop[k],ind[i]);
if(verbose) cout<<"Moved to "<<ind[i]<<endl;
}else {
moveInd(opop[k],ind[j]);
if(verbose) cout<<"Moved to "<<ind[j]<<endl;
}
}else if(log(rnd()) < lpi) {
if(verbose) cout<<"Moved to "<<ind[i]<<endl;
logpofsplit+=lpi;
moveInd(opop[k],ind[i]);
}else {
if(verbose) cout<<"Moved to "<<ind[j]<<endl;
logpofsplit+=lpj;
moveInd(opop[k],ind[j]);
}
};
removePop(opindex);
if(ind[i]<ind[j]){
mergepreva=i;mergeprevb=j;
}else{
mergeprevb=i;mergepreva=j;
}
return(logpofsplit);
}
void State::splitSAMS(int a, State * relstate)
{
vector<int> pop=getIndInPop(a);
if(pop.size()==1) {cerr<<"WARNING: splitting population of size 1!"<<endl;return;}
int i=RandomInteger(0,pop.size()-1);
int j=i;
while(j==i) j=RandomInteger(0,pop.size()-1);
splitSAMS(pop[i],pop[j],false,relstate);
}
void State::splitSAMSgreedy(int a,int cmax, State * relstate)
{
vector<int> pop=getIndInPop(a);
if(pop.size()==1) {cerr<<"WARNING: splitting population of size 1!"<<endl;return;}
if(cmax<0) throw(std::string("Need cmax to be set!"));
State oldstate(this);
State beststate(this);
double splitbest=-10e30,cursplit;
bool rand=true;
if((int) (pop.size()*(pop.size()-1))<2*cmax) {cmax=pop.size();rand=false;}
else cmax=(int)ceil(sqrt(cmax));
int i,j;
if(verbose) print(&cout,false);
// get a list of all the possible split seeds, or use random seeds
for(int c1=0;c1<cmax;c1++) {
for(int c2=c1+1;c2<cmax;c2++) {
if(rand) {
i=RandomInteger(0,pop.size()-1);
j=i;
while(j==i) j=RandomInteger(0,pop.size()-1);
}else{
i=c1;
j=c2;
}
// do the splits
splitSAMS(pop[i],pop[j],true,relstate);
if(verbose) cout<<"Testing state with probability "<<posteriorProb(relstate)<<endl;
if(verbose) print(&cout,false);
// test whether to keep the split
cursplit=posteriorProb(relstate);
if(cursplit<splitbest) {
// do nothing! reject this split
}else {// accept the split
splitbest=cursplit;
beststate.copyState(this);
}
copyState(&oldstate);
}
}
copyState(&beststate);
}
vector <int> State::getIndInPop(int pop)
{
if(pop<0 || pop>=(int)indinp.size()) throw(string("Error in getindinp: invalid index!"));
//cout<<"pop="<<pop<<" indinsize="<<indinp.size()<<endl;
//cout<<"indinp[pop]="<<indinp[pop].size()<<endl;
return(indinp[pop]);
}
void State::setIndInPop(std::vector<int> v,int i)
{
if(v.size()!=indinp[i].size()) throw(string("Setting population to invalid value!"));
vector<int> tmp=indinp[i];
for(unsigned int c1=0;c1<v.size();c1++) {
bool found=false;
for(unsigned int c2=0;c2<tmp.size();c2++) {
if(tmp[c2]==v[c1]) found=true;
}
if(found==false) throw(string("Invalid individual set in setindinpop!"));
indinp[i][indinp[i].size()-c1-1]=v[c1];
}
}
double State::sumX(int i, int pop,bool cf)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=X(i,jlist[j],cf);
return(s);
}
double State::sumY(int pop, int i,bool cf)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=X(jlist[j],i,cf);
return(s);
}
double State::calcSumXab(int a, int b,bool cf)
{
double s=0;
vector<int> ilist=getIndInPop(a);
for(unsigned int i=0;i<ilist.size();i++) s+=sumX(ilist[i],b,cf);
return(s);
}
double State::sumXab(int a, int b,bool cf)
{
// cout<<"a="<<a<<" b="<<b<<" stored="<<popX[a][b]<<" calc="<<calcSumXab(a,b)<<" psize=["<<getPsize(a)<<","<<getPsize(b)<<"] plength=["<<getPlength(a)<<","<<getPlength(b)<<"]"<<endl;
// return(calcSumXab(a,b,cf));
// if(popX[a][b]<0) {if(popX[a][b]>-0.00001) {popX[a][b]=0;}else{cout<<"popx of "<<a<<" "<<b<< "is "<<popX[a][b]<<endl;exit(0);}}
if (cf) return(popX[a][b]);
return(popX[a][b]*corfactor);
}
double State::sumLx(int i, int pop)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=L(i,jlist[j]);
return(s);
}
double State::sumLy(int pop, int i)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=L(jlist[j],i);
return(s);
}
double State::sumlogLpix(int i, int pop)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=logLpi(i,jlist[j]);
return(s);
}
double State::sumlogLpiy(int pop, int i)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) s+=logLpi(jlist[j],i);
return(s);
}
double State::sumlogLgammax(int i, int pop)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) if(data->get(i,jlist[j])!=0) s+=mylgamma(data->get(i,jlist[j]));
return(s);
}
double State::sumlogLgammay(int pop, int i)
{
double s=0;
vector<int> jlist=getIndInPop(pop);
for(unsigned int j=0;j<jlist.size();j++) if(data->get(i,jlist[j])!=0) s+=mylgamma(data->get(jlist[j],i));
return(s);
}
void State::printX(ostream * out,bool perindiv)
{
if(perindiv) *out<<"relXmat,";
else *out<<"Xmat,";
double denom;
for(unsigned int i=0;i<psize.size()-1;i++) *out<<i<<", ";
*out<<psize.size()-1<<endl;
for(unsigned int i=0;i<psize.size();i++) {
*out<<i<<", ";
if(perindiv) {
double partdenom=sumXa(i);
for(unsigned int j=0;j<psize.size()-1;j++) {
// if(i==j)denom=(psize[i])*(psize[i]-1);
// else denom=psize[i]*psize[j];
if(i==j)denom=(partdenom)*(psize[i]-1);
else denom=partdenom*psize[j];
// if(i==j)denom=(psize[j]-1);
// else denom=psize[j];
if(denom==0) *out<<"0.0,";
else *out<<sumXab(i,j)/denom<<",";
}
unsigned int j=psize.size()-1;
// if(i==j)denom=(psize[j]-1)*psize[i]-1;
// else denom=psize[i]*psize[j];
if(i==j)denom=(partdenom)*(psize[i]-1);
else denom=partdenom*psize[j];
// if(i==j)denom=(psize[j]-1);
// else denom=psize[j];
if(denom==0)*out<<"0.0"<<endl;
else *out<<sumXab(i,j)/denom<<endl;
}else{
for(unsigned int j=0;j<psize.size()-1;j++) *out<<sumXab(i,j)<<",";
*out<<sumXab(i,psize.size()-1)<<endl;
}
}
// *out<<"</X>"<<endl;
}
void State::printBeta(ostream * out)
{
*out<<"beta,";
for(unsigned int i=0;i<psize.size()-1;i++) *out<<i<<", ";
*out<<psize.size()-1<<endl;
for(unsigned int i=0;i<psize.size();i++) {
*out<<i<<", ";
for(unsigned int j=0;j<psize.size()-1;j++) *out<<getBeta(i,j)<<",";
*out<<getBeta(i,psize.size()-1)<<endl;
}
// *out<<"</beta>"<<endl;
}
void State::setSuperIndivRule(bool super){
if(super){// set up diagmod and epopsize
diagmod=std::vector<double>(getP(),0);
epopsize=std::vector<double>(getP(),0);
for(unsigned int a=0;a<psize.size();a++) {
vector<int> popa=getIndInPop(a);
double maxa=0;
for(unsigned int b=0;b<psize.size();b++) {if(b!=a){
vector<int> popb=getIndInPop(b);
for(unsigned int c1=0;c1<popa.size();c1++)for(unsigned int c2=0;c2<popb.size();c2++) if(data->get(popa[c1],popb[c2])/data->nindiv(popa[c1])/data->nindiv(popb[c2]) > maxa) maxa=data->get(popa[c1],popb[c2])/data->nindiv(popa[c1])/data->nindiv(popb[c2]);
}}
for(unsigned int c1=0;c1<popa.size();c1++){for(unsigned int c2=0;c2<popa.size();c2++){ if(data->get(popa[c1],popa[c2])/data->nindiv(popa[c1])/data->nindiv(popa[c2])> maxa){
//double diff=data->get(popa[c1],popa[c2]) - maxa;
//cout<<setprecision(10)<<"Flattening "<<popa[c1]<<","<<popa[c2]<<" from "<<data->get(popa[c1],popa[c2])/data->nindiv(popa[c1])/data->nindiv(popa[c2])<<" to "<<maxa<<endl;
data->set(popa[c1],popa[c2],maxa*data->nindiv(popa[c1])*data->nindiv(popa[c2]));
popX[a][a]=calcSumXab(a,a);
}}}
}
}else {diagmod=std::vector<double>(0);epopsize=std::vector<double>(0);}
}
void State::print(ostream * out,bool chat)
{
if(chat) *out<<"Printing State"<<endl<<"IND:, ";
for(unsigned int i=0;i<ind.size()-1;i++) *out<<ind[i]<<", ";
*out<<ind[ind.size()-1]<<endl;
if(chat) *out<<"POP:"<<endl;
for(unsigned int i=0;i<psize.size();i++) {
*out<<"pop "<<i<<" size="<<psize[i]<<": ";
vector<int> tp=getIndInPop(i);
for(unsigned int j=0;j<tp.size()-1;j++) *out<<data->getnames(tp[j])<<",";
*out<<data->getnames(tp[tp.size()-1])<<endl;
}
if(chat) {
*out<<"XMAT (to)"<<endl;
for(int i=0;i<getDim();i++) {
*out<<data->getnames(i)<<", ";
for(unsigned int j=0;j<psize.size()-1;j++) {
*out<<sumX(i,j)<<", ";
}
*out<<sumX(i,psize.size()-1)<<endl;
}
*out<<"YMAT (from)"<<endl;
for(int i=0;i<getDim();i++) {
*out<<data->getnames(i)<<", ";
for(unsigned int j=0;j<psize.size()-1;j++) {
*out<<sumY(j,i)<<", ";
}
*out<<sumY(psize.size()-1,i)<<endl;
}
}
}
void State::setprint(ostream * out)
{
*out<<"<Pop>"<<flush;
for(int popon=0;popon<getP();popon++) {
vector<int> pop=getIndInPop(popon);
if(pop.size()>0){
*out<<"("<<flush;
for(unsigned int i=0;i<pop.size()-1;i++) {
*out<<data->getnames(pop[i])<<","<<flush;
}
*out<<data->getnames(pop[pop.size()-1])<<")"<<flush;
}
}
*out<<"</Pop>"<<endl;
}
double State::posteriorProb(State * relstate)
{
double logp=psize.size() * log(alpha);
for(unsigned int a=0;a<psize.size();a++) {
logp+=mylgamma(getPsize(a));
if(usecounts && (modeltype==MODELTYPE_NORMALISED || modeltype==MODELTYPE_NORMALISEDMERGEONLY)) logp+=posteriorSetProb(a,relstate);
else if(usecounts && modeltype==MODELTYPE_INDIVIDUAL) logp+=posteriorIndSetProb(a);
else if(usecounts)logp+=posteriorSetProb(a); // Actually we do a lot of stuff in infmcmc that we don't need to if we use this model
//if(usecounts) logp+=posteriorSetProb(a);
if(uselengths) logp+=posteriorLengthSetProb(a);
if(usesums) logp+=posteriorNumChunksSetProb(a);
}
return(logp);
}
double State::posteriorSetProb(int a)
{
std::vector<int> tmp=getIndInPop(a);
double logp=0.0;
double sXa=sumXa(a);
// Normalising factor
if(psize[a]==0) return(0);// catch when merges remove population
double sbeta=getSumBeta(a);
logp+=mylgamma(sbeta) - mylgamma(sXa+sbeta);
if(checkPopForIgnoredSuper(a)){
return(-INFINITY);
}
// product over other populations
for(unsigned int b=0;b<psize.size();b++) {
double sumab=sumXab(a,b);
double betaab=getBeta(a,b);
int epop=getPsize(b);
if(a==(int)b) epop--;
if(epop>0) {
logp+=mylgamma(betaab+sumab) - mylgamma(betaab) - sumab*log(epop);
}
}
return(logp);
}
double State::posteriorSetProb(int a,State * relstate)
{
if(relstate==NULL) return(posteriorSetProb(a));
if(relstate->mergepreva<0 || relstate->mergeprevb<0 || relstate->mergenewab<0) return(posteriorSetProb(a));
//||getP()<=relstate->getP() was also in above if
if(psize[a]==0) return(0);// catch when merges remove population
double logp=0.0;
//double sXa=sumXa(a);
double sXa=0;
// for(int b=0;b<psize.size();b++)sXa+=sumXab(a,b);
double smod=0;
// bool userelstate=false;
//double sbeta=getSumBeta(a);
double sbeta=0;
/*if(relstate!=NULL) if(relstate->mergepreva>=0) if(a==ind[relstate->mergepreva] &&getP()>relstate->getP()){
cout<<"PSP: a="<<a<<" newa="<<relstate->ind[relstate->mergenewab]<<" This K="<<getP()<<" compared to "<<relstate->getP()<<" mnewab="<<mergenewab<<endl;
vector<int> indinab=relstate->getIndInPop(relstate->ind[relstate->mergenewab]);
vector<int> indina=getIndInPop(a);
for(int i =0;i<indina.size();i++) cout<<indina[i]<<",";
cout<<endl;