-
Notifications
You must be signed in to change notification settings - Fork 69
/
WQDataCollection.java
1516 lines (1316 loc) · 47.7 KB
/
WQDataCollection.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package phylonet.coalescent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import phylonet.lca.SchieberVishkinLCA;
import phylonet.tree.model.MutableTree;
import phylonet.tree.model.TMutableNode;
import phylonet.tree.model.TNode;
import phylonet.tree.model.Tree;
import phylonet.tree.model.sti.STINode;
import phylonet.tree.model.sti.STITree;
import phylonet.tree.model.sti.STITreeCluster;
import phylonet.tree.util.Trees;
import phylonet.util.BitSet;
/**
* Sets up the set X
*
* @author smirarab
*
*/
public class WQDataCollection extends AbstractDataCollection<Tripartition>
implements Cloneable {
/**
* A list that includes the cluster associated with the set of all taxa
* included in each gene tree
*/
List<STITreeCluster> treeAllClusters = new ArrayList<STITreeCluster>();
/**
* Similarity matrices for individuals. Used for setting up set X
*/
SimilarityMatrix similarityMatrix;
/**
* Similarity matrices for species. Used for setting up set X
*/
SimilarityMatrix speciesSimilarityMatrix;
// Parameters of ASTRAL-II heuristics
private boolean SLOW = false;
private final double[] GREEDY_ADDITION_THRESHOLDS = new double[] { 0,
1 / 100., 1 / 50., 1 / 20., 1 / 10., 1 / 5., 1 / 3. };
private final int GREEDY_DIST_ADDITTION_LAST_THRESHOLD_INDX = 3;
private final int GREEDY_ADDITION_MAX_POLYTOMY_MIN = 50;
private final int GREEDY_ADDITION_MAX_POLYTOMY_MULT = 25;
private final int GREEDY_ADDITION_DEFAULT_RUNS = 10;
private final int GREEDY_ADDITION_MIN_FREQ = 5;
private final double GREEDY_ADDITION_MIN_RATIO = 0.01;
private final int GREEDY_ADDITION_MAX = 100;
private final int GREEDY_ADDITION_IMPROVEMENT_REWARD = 2;
private final int POLYTOMY_RESOLUTIONS = 3;
private final double POLYTOMY_RESOLUTIONS_GREEDY_GENESAMPLE = 0.9;
private List<Tree> geneTrees;
private boolean outputCompleted;
private String outfileName;
private final int POLYTOMY_RESOLUTIONS_SAMPLE_GRADIENT = 15000;
private final int POLYTOMY_SIZE_LIMIT_MAX = 100000;
private int polytomySizeLimit = POLYTOMY_SIZE_LIMIT_MAX;
// Just a reference to gene trees from inference (for convinience).
private List<Tree> originalInompleteGeneTrees;
/**
* Gene trees after completion.
*/
private List<Tree> completedGeeneTrees;
// A reference to user-spcified global options.
private Options options;
public WQDataCollection(WQClusterCollection clusters,
AbstractInference<Tripartition> inference) {
this.clusters = clusters;
this.SLOW = inference.options.getAddExtra() == 2;
this.originalInompleteGeneTrees = inference.trees;
this.completedGeeneTrees = new ArrayList<Tree>();
this.options = inference.options;
}
/**
* Once we have chosen a subsample with only one individual per species, we
* can use this metod to compute and add bipartitions from the input gene
* trees to set X. This is equivalent of ASTRAL-I set X computed for the
* subsample.
*
* @param allGenesGreedy
* @param trees
* @param taxonSample
* @param greedy
* is the greedy consensus of all gene trees
*/
private void addBipartitionsFromSignleIndTreesToX(Tree tr,
Collection<Tree> baseTrees, TaxonIdentifier id) {
Stack<STITreeCluster> stack = new Stack<STITreeCluster>();
for (TNode node : tr.postTraverse()) {
if (node.isLeaf()) {
STITreeCluster cluster = GlobalMaps.taxonNameMap
.getSpeciesIdMapper().getSTTaxonIdentifier()
.getClusterForNodeName(node.getName());
stack.add(cluster);
addSpeciesBipartitionToX(cluster);
} else {
ArrayList<BitSet> childbslist = new ArrayList<BitSet>();
BitSet bs = new BitSet(GlobalMaps.taxonNameMap
.getSpeciesIdMapper().getSTTaxonIdentifier()
.taxonCount());
for (TNode child : node.getChildren()) {
STITreeCluster pop = stack.pop();
childbslist.add(pop.getBitSet());
bs.or(pop.getBitSet());
}
/**
* Note that clusters added to the stack are currently using the
* global taxon identifier that has all individuals
*/
STITreeCluster cluster = GlobalMaps.taxonNameMap
.getSpeciesIdMapper().getSTTaxonIdentifier()
.newCluster();
cluster.setCluster(bs);
stack.add(cluster);
//boolean bug = false;
try {
if (addSpeciesBipartitionToX(cluster)) {
}
} catch (Exception e) {
//bug = true;
// System.err.println("node : "+node.toString());
// System.err.println("cluster : "+cluster);
// System.err.println(childbslist.size());
// System.err.println(childbslist);
// System.err.println("bs : "+bs);
e.printStackTrace();
}
/**
* For polytomies, if we don't do anything extra, the cluster
* associated with the polytomy may not have any resolutions in
* X. We don't want that. We use the greedy consensus trees and
* random sampling to add extra bipartitions to the input set
* when we have polytomies.
*/
if (childbslist.size() > 2) {
BitSet remaining = (BitSet) bs.clone();
remaining.flip(0, GlobalMaps.taxonNameMap
.getSpeciesIdMapper().getSTTaxonIdentifier()
.taxonCount());
// if (bug) {
// System.err.println(remaining);
// }
//
boolean isRoot = remaining.isEmpty();
int d = childbslist.size() + (isRoot ? 0 : 1);
BitSet[] polytomy = new BitSet[d];
int i = 0;
for (BitSet child : childbslist) {
polytomy[i++] = child;
}
if (!isRoot) {
polytomy[i] = remaining;
}
// TODO: do multiple samples
int gradient = Integer.MAX_VALUE;
for(int ii = 0 ; ii < 3; ii++){
int b = this.clusters.getClusterCount();
HashMap<String, Integer> randomSample = this.randomSampleAroundPolytomy(polytomy, GlobalMaps.taxonNameMap
.getSpeciesIdMapper().getSTTaxonIdentifier());
// int sampleAndResolveRounds = 4;
// for (int j = 0; j < sampleAndResolveRounds; j++) {
// sampleAndResolve(polytomy,inputTrees, false, speciesSimilarityMatrix, GlobalMaps.taxonNameMap
// .getSpeciesIdMapper()
// .getSTTaxonIdentifier(), false, true);
// }
for (Tree gct : baseTrees){
for (BitSet restrictedBitSet : Utils.getBitsets(
randomSample, gct)) {
/**
* Before adding bipartitions from the greedy consensus
* to the set X we need to add the species we didn't
* sample to the bitset.
*/
restrictedBitSet = this.addbackAfterSampling(polytomy,
restrictedBitSet, GlobalMaps.taxonNameMap
.getSpeciesIdMapper()
.getSTTaxonIdentifier());
this.addSpeciesBitSetToX(restrictedBitSet);
}
gradient = this.clusters.getClusterCount() - b;
}
gradient = this.clusters.getClusterCount() - b;
}
}
}
}
}
/**
* How many rounds of sampling should we do? Completely arbitrarily at this
* point. Should be better explored.
*
* @param userProvidedRounds
* @return
*/
private int getSamplingRepeationFactor(int userProvidedRounds) {
if (userProvidedRounds < 1) {
double sampling = GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.meanSampling();
int repeat = (int) (int) Math.ceil(Math.log(2*sampling)/Math.log(2));
return repeat;
} else {
return userProvidedRounds;
}
}
/**
* Completes an incomplete tree for the purpose of adding to set X
* Otherwise, bipartitions are meaningless.
*
* @param tr
* @param gtAllBS
* @return
*/
Tree getCompleteTree(Tree tr, BitSet gtAllBS) {
if (gtAllBS.cardinality() < 3) {
throw new RuntimeException("Tree " + tr.toNewick()
+ " has less than 3 taxa; it cannot be completed");
}
STITree trc = new STITree(tr);
Trees.removeBinaryNodes(trc);
for (int missingId = gtAllBS.nextClearBit(0); missingId < GlobalMaps.taxonIdentifier
.taxonCount(); missingId = gtAllBS.nextClearBit(missingId + 1)) {
int closestId = similarityMatrix.getClosestPresentTaxonId(gtAllBS,
missingId);
STINode closestNode = trc.getNode(GlobalMaps.taxonIdentifier
.getTaxonName(closestId));
trc.rerootTreeAtNode(closestNode);
Trees.removeBinaryNodes(trc);
Iterator cit = trc.getRoot().getChildren().iterator();
STINode c1 = (STINode) cit.next();
STINode c2 = (STINode) cit.next();
STINode start = closestNode == c1 ? c2 : c1;
int c1random = -1;
int c2random = -1;
while (true) {
if (start.isLeaf()) {
break;
}
cit = start.getChildren().iterator();
c1 = (STINode) cit.next();
c2 = (STINode) cit.next();
// TODO: what if c1 or c2 never appears in the same tree as
// missing and closestId .
if (c1random == -1) {
c1random = GlobalMaps.taxonIdentifier.taxonId(Utils
.getLeftmostLeaf(c1));
}
if (c2random == -1) {
c2random = GlobalMaps.taxonIdentifier.taxonId(Utils
.getLeftmostLeaf(c2));
}
int betterSide = similarityMatrix.getBetterSideByFourPoint(
missingId, closestId, c1random, c2random);
if (betterSide == closestId) {
break;
} else if (betterSide == c1random) {
start = c1;
// Currently, c1random is always under left side of c1
c2random = -1;
} else if (betterSide == c2random) {
start = c2;
// Currently, c2random is always under left side of c2
c1random = c2random;
c2random = -1;
}
}
if (start.isLeaf()) {
STINode newnode = start.getParent().createChild(
GlobalMaps.taxonIdentifier.getTaxonName(missingId));
STINode newinternalnode = start.getParent().createChild();
newinternalnode.adoptChild(start);
newinternalnode.adoptChild(newnode);
} else {
STINode newnode = start.createChild(GlobalMaps.taxonIdentifier
.getTaxonName(missingId));
STINode newinternalnode = start.createChild();
newinternalnode.adoptChild(c1);
newinternalnode.adoptChild(c2);
}
}
return trc;
}
/**
* Given a bitset that shows one side of a bipartition this method adds the
* bipartition to the set X. Importantly, when the input bitset has only one
* (or a sbuset) of individuals belonging to a species set, the other
* individuals from that species are also set to one before adding the
* bipartition to the set X. Thus, all individuals from the same species
* will be on the same side of the bipartition. These additions are done on
* a copy of the input bitset not the instance passed in.
*
* @param stBitSet
* @return was the cluster new?
*/
// private boolean addSingleIndividualBitSetToX(final BitSet bs) {
// STITreeCluster cluster = GlobalMaps.taxonIdentifier.newCluster();
// cluster.setCluster(bs);
// return this.addSingleIndividualBipartitionToX(cluster);
// }
private boolean addSpeciesBitSetToX(final BitSet stBitSet) {
STITreeCluster cluster = GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier().newCluster();
// BitSet sBS = GlobalMaps.taxonNameMap.getSpeciesIdMapper()
// .getGeneBisetForSTBitset(bs);
// cluster.setCluster(sBS);
cluster.setCluster(stBitSet);
return this.addSpeciesBipartitionToX(cluster);
}
/**
* Adds bipartitions to X. When only one individual from each species is
* sampled, this method adds other individuals from that species to the
* cluster as well, but note that these additions are done on a copy of c1
* not c1 itself.
*/
private boolean addSpeciesBipartitionToX(final STITreeCluster stCluster) {
boolean added = false;
STITreeCluster c1GT = GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getGeneClusterForSTCluster(stCluster);
added |= this.addCompletedSpeciesFixedBipartionToX(c1GT,
c1GT.complementaryCluster());
// if (added) { System.err.print(".");}
return added;
}
/**
* Adds extra bipartitions added by user using the option -e and -f
*/
public void addExtraBipartitionsByInput(List<Tree> extraTrees,
boolean extraTreeRooted) {
//List<Tree> completedExtraGeeneTrees = new ArrayList<Tree>();
for (Tree tr : extraTrees) {
String[] gtLeaves = tr.getLeaves();
STITreeCluster gtAll = GlobalMaps.taxonIdentifier.newCluster();
for (int i = 0; i < gtLeaves.length; i++) {
gtAll.addLeaf(GlobalMaps.taxonIdentifier.taxonId(gtLeaves[i]));
}
Tree trc = getCompleteTree(tr, gtAll.getBitSet());
STITree stTrc = new STITree(trc);
GlobalMaps.taxonNameMap.getSpeciesIdMapper().gtToSt((MutableTree) stTrc);
if(hasPolytomy(stTrc)){
throw new RuntimeException("Extra tree shouldn't have polytomy ");
}
ArrayList<Tree> st = new ArrayList<Tree>();
st.add(stTrc);
addBipartitionsFromSignleIndTreesToX(stTrc,st, GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier());
}
}
public void removeTreeBipartitionsFromSetX(STITree st){
List<STITreeCluster> stClusters = Utils.getGeneClusters(st, GlobalMaps.taxonIdentifier);
int size;
for(int i = 0; i < stClusters.size(); i++){
STITreeCluster cluster = stClusters.get(i);
size = cluster.getClusterSize();
removeCluster(cluster, size);
// System.err.println(size+ cluster.toString());
STITreeCluster comp = cluster.complementaryCluster();
if(comp.getClusterSize() < GlobalMaps.taxonIdentifier.taxonCount() - 1){
removeCluster(comp, size);
}
}
}
public void removeExtraBipartitionsByInput(List<Tree> extraTrees,
boolean extraTreeRooted) {
for (Tree tr : extraTrees) {
System.err.println(tr.toNewick());
STITree stTrc = new STITree(tr);
GlobalMaps.taxonNameMap.getSpeciesIdMapper().gtToSt((MutableTree) stTrc);
removeTreeBipartitionsFromSetX(stTrc);
}
}
public boolean hasPolytomy(Tree tr){
for (TNode node : tr.postTraverse()) {
if(node.getChildCount() > 2){
return true;
}
}
return false;
}
/**
* Adds a bipartition to the set X. This method assumes inputs are already
* fixed to have all individuals of the same species.
*
* @param c1
* @param c2
* @return was the cluster new?
*/
private boolean addCompletedSpeciesFixedBipartionToX(STITreeCluster c1,
STITreeCluster c2) {
boolean added = false;
int size = c1.getClusterSize();
/*
* TODO: check if this change is correct
*/
if (size == GlobalMaps.taxonIdentifier.taxonCount()
|| size == 0) {
return false;
}
// System.err.println("size:" + size);
added |= addToClusters(c1, size);
size = c2.getClusterSize();
added |= addToClusters(c2, size);
return added;
}
// /***
// * Computes and adds partitions from the input set (ASTRAL-I)
// * Also, adds extra bipartitions using ASTRAL-II heuristics.
// * Takes care of multi-individual dataset subsampling.
// */
// @Override
// public void formSetX(AbstractInference<Tripartition> inf) {
//
// WQInference inference = (WQInference) inf;
// int haveMissing = preProcess(inference);
// SpeciesMapper spm = GlobalMaps.taxonNameMap.getSpeciesIdMapper();
//
// calculateDistances();
//
// if (haveMissing > 0 ) {
// completeGeneTrees();
// } else {
// this.completedGeeneTrees = this.originalInompleteGeneTrees;
// }
//
// /*
// * Calculate gene tree clusters and bipartitions for X
// */
// STITreeCluster all = GlobalMaps.taxonIdentifier.newCluster();
// all.getBitSet().set(0, GlobalMaps.taxonIdentifier.taxonCount());
// addToClusters(all, GlobalMaps.taxonIdentifier.taxonCount());
//
// System.err.println("Building set of clusters (X) from gene trees ");
//
//
// /**
// * This is where we randomly sample one individual per species
// * before performing the next steps in construction of the set X.
// */
// int maxRepeat =
// getSamplingRepeationFactor(inference.options.getSamplingrounds());
//
// if (maxRepeat > 1)
// System.err.println("Average sampling is "+ spm.meanSampling() +
// ".\nWill do "+maxRepeat+" rounds of sampling ");
//
// //System.err.println(this.completedGeeneTrees.get(0));
// int prev = 0, firstgradiant = -1, gradiant = 0;
// for (int r = 0; r < maxRepeat; r++) {
//
// System.err.println("------------\n"
// + "Round " +r +" of individual sampling ...");
// SingleIndividualSample taxonSample = new
// SingleIndividualSample(spm,this.similarityMatrix);
//
// System.err.println("taxon sample " +
// Arrays.toString(taxonSample.getTaxonIdentifier().getAllTaxonNames()));
//
// List<Tree> contractedTrees =
// taxonSample.contractTrees(this.completedGeeneTrees);
//
// //System.err.println(trees.get(0));
//
// addBipartitionsFromSignleIndTreesToX(contractedTrees, taxonSample);
//
// System.err.println("Number of clusters after simple addition from gene trees: "
// + clusters.getClusterCount());
//
// if (inference.getAddExtra() != 0) {
// System.err.println("calculating extra bipartitions to be added at level "
// + inference.getAddExtra() +" ...");
// this.addExtraBipartitionByHeuristics(contractedTrees, taxonSample);
//
// System.err.println("Number of Clusters after addition by greedy: " +
// clusters.getClusterCount());
// gradiant = clusters.getClusterCount() - prev;
// prev = clusters.getClusterCount();
// if (firstgradiant == -1)
// firstgradiant = gradiant;
// else {
// //System.err.println("First gradiant: " + firstgradiant+
// " current gradiant: " + gradiant);
// if (gradiant < firstgradiant / 10) {
// //break;
// }
// }
//
// }
// }
// System.err.println();
//
// System.err.println("Number of Default Clusters: " +
// clusters.getClusterCount());
//
// }
/***
* Computes and adds partitions from the input set (ASTRAL-I) Also, adds
* extra bipartitions using ASTRAL-II heuristics. Takes care of
* multi-individual dataset subsampling.
*/
@Override
public void formSetX(AbstractInference<Tripartition> inf) {
WQInference inference = (WQInference) inf;
int haveMissing = preProcess(inference);
SpeciesMapper spm = GlobalMaps.taxonNameMap.getSpeciesIdMapper();
calculateDistances();
if (this.options.getAddExtra() != 3) {
if (haveMissing > 0) {
completeGeneTrees();
} else {
this.completedGeeneTrees = new ArrayList<Tree>(this.originalInompleteGeneTrees.size());
for (Tree t: this.originalInompleteGeneTrees) {
this.completedGeeneTrees.add(new STITree(t));
}
}
} else {
System.err.println("Using extranl trees as completed input gene trees");
if (inference.extraTrees.size() != this.originalInompleteGeneTrees.size())
System.err.println("WARNING: you provided fewer trees with -p3 -e than there are gene trees. "
+ "This is not expected");
for (Tree tr : inference.extraTrees) {
STITree stTrc = (STITree) tr; //new STITree(tr);
//GlobalMaps.taxonNameMap.getSpeciesIdMapper().gtToSt((MutableTree) stTrc);
if(hasPolytomy(stTrc)){
throw new RuntimeException("Extra tree shouldn't have polytomy ");
}
if (stTrc.getLeafCount() != GlobalMaps.taxonIdentifier.taxonCount()) {
throw new RuntimeException("With -p 3, all extra trees should be complete. "
+ "The following tree has missing data:\n" + tr);
}
this.completedGeeneTrees.add(stTrc);
}
}
System.err.println("Building set of clusters (X) from gene trees ");
// List<STITreeCluster> upgma = new ArrayList<STITreeCluster>();
// for(BitSet b : this.speciesSimilarityMatrix.UPGMA()){
// STITreeCluster sti = new STITreeCluster(GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier());
// sti.setCluster(b);
// upgma.add(sti);
// }
// Tree t = Utils.buildTreeFromClusters(upgma, GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier(), false);
// System.out.println(t.toNewick());
// java.lang.System.exit(0);
/**
* This is where we randomly sample one individual per species before
* performing the next steps in construction of the set X.
*/
int firstRoundSampling = 400;
//double sampling = GlobalMaps.taxonNameMap.getSpeciesIdMapper().meanSampling();
//int secondRoundSampling = (int) Math.ceil(Math.log(2*sampling)/Math.log(2));
int secondRoundSampling = getSamplingRepeationFactor(inference.options.getSamplingrounds());;
ArrayList<SingleIndividualSample> firstRoundSamples = new ArrayList<SingleIndividualSample>();
int K =100;
STITreeCluster all = GlobalMaps.taxonIdentifier.newCluster();
all.getBitSet().set(0, GlobalMaps.taxonIdentifier.taxonCount());
addToClusters(all, GlobalMaps.taxonIdentifier.taxonCount());
int arraySize = this.completedGeeneTrees.size();
List<Tree> [] allGreedies = new List [arraySize];
int prev = 0, gradiant = 0;
if (GlobalMaps.taxonNameMap.getSpeciesIdMapper().isSingleIndividual()) {
int gtindex = 0;
for (Tree gt : this.completedGeeneTrees) {
ArrayList<Tree> tmp = new ArrayList<Tree>();
STITree gtrelabelled = new STITree( gt);
GlobalMaps.taxonNameMap.getSpeciesIdMapper().gtToSt((MutableTree) gtrelabelled);
tmp.add(gtrelabelled);
allGreedies[gtindex++] = tmp;
}
} else {
//System.err.println("In the first round of sampling "
// + firstRoundSampling + " samples will be taken");
/*
* instantiate k random samples
*/
for (int r = 0; r < secondRoundSampling*K; r++) {
//System.err.println("------------\n" + "sample " + (r+1)
// + " of individual sampling ...");
SingleIndividualSample taxonSample = new SingleIndividualSample(
spm, this.similarityMatrix);
firstRoundSamples.add(taxonSample);
}
System.err.println("In second round sampling "+secondRoundSampling+" rounds will be done");
int gtindex = 0;
for (Tree gt : this.completedGeeneTrees) {
// System.err.println("gene tree number " + i + " is processing..");
ArrayList<Tree> firstRoundSampleTrees = new ArrayList<Tree>();
for (SingleIndividualSample sample : firstRoundSamples) {
Tree contractedTree = sample.contractTree(gt);
contractedTree.rerootTreeAtEdge(GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getSTTaxonIdentifier().getTaxonName(0));
Trees.removeBinaryNodes((MutableTree)contractedTree);
// returns a tree with species label
firstRoundSampleTrees.add(contractedTree);
}
ArrayList<Tree> greedies = new ArrayList<Tree>();
for (int r = 0; r < secondRoundSampling; r++) {
List<Tree> sample;
//Collections.shuffle(firstRoundSampleTrees, GlobalMaps.random);
sample = firstRoundSampleTrees.subList(r*K, K*r+99);
greedies.add(Utils.greedyConsensus(sample, false,
GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getSTTaxonIdentifier(), true));
}
allGreedies[gtindex++]=greedies;
// System.err.println("Number of clusters after simple addition from gene trees: "
// + clusters.getClusterCount());
}
}
/**
* generate a list of sampled gene trees selecting each one randomly
*/
// ArrayList<Tree> greedyCandidates = new ArrayList<Tree>();
//
// for (List<Tree> l : allGreedies) {
// int rand = GlobalMaps.random.nextInt(l.size());
// STITree temp = new STITree(l.get(rand));
// //System.err.println(temp);
// resolveByUPGMA((MutableTree) temp, GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier(), this.speciesSimilarityMatrix);
// greedyCandidates.add(temp);
//
// }
ArrayList<Tree> baseTrees = new ArrayList<Tree>();
List<STITreeCluster> upgma = new ArrayList<STITreeCluster>();
for(BitSet b : this.speciesSimilarityMatrix.UPGMA()){
STITreeCluster sti = new STITreeCluster(GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier());
sti.setCluster(b);
upgma.add(sti);
}
Tree UPGMA = Utils.buildTreeFromClusters(upgma, GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier(), false);
/// Tree allGenesGreedy = Utils.greedyConsensus(greedyCandidates, false,
// GlobalMaps.taxonNameMap.getSpeciesIdMapper()
// .getSTTaxonIdentifier(), true);
//// resolveByUPGMA((MutableTree) allGenesGreedy, GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier(),
// this.speciesSimilarityMatrix);
// baseTrees.add(allGenesGreedy);
baseTrees.add(UPGMA);
addBipartitionsFromSignleIndTreesToX(UPGMA, baseTrees,
GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier());
for (int ii=0; ii < secondRoundSampling; ii++) {
for (int j=0 ; j< allGreedies.length ; j++) {
try {
addBipartitionsFromSignleIndTreesToX(allGreedies[j].get(ii), baseTrees,
GlobalMaps.taxonNameMap.getSpeciesIdMapper().getSTTaxonIdentifier());
} catch (Exception e) {
System.err.println(allGreedies[j].get(ii));
e.printStackTrace();
}
//System.err
// .println("Number of clusters added from gene tree "+j+" in round"+ii+" "
// + clusters.getClusterCount());
}
System.err
.println("------------------------------");
gradiant = clusters.getClusterCount() - prev;
System.err.println("gradient"+ii +": "+ gradiant);
prev = clusters.getClusterCount();
}
prev = 0;
gradiant = 0;
if (inference.options.getAddExtra() != 0) {
this.addExtraBipartitionByDistance();
for (int l = 0; l < secondRoundSampling; l++) {
ArrayList<Tree> genes = new ArrayList<Tree>();
for (int j = 0; j < allGreedies.length; j++) {
genes.add(allGreedies[j].get(l));
}
System.err
.println("calculating extra bipartitions to be added at level "
+ inference.options.getAddExtra() + " ...");
this.addExtraBipartitionByHeuristics(genes,
GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getSTTaxonIdentifier(),
this.speciesSimilarityMatrix,inference.options.getPolylimit());
System.err
.println("Number of Clusters after addition by greedy: "
+ clusters.getClusterCount());
gradiant = clusters.getClusterCount() - prev;
System.err.println("gradient"+l+" in heuristiic: "+ gradiant);
prev = clusters.getClusterCount();
}
}
}
/**
* Calculates a distance matrix based on input gene trees. To be used for
* gene tree completion.
*/
private void calculateDistances() {
System.err
.println("Calculating quartet distance matrix (for completion of X)");
this.similarityMatrix = new SimilarityMatrix(
GlobalMaps.taxonIdentifier.taxonCount());
this.similarityMatrix.populateByQuartetDistance(treeAllClusters,
this.originalInompleteGeneTrees);
this.speciesSimilarityMatrix = GlobalMaps.taxonNameMap
.getSpeciesIdMapper().convertToSpeciesDistance(
this.similarityMatrix);// this.similarityMatrix.convertToSpeciesDistance(spm);
}
/**
* Computes the set of available leaves per gene tree.
*
* @param inference
* @return
*/
int preProcess(AbstractInference<Tripartition> inference) {
System.err.println("Number of gene trees: "
+ this.originalInompleteGeneTrees.size());
// n = GlobalMaps.taxonIdentifier.taxonCount();
int haveMissing = 0;
for (Tree tree : this.originalInompleteGeneTrees) {
if (tree.getLeafCount() != GlobalMaps.taxonIdentifier.taxonCount()) {
haveMissing++;
}
String[] gtLeaves = tree.getLeaves();
STITreeCluster gtAll = GlobalMaps.taxonIdentifier.newCluster();
long ni = gtLeaves.length;
for (int i = 0; i < ni; i++) {
gtAll.addLeaf(GlobalMaps.taxonIdentifier.taxonId(gtLeaves[i]));
}
treeAllClusters.add(gtAll);
}
System.err.println(haveMissing + " trees have missing taxa");
return haveMissing;
}
/*
* long maxPossibleScore(Tripartition trip) {
*
* long weight = 0;
*
* for (STITreeCluster all : this.treeAllClusters){ long a =
* trip.cluster1.getBitSet().intersectionSize(all.getBitSet()), b =
* trip.cluster2.getBitSet().intersectionSize(all.getBitSet()), c =
* trip.cluster3.getBitSet().intersectionSize(all.getBitSet());
*
* weight += (a+b+c-3)*a*b*c; } return weight; }
*/
/**
* Completes all the gene trees using a heuristic algorithm described in
* Siavash's dissertation. Uses the distance matrix for completion.
*/
private void completeGeneTrees() {
System.err
.println("Will attempt to complete bipartitions from X before adding using a distance matrix.");
int t = 0;
BufferedWriter completedFile = null;
if (this.options.isOutputCompletedGenes()) {
String fn = this.options.getOutputFile() + ".completed_gene_trees";
System.err.println("Outputting completed gene trees to " + fn);
try {
completedFile = new BufferedWriter(new FileWriter(fn));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
for (Tree tr : this.originalInompleteGeneTrees) {
Tree trc = getCompleteTree(tr, this.treeAllClusters.get(t++)
.getBitSet());
this.completedGeeneTrees.add(trc);
if (completedFile != null) {
try {
completedFile.write(trc.toNewick() + " \n");
completedFile.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
if (completedFile != null) {
try {
completedFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (!options.isRunSearch()) {
System.err.println("Stopping after outputting completed gene tree");
System.exit(0);
}
}
}
/**
* for debugging
*
* @param distSTMatrix
*/
private void printoutdistmatrix(double[][] distSTMatrix) {
SpeciesMapper spm = GlobalMaps.taxonNameMap.getSpeciesIdMapper();
for (String s : spm.getSTTaxonIdentifier().getAllTaxonNames()) {
System.err.print(String.format("%1$8s", s));
}
System.err.println();
for (int i = 0; i < spm.getSpeciesCount(); i++) {
for (int j = 0; j < spm.getSpeciesCount(); j++) {
System.err.print(String.format("%1$8.3f", distSTMatrix[i][j]));
}
System.err.println();
}
}
/**
* By default (when SLOW is false) it only computes an UPGMA tree from the
* distance data and adds to the set of bipartitions
*/
public void addExtraBipartitionByDistance() {
for (BitSet bs : speciesSimilarityMatrix.UPGMA()) {
STITreeCluster g = GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getGeneClusterForSTCluster(bs);
this.addCompletedSpeciesFixedBipartionToX(g,
g.complementaryCluster());
// upgmac.add(g);
}
;
if (SLOW) {
for (BitSet bs : speciesSimilarityMatrix.getQuadraticBitsets()) {
STITreeCluster g = GlobalMaps.taxonNameMap.getSpeciesIdMapper()
.getGeneClusterForSTCluster(bs);
this.addCompletedSpeciesFixedBipartionToX(g,
g.complementaryCluster());
}
;
}
System.err.println("Number of Clusters after addition by distance: "
+ clusters.getClusterCount());
}
/**
* Main function implementing new heuristics in ASTRAL-II. At this point, we
* require a subsample with a single individual per species.
*
* @param trees
* : the input trees contracted to the subsample
* @param sis
* : the single-individual subsample information
*/
void addExtraBipartitionByHeuristics(Collection<Tree> contractedTrees,
TaxonIdentifier tid, SimilarityMatrix sm, int polylimit) {
// Greedy trees. These will be based on sis taxon identifier
Collection<Tree> allGreedies;
System.err
.println("Adding to X using resolutions of greedy consensus ...");
for (Tree tree : contractedTrees) {
tree.rerootTreeAtEdge(tid.getTaxonName(0));
Trees.removeBinaryNodes((MutableTree) tree);
}
/*
* if (completeTrees.size() < 2) {
* System.err.println("Only "+completeTrees.size() +
* " complete trees found. Greedy-based completion not applicable.");
* return; }
*/
allGreedies = Utils.greedyConsensus(contractedTrees,
this.GREEDY_ADDITION_THRESHOLDS, true, 1, tid, true);
int sumDegrees = 0;
ArrayList<Integer> deg = new ArrayList<Integer>();
for (Tree cons : allGreedies) {
for (TNode greedyNode : cons.postTraverse()) {
if (greedyNode.getChildCount() > 2){
deg.add(greedyNode.getChildCount());
}
}
}
Collections.sort(deg);