-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFramework.C
1426 lines (1295 loc) · 39.2 KB
/
Framework.C
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
/*
CMINT: An algorithm to cluster functional genomics data for multiple cell types
Copyright (C) 2016 Sushmita Roy sushroy@gmail.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <ctime>
#include <iostream>
#include <fstream>
#include <vector>
#include <math.h>
#include <string.h>
#include "GeneMap.H"
#include "MappedOrthogroup.H"
#include "MappedOrthogroupReader.H"
#include "Matrix.H"
#include "SpeciesDistManager.H"
#include "GeneTree.H"
#include "GeneTreeManager.H"
#include "Expert.H"
#include "Gamma.H"
#include "GammaManager.H"
#include "GeneNameMapper.H"
#include "SpeciesClusterManager.H"
#include "Error.H"
#include "Evidence.H"
#include "EvidenceManager.H"
#include "Framework.H"
Framework::Framework()
{
}
Framework::~Framework()
{
}
int
Framework::readSpeciesData(const char* aFName, const char* rand)
{
if(strcmp(rand,"none")==0)
{
scMgr.setRandom(false);
}
else if(strcmp(rand,"yes")==0)
{
scMgr.setRandom(true);
}
else if(isdigit(rand[0]))
{
scMgr.setRandom(true);
scMgr.setRandSeed(atoi(rand));
}
scMgr.setMaxClusterCnt(maxClusterCnt);
// get species list from sdMgr -- this way we don't read data for other species
// the RNG for scMgr gets set up in readSpeciesData
vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
int dataOK=scMgr.readSpeciesData(aFName, speciesList);
if (dataOK != 0)
{
return 1;
}
// this is an RNG for Framework that is different from scMgr's
randnum=gsl_rng_alloc(gsl_rng_default);
return 0;
}
int
Framework::readSpeciesTree(int clusterCnt, const char* aFName)
{
maxClusterCnt=clusterCnt;
sdMgr.setMaxClusters(clusterCnt);
sdMgr.readSpeciesTree(aFName);
sdMgr.assignLevel();
gammaMgr.setSpeciesDistManager(&sdMgr);
return 0;
}
int
Framework::readOrthology(const char* specOrder, const char* orthomapfile)
{
int orderOK = mor.readSpeciesMapping(specOrder);
if (orderOK != 0)
{
cerr << "Problem reading cell order file: " << specOrder << endl;
return 1;
}
mor.readFile(orthomapfile);
scMgr.setOrthogroupReader(&mor);
gammaMgr.setOrthogroupReader(&mor);
gammaMgr.setMaxClusterCnt(maxClusterCnt);
scMgr.setGammaManager(&gammaMgr);
return 0;
}
/*
* Reads regulator OG list.
*/
int Framework::readRegulatorOGIds(const char* regfile)
{
int success=scMgr.setRestrictedList(regfile);
if (success != 0)
{
cerr << "Problem reading regulator list file: " << regfile << endl;
}
return success;
}
int
Framework::setSrcSpecies(const char* specName)
{
strcpy(srcSpecies,specName);
scMgr.setSrcSpecies(specName);
return 0;
}
/**
* This is the main function.
*
*/
int
Framework::startClustering(const char* aDir)
{
strcpy(outputDir,aDir);
scMgr.initExperts();
cout <<"Total updated parent nodes "<< gammaMgr.getTotalUpdatedParentCnt() << endl;
gammaMgr.showTotalUpdatedParents();
initClusterTransitionProb(); // initialize from input
// emint output
char dirName[1024];
sprintf(dirName,"mkdir -p %s/emint",outputDir);
int errcode = system(dirName);
if (errcode != 0)
{
cerr << "Could not make directory " << dirName << endl;
return errcode;
}
sprintf(dirName,"%s/emint",outputDir);
cout << "Running EMINT; putting results in " << dirName << endl;
//SR: We will rename this to initializeExperts
scMgr.estimateExpertParameters(dirName); // Run EMINT until convergence.
// print the emint stuff
printResults(dirName);
// print current data and DRMN data to subdirs emint/ and features/
//scMgr.printCurrentData(outputDir); // not used
// for each cluster, print the maintenance probs
/*for (int k=0; k<maxClusterCnt; k++)
{
cout << "Maintenance probs for cluster " << k << endl;
sdMgr.showTreeForCluster(k);
}*/
// species list
vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
//return 0;
// Get maximal cluster assignments and update transition probs
// die if cannot create dir
sprintf(dirName,"mkdir -p %s/drmn",outputDir);
errcode = system(dirName);
if (errcode != 0)
{
cerr << "Could not create output directory " << outputDir << endl;
return errcode;
}
sprintf(dirName,"%s/drmn",outputDir);
cout << "Will put drmn results in " << dirName << endl;
char drmnOutputDir[1024];
sprintf(drmnOutputDir,"%s/drmn",outputDir);
scMgr.setMaxAssignments(); // Redundant with the printing function, but OK -- need to make sure we do this.
// check for errors
int ran = scMgr.estimateDRMN(outputDir);
if (ran != 0)
{
cerr << "Could not estimate DRMN." << endl;
return 1;
}
double newScore=scMgr.getScore();
scMgr.dumpAllInferredClusterAssignments(outputDir);
double newScore_PP=scMgr.getScore();
//cout <<"Score before PP " << newScore << "\t" << " Score after PP " << newScore_PP << endl;
scMgr.showClusters_Extant(outputDir);
scMgr.showClusters_Ancestral(outputDir);
scMgr.showMeans(outputDir);
//This is only for visualization purposes
/*vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
for(int i=0;i<speciesList.size();i++)
{
cout << speciesList[i] << endl;
}*/
//scMgr.dumpAllInferredClusters_SrcwiseGrouped(outputDir,speciesList);
scMgr.dumpAllInferredClusters_LCA(outputDir,speciesList,sdMgr.getRoot()->name);
scMgr.dumpAllInferredClusterGammas(outputDir,speciesList);
int printed = scMgr.showDRMNResults(drmnOutputDir);
if (printed !=0)
{
cerr << "Could not print final results." << endl;
return printed;
}
//sdMgr.showInferredConditionals_ML(outputDir);
return 0;
}
//This function will implement the logic of startClustering for different folds of the data
// note that folds are determined by OGIDs, which may be a larger set than the initial cluster assignments
// int myFold: which fold (out of total folds) to run this time. If < 0, run all folds.
// int foldSeed: seed to RNG for ordering examples into folds. if < 0, use PID.
// If foldSeed < 0 and myFold >=0, then we are doing sampling with replacement.
int
Framework::startClustering_CV(const char* aFName, const char* rand, const char* aDir,int folds, int myFold, int foldSeed)
{
if(strcmp(rand,"none")==0)
{
scMgr.setRandom(false); // no randomization of clusterIDs
}
else if(strcmp(rand,"yes")==0)
{
scMgr.setRandom(true); // set cluster IDs randomly
}
else if(isdigit(rand[0]))
{
scMgr.setRandom(true);
scMgr.setRandSeed(atoi(rand)); // set cluster ID randomizer seed
}
strcpy(outputDir,aDir);
// This is the RNG for CV.
randnum=gsl_rng_alloc(gsl_rng_default);
if (foldSeed >= 0) // user provided seed so that we can make folds without replacement
{
gsl_rng_set(randnum, foldSeed);
cout << "Set RNG seed to: " << foldSeed << endl;
}
scMgr.setMaxClusterCnt(maxClusterCnt);
EvidenceManager dummyEvManager;
map<int,MappedOrthogroup*>& ogSet=mor.getMappedOrthogroups();
vector<int> ogSet_IDs;
for(map<int,MappedOrthogroup*>::iterator oIter=ogSet.begin();oIter!=ogSet.end();oIter++)
{
ogSet_IDs.push_back(oIter->first);
}
int* randInds=new int[ogSet.size()];
// this is where we populate randInds with the order of examples
dummyEvManager.populateRandIntegers(randnum,randInds,ogSet.size());
int testBegin=0;
int foldSize=(int)(ogSet.size()/folds);
for(int f=0;f<folds;f++)
{
int testEnd=testBegin+foldSize;
map<int,int> trainIDs;
map<int,int> testIDs;
for(int i=0;i<ogSet.size();i++)
{
int randid=randInds[i];
int ogid=ogSet_IDs[randid];
if(i>=testBegin && i<testEnd)
{
testIDs[ogid]=0;
}
else
{
trainIDs[ogid]=0;
}
}
testBegin=testEnd;
// if we have specified one fold to run and it's not this, skip.
if (myFold >= 0 && myFold != f)
{
cout << "SKIPPING fold " << f << endl;
continue;
}
cout << "NOW RUNNING fold " << f << endl;
scMgr.setTrainOGIDs(trainIDs);
// species list
vector<string> mySpecies;
sdMgr.getSpeciesListPrefix(mySpecies);
int dataOK=scMgr.readSpeciesData(aFName, mySpecies);
if (dataOK != 0)
{
cerr << "Problem reading species data in fold " << f << endl;
return 1;
}
scMgr.initExperts();
cout <<"Total updated parent nodes "<< gammaMgr.getTotalUpdatedParentCnt() << endl;
gammaMgr.showTotalUpdatedParents();
initClusterTransitionProb(); // initialize from input
// emint output
char dirName[1024];
sprintf(dirName,"mkdir -p %s/fold%d/emint",outputDir,f);
int errcode = system(dirName);
if (errcode != 0)
{
cerr << "Could not create output directory " << outputDir << endl;
return 1;
}
sprintf(dirName,"%s/fold%d/emint",outputDir,f);
cout << "Running EMINT; putting results in " << dirName << endl;
//SR: We will rename this to initializeExperts
scMgr.estimateExpertParameters(dirName); // Run EMINT until convergence.
// print the emint stuff
printResults(dirName);
// species list
vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
// Get maximal cluster assignments and update transition probs
sprintf(dirName,"mkdir -p %s/fold%d/drmn",outputDir,f);
errcode = system(dirName);
if (errcode != 0)
{
cerr << "Could not create output directory " << outputDir << endl;
return 1;
}
sprintf(dirName,"%s/fold%d/drmn",outputDir,f);
cout << "Will put drmn results in " << dirName << endl;
char drmnOutputDir[1024];
sprintf(drmnOutputDir,"%s/fold%d/drmn",outputDir,f);
scMgr.setMaxAssignments(); // Redundant with the printing function, but OK -- need to make sure we do this.
int success=scMgr.estimateDRMN(drmnOutputDir);
if (success != 0)
{
cerr << "Could not estimate DRMN" << endl;
return success;
}
// collect training data likelihood
double trainUnpen=0;
double trainPen=0;
scMgr.getDRMNScore_test(trainIDs, trainUnpen, trainPen);
scMgr.dumpAllInferredClusterAssignments(drmnOutputDir);
scMgr.showClusters_Extant(drmnOutputDir);
scMgr.showClusters_Ancestral(drmnOutputDir);
scMgr.showMeans(drmnOutputDir);
scMgr.dumpAllInferredClusters_LCA(drmnOutputDir,speciesList,sdMgr.getRoot()->name);
scMgr.dumpAllInferredClusterGammas(drmnOutputDir,speciesList);
//Then we will generate test predictions
scMgr.getTestPerformance(drmnOutputDir,testIDs);
// collect test data likelihood
double unpenalized;
double penalized;
scMgr.getDRMNScore_test(testIDs, unpenalized, penalized);
// print to console for now
cout << "TrainDRMN UnpenalizedLL " << trainUnpen << " PenalizedLL " << trainPen << endl;
cout << "TestDRMN UnpenalizedLL " << unpenalized << " PenalizedLL " << penalized << endl;
// print likelihoods to file
char llName[1024];
sprintf(llName,"%s/fold%d/drmn/likelihood.txt",outputDir, f);
ofstream oFile(llName);
oFile << "Data\tUnpenalizedLL\tPenalizedLL" << endl;
oFile << "Train_" << f << "\t" << trainUnpen << "\t" << trainPen << endl;
oFile << "Test_" << f << "\t" << unpenalized << "\t" << penalized << endl;
oFile.close();
cout << "Wrote likelihood scores to " << llName << endl;
scMgr.clear();
trainIDs.clear();
testIDs.clear();
}
return 0;
}
/*
* Prints out all the files to a results directory.
* Useful for printing out the EMINT-initialization results before running DRMN.
*/
int
Framework::printResults(const char* outputDir)
{
scMgr.dumpAllInferredClusterAssignments(outputDir);
scMgr.showClusters_Extant(outputDir);
scMgr.showClusters_Ancestral(outputDir);
scMgr.showMeans(outputDir);
vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
scMgr.dumpAllInferredClusters_LCA(outputDir,speciesList,sdMgr.getRoot()->name);
scMgr.dumpAllInferredClusterGammas(outputDir,speciesList);
sdMgr.showInferredConditionals(outputDir);
return 0;
}
int
Framework::generateData(const char* outputDir)
{
scMgr.initExperts();
//Lets do one round of learning shall we.
initClusterTransitionProb();
scMgr.estimateExpertParameters(outputDir);
sdMgr.showInferredConditionals(outputDir);
scMgr.showMeans(outputDir);
char dirName[1024];
sprintf(dirName,"mkdir -p %s/samples",outputDir);
system(dirName);
sprintf(dirName,"%s/samples",outputDir);
vector<string> speciesList;
sdMgr.getSpeciesListPrefix(speciesList);
scMgr.generateData(dirName,sdMgr.getRoot()->name,speciesList);
return 0; // ENDS HERE
/*char fName[1024];
//Assume we want to generate the same number of genes as in the original data
SpeciesDistManager::Species* root=sdMgr.getRoot();
map<string,CLUSTERSET*>& extantSpeciesSet=scMgr.getExtantSpeciesClusters();
map<string,ofstream*> filePtrSet;
map<string,ofstream*> filePtrClusteredSet;
map<string,ofstream*> clusterFilePtrSet;
map<string,map<int,int>*> speciesClusterDist;
map<string,map<int,map<string,int>*>*> speciesClusterMembers;
for(map<string,CLUSTERSET*>::iterator sIter=extantSpeciesSet.begin();sIter!=extantSpeciesSet.end();sIter++)
{
sprintf(fName,"%s/%s_samples.txt",outputDir,sIter->first.c_str());
ofstream* oFile=new ofstream(fName);
filePtrSet[sIter->first]=oFile;
sprintf(dirName,"mkdir -p %s/%s",outputDir,sIter->first.c_str());
system(dirName);
sprintf(fName,"%s/%s/clusterassign.txt",outputDir,sIter->first.c_str());
ofstream* cFile=new ofstream(fName);
clusterFilePtrSet[sIter->first]=cFile;
}
map<int,MappedOrthogroup*>& ogSet=mor.getMappedOrthogroups();
vector<double> sampleValues;
char clusterAssignmentFName[1024];
sprintf(clusterAssignmentFName,"%s/clusterassign_multspecies.txt",outputDir);
ofstream caFile(clusterAssignmentFName);
string scer(srcSpecies);
map<string,int>* scerGenes=scMgr.getGenesForSpecies(scer);
int shown=0;
for(map<string,int>::iterator gIter=scerGenes->begin();gIter!=scerGenes->end();gIter++)
{
int cId=sampleAncestralCluster(randnum,root);
map<string,int>* clusterAssign=new map<string,int>;
clusterAssignments[gIter->first]=clusterAssign;
(*clusterAssign)[root->name]=cId;
//sampleChildCluster(randnum,root->leftchild,cId,*clusterAssign);
//sampleChildCluster(randnum,root->rightchild,cId,*clusterAssign);
for (int i=0; i<root->children.size(); i++) {
sampleChildCluster(randnum,root->children[i],cId,*clusterAssign);
}
caFile << gIter->first;
for(map<string,int>::iterator cIter=clusterAssign->begin();cIter!=clusterAssign->end();cIter++)
{
cout<<" " <<cIter->first <<"=" << cIter->second;
caFile<<"\t" <<cIter->first <<"=" << cIter->second;
map<int,int>* clusterCnt=NULL;
if(speciesClusterDist.find(cIter->first)==speciesClusterDist.end())
{
clusterCnt=new map<int,int>;
speciesClusterDist[cIter->first]=clusterCnt;
}
else
{
clusterCnt=speciesClusterDist[cIter->first];
}
if(clusterCnt->find(cIter->second)==clusterCnt->end())
{
(*clusterCnt)[cIter->second]=1;
}
else
{
(*clusterCnt)[cIter->second]=(*clusterCnt)[cIter->second]+1;
}
}
caFile<< endl;
cout << endl;
int ogid=mor.getMappedOrthogroupID(gIter->first.c_str(),srcSpecies);
MappedOrthogroup* mgrp=ogSet[ogid];
//Then for all extant species draw the expression vector
for(map<string,CLUSTERSET*>::iterator sIter=extantSpeciesSet.begin();sIter!=extantSpeciesSet.end();sIter++)
{
CLUSTERSET* clusterSet=sIter->second;
int specClustId=(*clusterAssign)[sIter->first];
Expert* e=(*clusterSet)[specClustId];
e->generateSample(randnum,sampleValues);
GeneMap* gMap=mgrp->getSpeciesHits(sIter->first.c_str());
ofstream* oFile=filePtrSet[sIter->first];
ofstream* cFile=clusterFilePtrSet[sIter->first];
const string& geneName=gMap->getGeneSet().begin()->first;
(*cFile) <<geneName <<"\t" << specClustId <<endl;
(*oFile) << geneName;
for(int j=0;j<sampleValues.size();j++)
{
(*oFile) <<"\t" << sampleValues[j];
}
(*oFile) << endl;
sampleValues.clear();
}
shown++;
//clusterAssign.clear();
}
for(map<string,ofstream*>::iterator fIter=filePtrSet.begin();fIter!=filePtrSet.end();fIter++)
{
fIter->second->close();
ofstream* cFile=clusterFilePtrSet[fIter->first];
cFile->close();
}
caFile.close();
scMgr.showClusters_Extant(outputDir);
//Cluster size dist
for(map<string,map<int,int>*>::iterator sIter=speciesClusterDist.begin();sIter!=speciesClusterDist.end();sIter++)
{
cout <<sIter->first;
map<int,int>* sizeDist=sIter->second;
for(map<int,int>::iterator aIter=sizeDist->begin();aIter!=sizeDist->end();aIter++)
{
cout <<" " << aIter->first<<":"<< aIter->second;
}
cout << endl;
}
return 0;*/
} // end "generate"
int
Framework::redisplay(const char* outputDir)
{
scMgr.initExperts();
scMgr.showClusters(outputDir);
//Only redisplay the data
return 0;
}
int
Framework::setPdiagonalLeaf(double aval)
{
p_diagonal_leaf=aval;
return 0;
}
int
Framework::setPdiagonalNonLeaf(double aval)
{
p_diagonal_nonleaf=aval;
return 0;
}
//Need to initialize a conditional distribution for every branch which species
//the probability of transitioning from cluster k to cluster j
//TODO: initialize using the ribosomal clusters or some known cluster membership across species
//TODO: Use the rate and the branch length information
int
Framework::initClusterTransitionProb()
{
SpeciesDistManager::Species* root=sdMgr.getRoot();
Matrix* conditional=root->getParams();
int colcnt=conditional->getColCnt();
for(int i=0;i<colcnt;i++)
{
double aval=1/((double)colcnt);
conditional->setValue(aval,0,i);
}
for (int i=0; i<root->children.size(); i++) {
initClusterTransitionProb(root->children[i]);
}
//initClusterTransitionProb(root->leftchild);
//initClusterTransitionProb(root->rightchild);
return 0;
}
int
Framework::initClusterTransitionProb(SpeciesDistManager::Species* anode)
{
cout <<"Transitions for " << anode->name << endl;
//if(anode->leftchild==NULL)
if (anode->children.empty())
{
if(clusterTransitionProb.find(anode->name)==clusterTransitionProb.end())
{
cout <<"No cluster transition prob for " << anode->name << endl;
exit(0);
}
double pval=clusterTransitionProb[anode->name];
initTransitionProb(anode->getParams(),pval);
}
else
{
if(clusterTransitionProb.find(anode->name)==clusterTransitionProb.end())
{
cout <<"No cluster transition prob for " << anode->name << endl;
exit(0);
}
double pval=clusterTransitionProb[anode->name];
initTransitionProb(anode->getParams(),pval);
}
/*
if(anode->leftchild!=NULL)
{
cout <<"Transitions for " << anode->leftchild->name << endl;
initClusterTransitionProb(anode->leftchild);
cout <<"Transitions for " << anode->rightchild->name << endl;
initClusterTransitionProb(anode->rightchild);
}*/
for (int i=0; i<anode->children.size(); i++) {
cout <<"Transitions for " << anode->children[i]->name << endl;
initClusterTransitionProb(anode->children[i]);
}
return 0;
}
//The matrix is supposed to be a transition matrix of going from cluster k to cluster l
int
Framework::initTransitionProb(Matrix* m,double initval)
{
int rowcnt=m->getRowCnt();
int colcnt=m->getColCnt();
for (int i=0;i<rowcnt;i++)
{
double s=0;
for(int j=0;j<colcnt;j++)
{
double aval=0;
if(i==j)
{
aval=initval;
}
else
{
aval=(1-initval)/((double) (rowcnt-1));
}
// returns random value between 0 and 0.01
// randnum is the RNG
double err=gsl_ran_flat(randnum,0,0.01);
m->setValue(aval+err,i,j);
s=s+err+aval;
}
for(int j=0;j<colcnt;j++)
{
double aval=m->getValue(i,j);
aval=aval/s;
m->setValue(aval,i,j);
}
}
m->showMatrix(1e-5);
return 0;
}
int
Framework::inferAncestralClusters(map<int,map<string,int>*>& clusterAssignments)
{
cout <<"Inferring ancestral clusters" << endl;
map<string,map<int,int>*> speciesClusterSizeDist;
int disp=0;
for(map<int,map<string,int>*>::iterator cIter=clusterAssignments.begin();cIter!=clusterAssignments.end();cIter++)
{
map<string,int>* extantClustering=cIter->second;
map<string,int> ancestralClustering;
sdMgr.getAncestralClustering(*extantClustering,ancestralClustering);
for(map<string,int>::iterator aIter=ancestralClustering.begin();aIter!=ancestralClustering.end();aIter++)
{
(*extantClustering)[aIter->first]=aIter->second;
}
for(map<string,int>::iterator aIter=extantClustering->begin();aIter!=extantClustering->end();aIter++)
{
map<int,int>* clusterCnts=NULL;
if(speciesClusterSizeDist.find(aIter->first)==speciesClusterSizeDist.end())
{
clusterCnts=new map<int,int>;
speciesClusterSizeDist[aIter->first]=clusterCnts;
}
else
{
clusterCnts=speciesClusterSizeDist[aIter->first];
}
if(clusterCnts->find(aIter->second)==clusterCnts->end())
{
(*clusterCnts)[aIter->second]=1;
}
else
{
(*clusterCnts)[aIter->second]=(*clusterCnts)[aIter->second]+1;
}
}
/*if(cIter==clusterAssignments.begin())
{
cout<<"Gene";
for(map<string,int>::iterator aIter=extantClustering->begin();aIter!=extantClustering->end();aIter++)
{
cout <<" " << aIter->first;
}
cout << endl;
}*/
if(disp<10)
{
cout<<cIter->first;
for(map<string,int>::iterator aIter=extantClustering->begin();aIter!=extantClustering->end();aIter++)
{
cout <<" " << aIter->first<<"="<< aIter->second;
}
cout << endl;
}
disp++;
}
for(map<string,map<int,int>*>::iterator sIter=speciesClusterSizeDist.begin();sIter!=speciesClusterSizeDist.end();sIter++)
{
cout <<sIter->first;
map<int,int>* csize=sIter->second;
for(map<int,int>::iterator cIter=csize->begin();cIter!=csize->end();cIter++)
{
cout <<" " << cIter->first <<":"<< cIter->second;
}
cout << endl;
}
return 0;
}
int
Framework::inferExtantClusters(map<int,map<string,int>*>& clusterAssignments)
{
cout <<"Inferring extant clusters" << endl;
map<string,map<int,int>*> speciesClusterSizeDist;
int disp=0;
for(map<int,map<string,int>*>::iterator cIter=clusterAssignments.begin();cIter!=clusterAssignments.end();cIter++)
{
map<string,int>* ancestralClustering=cIter->second;
map<string,int> extantClustering;
sdMgr.getExtantClustering(*ancestralClustering,extantClustering);
for(map<string,int>::iterator aIter=extantClustering.begin();aIter!=extantClustering.end();aIter++)
{
(*ancestralClustering)[aIter->first]=aIter->second;
}
for(map<string,int>::iterator aIter=ancestralClustering->begin();aIter!=ancestralClustering->end();aIter++)
{
map<int,int>* clusterCnts=NULL;
if(speciesClusterSizeDist.find(aIter->first)==speciesClusterSizeDist.end())
{
clusterCnts=new map<int,int>;
speciesClusterSizeDist[aIter->first]=clusterCnts;
}
else
{
clusterCnts=speciesClusterSizeDist[aIter->first];
}
if(clusterCnts->find(aIter->second)==clusterCnts->end())
{
(*clusterCnts)[aIter->second]=1;
}
else
{
(*clusterCnts)[aIter->second]=(*clusterCnts)[aIter->second]+1;
}
}
/*if(cIter==clusterAssignments.begin())
{
cout<<"Gene";
for(map<string,int>::iterator aIter=ancestralClustering->begin();aIter!=ancestralClustering->end();aIter++)
{
cout <<" " << aIter->first;
}
cout << endl;
}*/
if(disp<10)
{
cout<<cIter->first;
for(map<string,int>::iterator aIter=ancestralClustering->begin();aIter!=ancestralClustering->end();aIter++)
{
cout <<" " << aIter->first<<"="<< aIter->second;
}
cout << endl;
}
disp++;
}
for(map<string,map<int,int>*>::iterator sIter=speciesClusterSizeDist.begin();sIter!=speciesClusterSizeDist.end();sIter++)
{
cout <<sIter->first;
map<int,int>* csize=sIter->second;
for(map<int,int>::iterator cIter=csize->begin();cIter!=csize->end();cIter++)
{
cout <<" " << cIter->first <<":"<< cIter->second;
}
cout << endl;
}
return 0;
}
int
Framework::estimateClusterTransProb(map<int,map<string,int>*>& clusterAssignments)
{
SpeciesDistManager::Species* root=sdMgr.getRoot();
//Estimate prior of the root
Matrix* rootparam=root->conditional;
rootparam->setAllValues(1e-5);
for(map<int,map<string,int>*>::iterator aIter=clusterAssignments.begin();aIter!=clusterAssignments.end();aIter++)
{
int cid=(*aIter->second)[root->name];
double aval=rootparam->getValue(cid,0);
aval=aval+1;
rootparam->setValue(aval,cid,0);
}
for(int i=0;i<rootparam->getRowCnt();i++)
{
double aval=rootparam->getValue(i,0)/clusterAssignments.size();
rootparam->setValue(aval,i,0);
}
rootparam->showMatrix(1e-5);
//estimateClusterTransProb(root,root->leftchild,clusterAssignments);
//estimateClusterTransProb(root,root->rightchild,clusterAssignments);
for (int i=0; i<root->children.size(); i++) {
estimateClusterTransProb(root,root->children[i],clusterAssignments);
}
return 0;
}
int
Framework::estimateClusterTransProb(SpeciesDistManager::Species* parent, SpeciesDistManager::Species* child, map<int,map<string,int>*>& clusterAssignments)
{
estimateTransitionMatrix(parent->name,child->name,child,clusterAssignments);
/*if(child->leftchild!=NULL)
{
estimateClusterTransProb(child,child->leftchild,clusterAssignments);
estimateClusterTransProb(child,child->rightchild,clusterAssignments);
}*/
for (int i=0; i<child->children.size(); i++) {
estimateClusterTransProb(child,child->children[i],clusterAssignments);
}
return 0;
}
int
Framework::estimateTransitionMatrix(string& parentname,string& childname, SpeciesDistManager::Species* child, map<int,map<string,int>*>& clusterAssignments)
{
Matrix* param=child->getParams();
param->setAllValues(1);
for(map<int,map<string,int>*>::iterator cIter=clusterAssignments.begin();cIter!=clusterAssignments.end();cIter++)
{
map<string,int>* assignments=cIter->second;
int ancid=(*assignments)[parentname];
int childid=(*assignments)[childname];
double currval=param->getValue(ancid,childid);
currval=currval+1;
param->setValue(currval,ancid,childid);
}
cout <<"New Params for " << childname << " before norm " << endl;
param->showMatrix(1e-5);
//Row is for ancestral cluster id. Cols in a row must add to 1
for(int i=0;i<param->getRowCnt();i++)
{
double sum=0;
for(int j=0;j<param->getColCnt();j++)
{
sum=sum+param->getValue(i,j);
}
for(int j=0;j<param->getColCnt();j++)
{
double prob=param->getValue(i,j);
prob=prob/sum;
param->setValue(prob,i,j);
}
}
cout <<"After normalzation" << childname << endl;
param->showMatrix(1e-5);
return 0;
}
bool
Framework::checkConvergence(map<int,map<string,int>*>& clusterAssignments,map<int,map<string,int>*>& oldclusterAssignments)
{
bool convergence=false;
int changes=0;
for(map<int,map<string,int>*>::iterator cIter=clusterAssignments.begin();cIter!=clusterAssignments.end();cIter++)
{
map<string,int>* newassign=cIter->second;
map<string,int>* oldassign=oldclusterAssignments[cIter->first];
for(map<string,int>::iterator nIter=newassign->begin();nIter!=newassign->end();nIter++)
{
if(oldassign->find(nIter->first)==oldassign->end())
{
cout <<"Fatal error " << endl;
exit(0);
}
int currassignval=(*oldassign)[nIter->first];
if(currassignval!=nIter->second)
{
changes++;
}
}
}
if(changes==0)
{
convergence=true;
}
return convergence;
}
int
Framework::saveClusterAssignments(map<int,map<string,int>*>& clusterAssignments,map<int,map<string,int>*> &oldclusterAssignments)
{
for(map<int,map<string,int>*>::iterator aIter=oldclusterAssignments.begin();aIter!=oldclusterAssignments.end();aIter++)
{
//delete aIter->second;
//aIter->second->clear();
}
//oldclusterAssignments.clear();
for(map<int,map<string,int>*>::iterator bIter=clusterAssignments.begin();bIter!=clusterAssignments.end();bIter++)
{
map<string,int>* newassign=NULL;
if(oldclusterAssignments.find(bIter->first)==oldclusterAssignments.end())
{
newassign=new map<string,int>;
oldclusterAssignments[bIter->first]=bIter->second;
}
else
{
newassign=oldclusterAssignments[bIter->first];
}
map<string,int>* oldassign=bIter->second;
for(map<string,int>::iterator dIter=oldassign->begin();dIter!=oldassign->end();dIter++)
{
//cout <<"updating " << bIter->first <<" "<< dIter->first << " " << dIter->second << endl;
(*newassign)[dIter->first]=dIter->second;
}
oldclusterAssignments[bIter->first]=newassign;
}
//clusterAssignments.clear();
return 0;
}
int
Framework::sampleAncestralCluster(gsl_rng* r,SpeciesDistManager::Species* root)
{
int clustId=-1;
double pval=gsl_ran_flat(r,0,1);
Matrix* params=root->getParams();
vector<int>* sortedClustIDs=root->getSortedClusterIDs(0);