-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathpda.cpp
2638 lines (2302 loc) · 81.5 KB
/
pda.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
/***************************************************************************
* Copyright (C) 2006 by BUI Quang Minh, Steffen Klaere, Arndt von Haeseler *
* minh.bui@univie.ac.at *
* *
* 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 2 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, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <iqtree_config.h>
#if defined WIN32 || defined _WIN32 || defined __WIN32__
//#include <winsock2.h>
//#include <windows.h>
//extern __declspec(dllexport) int gethostname(char *name, int namelen);
#else
#include <sys/resource.h>
#endif
//#include "Eigen/Core"
#include <stdio.h>
#include "tree/phylotree.h"
#include <signal.h>
#include <cstdio>
#include <streambuf>
#include <iostream>
#include <cstdlib>
#include <errno.h>
#include "pda/greedy.h"
#include "pda/pruning.h"
//#include "naivegreedy.h"
#include "pda/splitgraph.h"
#include "pda/circularnetwork.h"
#include "tree/mtreeset.h"
#include "tree/mexttree.h"
#include "ncl/ncl.h"
#include "nclextra/msetsblock.h"
#include "nclextra/myreader.h"
#include "phyloanalysis.h"
#include "tree/matree.h"
//#include "ngs.h"
//#include "parsmultistate.h"
//#include "gss.h"
#include "alignment/maalignment.h" //added by MA
#include "tree/ncbitree.h"
#include "pda/ecopd.h"
#include "upperbounds.h"
#include "tree/ecopdmtreeset.h"
#include "pda/gurobiwrapper.h"
#include "utils/timeutil.h"
//#include <unistd.h>
#include <stdlib.h>
#include "vectorclass/instrset.h"
#include "utils/MPIHelper.h"
#ifdef _IQTREE_MPI
#include <mpi.h>
#endif
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
void generateRandomTree(Params ¶ms)
{
if (params.sub_size < 3 && !params.aln_file) {
outError(ERR_FEW_TAXA);
}
if (!params.user_file) {
outError("Please specify an output tree file name");
}
////cout << "Random number seed: " << params.ran_seed << endl << endl;
SplitGraph sg;
try {
if (params.tree_gen == YULE_HARDING || params.tree_gen == CATERPILLAR ||
params.tree_gen == BALANCED || params.tree_gen == UNIFORM || params.tree_gen == STAR_TREE) {
if (!overwriteFile(params.user_file)) return;
ofstream out;
out.open(params.user_file);
MTree itree;
if (params.second_tree) {
cout << "Generating random branch lengths on tree " << params.second_tree << " ..." << endl;
itree.readTree(params.second_tree, params.is_rooted);
} else
switch (params.tree_gen) {
case YULE_HARDING:
cout << "Generating random Yule-Harding tree..." << endl;
break;
case UNIFORM:
cout << "Generating random uniform tree..." << endl;
break;
case CATERPILLAR:
cout << "Generating random caterpillar tree..." << endl;
break;
case BALANCED:
cout << "Generating random balanced tree..." << endl;
break;
case STAR_TREE:
cout << "Generating star tree with random external branch lengths..." << endl;
break;
default: break;
}
ofstream out2;
if (params.num_zero_len) {
cout << "Setting " << params.num_zero_len << " internal branches to zero length..." << endl;
string str = params.user_file;
str += ".collapsed";
out2.open(str.c_str());
}
for (int i = 0; i < params.repeated_time; i++) {
MExtTree mtree;
if (itree.root) {
mtree.copyTree(&itree);
mtree.generateRandomBranchLengths(params);
} else {
mtree.generateRandomTree(params.tree_gen, params);
}
if (params.num_zero_len) {
mtree.setZeroInternalBranches(params.num_zero_len);
MExtTree collapsed_tree;
collapsed_tree.copyTree(&mtree);
collapsed_tree.collapseZeroBranches();
collapsed_tree.printTree(out2);
out2 << endl;
}
mtree.printTree(out);
out << endl;
}
out.close();
cout << params.repeated_time << " tree(s) printed to " << params.user_file << endl;
if (params.num_zero_len) {
out2.close();
cout << params.repeated_time << " collapsed tree(s) printed to " << params.user_file << ".collapsed" << endl;
}
}
// Generate random trees if optioned
else if (params.tree_gen == CIRCULAR_SPLIT_GRAPH) {
cout << "Generating random circular split network..." << endl;
if (!overwriteFile(params.user_file)) return;
sg.generateCircular(params);
} else if (params.tree_gen == TAXA_SET) {
sg.init(params);
cout << "Generating random taxa set of size " << params.sub_size <<
" overlap " << params.overlap << " with " << params.repeated_time << " times..." << endl;
if (!overwriteFile(params.pdtaxa_file)) return;
sg.generateTaxaSet(params.pdtaxa_file, params.sub_size, params.overlap, params.repeated_time);
}
} catch (bad_alloc) {
outError(ERR_NO_MEMORY);
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, params.user_file);
}
// calculate the distance
if (params.run_mode == CALC_DIST) {
if (params.tree_gen == CIRCULAR_SPLIT_GRAPH) {
cout << "Calculating distance matrix..." << endl;
sg.calcDistance(params.dist_file);
cout << "Distances printed to " << params.dist_file << endl;
}// else {
//mtree.calcDist(params.dist_file);
//}
}
}
inline void separator(ostream &out, int type = 0) {
switch (type) {
case 0:
out << endl << "==============================================================================" << endl;
break;
case 1:
out << endl << "-----------------------------------------------------------" << endl;
break;
default:
break;
}
}
void printCopyright(ostream &out) {
#ifdef IQ_TREE
out << "IQ-TREE";
#ifdef _IQTREE_MPI
out << " MPI";
#endif
#ifdef _OPENMP
out << " multicore";
#endif
out << " version ";
#else
out << "PDA - Phylogenetic Diversity Analyzer version ";
#endif
out << iqtree_VERSION_MAJOR << "." << iqtree_VERSION_MINOR << "." << iqtree_VERSION_PATCH;
#if defined _WIN32 || defined WIN32
out << " for Windows";
#elif defined __APPLE__ || defined __MACH__
out << " for Mac OS X";
#elif defined __linux__
out << " for Linux";
#elif defined __unix__ || defined __unix
out << " for Unix";
#else
out << " for unknown platform"
#endif
out << " " << 8*sizeof(void*) << "-bit" << " built " << __DATE__;
#if defined DEBUG
out << " - debug mode";
#endif
#ifdef IQ_TREE
out << endl << "Developed by Bui Quang Minh, Nguyen Lam Tung, Olga Chernomor,"
<< endl << "Heiko Schmidt, Dominik Schrempf, Michael Woodhams." << endl << endl;
#else
out << endl << "Copyright (c) 2006-2014 Olga Chernomor, Arndt von Haeseler and Bui Quang Minh." << endl << endl;
#endif
}
void printRunMode(ostream &out, RunMode run_mode) {
switch (run_mode) {
case DETECTED: out << "Detected"; break;
case GREEDY: out << "Greedy"; break;
case PRUNING: out << "Pruning"; break;
case BOTH_ALG: out << "Greedy and Pruning"; break;
case EXHAUSTIVE: out << "Exhaustive"; break;
case DYNAMIC_PROGRAMMING: out << "Dynamic Programming"; break;
case LINEAR_PROGRAMMING: out << "Integer Linear Programming"; break;
default: outError(ERR_INTERNAL);
}
}
/**
summarize the running with header
*/
void summarizeHeader(ostream &out, Params ¶ms, bool budget_constraint, InputType analysis_type) {
printCopyright(out);
out << "Input tree/split network file name: " << params.user_file << endl;
if(params.eco_dag_file)
out << "Input food web file name: "<<params.eco_dag_file<<endl;
out << "Input file format: " << ((params.intype == IN_NEWICK) ? "Newick" : ( (params.intype == IN_NEXUS) ? "Nexus" : "Unknown" )) << endl;
if (params.initial_file != NULL)
out << "Initial taxa file: " << params.initial_file << endl;
if (params.param_file != NULL)
out << "Parameter file: " << params.param_file << endl;
out << endl;
out << "Type of measure: " << ((params.root != NULL || params.is_rooted) ? "Rooted": "Unrooted") <<
(analysis_type== IN_NEWICK ? " phylogenetic diversity (PD)" : " split diversity (SD)");
if (params.root != NULL) out << " at " << params.root;
out << endl;
if (params.run_mode != CALC_DIST && params.run_mode != PD_USER_SET) {
out << "Search objective: " << ((params.find_pd_min) ? "Minimum" : "Maximum") << endl;
out << "Search algorithm: ";
printRunMode(out, params.run_mode);
if (params.run_mode == DETECTED) {
out << " -> ";
printRunMode(out, params.detected_mode);
}
out << endl;
out << "Search option: " << ((params.find_all) ? "Multiple optimal sets" : "Single optimal set") << endl;
}
out << endl;
out << "Type of analysis: ";
switch (params.run_mode) {
case PD_USER_SET: out << "PD/SD of user sets";
if (params.pdtaxa_file) out << " (" << params.pdtaxa_file << ")"; break;
case CALC_DIST: out << "Distance matrix computation"; break;
default:
out << ((budget_constraint) ? "Budget constraint " : "Subset size k ");
if (params.intype == IN_NEWICK)
out << ((analysis_type == IN_NEWICK) ? "on tree" : "on tree -> split network");
else
out << "on split network";
}
out << endl;
//out << "Random number seed: " << params.ran_seed << endl;
}
void summarizeFooter(ostream &out, Params ¶ms) {
separator(out);
time_t beginTime;
time (&beginTime);
char *date;
date = ctime(&beginTime);
out << "Time used: " << params.run_time << " seconds." << endl;
out << "Finished time: " << date << endl;
}
int getMaxNameLen(vector<string> &setName) {
int len = 0;
for (vector<string>::iterator it = setName.begin(); it != setName.end(); it++)
if (len < (*it).length())
len = (*it).length();
return len;
}
void printPDUser(ostream &out, Params ¶ms, PDRelatedMeasures &pd_more) {
out << "List of user-defined sets of taxa with PD score computed" << endl << endl;
int maxlen = getMaxNameLen(pd_more.setName)+2;
out.width(maxlen);
out << "Name" << " PD";
if (params.exclusive_pd) out << " excl.-PD";
if (params.endemic_pd) out << " PD-Endem.";
if (params.complement_area) out << " PD-Compl. given area " << params.complement_area;
out << endl;
int cnt;
for (cnt = 0; cnt < pd_more.setName.size(); cnt++) {
out.width(maxlen);
out << pd_more.setName[cnt] << " ";
out.width(7);
out << pd_more.PDScore[cnt] << " ";
if (params.exclusive_pd) {
out.width(7);
out << pd_more.exclusivePD[cnt] << " ";
}
if (params.endemic_pd) {
out.width(7);
out << pd_more.PDEndemism[cnt] << " ";
}
if (params.complement_area) {
out.width(8);
out << pd_more.PDComplementarity[cnt];
}
out << endl;
}
separator(out, 1);
}
void summarizeTree(Params ¶ms, PDTree &tree, vector<PDTaxaSet> &taxa_set,
PDRelatedMeasures &pd_more) {
string filename;
if (params.out_file == NULL) {
filename = params.out_prefix;
filename += ".pda";
} else
filename = params.out_file;
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(filename.c_str());
summarizeHeader(out, params, false, IN_NEWICK);
out << "Tree size: " << tree.leafNum-params.is_rooted << " taxa, " <<
tree.nodeNum-1-params.is_rooted << " branches" << endl;
separator(out);
vector<PDTaxaSet>::iterator tid;
if (params.run_mode == PD_USER_SET) {
printPDUser(out, params, pd_more);
}
else if (taxa_set.size() > 1)
out << "Optimal PD-sets with k = " << params.min_size-params.is_rooted <<
" to " << params.sub_size-params.is_rooted << endl << endl;
int subsize = params.min_size-params.is_rooted;
if (params.run_mode == PD_USER_SET) subsize = 1;
for (tid = taxa_set.begin(); tid != taxa_set.end(); tid++, subsize++) {
if (tid != taxa_set.begin())
separator(out, 1);
if (params.run_mode == PD_USER_SET) {
out << "Set " << subsize << " has PD score of " << tid->score << endl;
}
else {
out << "For k = " << subsize << " the optimal PD score is " << (*tid).score << endl;
out << "The optimal PD set has " << subsize << " taxa:" << endl;
}
for (NodeVector::iterator it = (*tid).begin(); it != (*tid).end(); it++)
if ((*it)->name != ROOT_NAME){
out << (*it)->name << endl;
}
if (!tid->tree_str.empty()) {
out << endl << "Corresponding sub-tree: " << endl;
out << tid->tree_str << endl;
}
tid->clear();
}
taxa_set.clear();
summarizeFooter(out, params);
out.close();
cout << endl << "Results are summarized in " << filename << endl << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
}
void printTaxaSet(Params ¶ms, vector<PDTaxaSet> &taxa_set, RunMode cur_mode) {
int subsize = params.min_size-params.is_rooted;
ofstream out;
ofstream scoreout;
string filename;
filename = params.out_prefix;
filename += ".score";
scoreout.open(filename.c_str());
if (!scoreout.is_open())
outError(ERR_WRITE_OUTPUT, filename);
cout << "PD scores printed to " << filename << endl;
if (params.nr_output == 1) {
filename = params.out_prefix;
filename += ".pdtaxa";
out.open(filename.c_str());
if (!out.is_open())
outError(ERR_WRITE_OUTPUT, filename);
}
for (vector<PDTaxaSet>::iterator tid = taxa_set.begin(); tid != taxa_set.end(); tid++, subsize++) {
if (params.nr_output > 10) {
filename = params.out_prefix;
filename += ".";
filename += subsize;
if (params.run_mode == BOTH_ALG) {
if (cur_mode == GREEDY)
filename += ".greedy";
else
filename += ".pruning";
} else {
filename += ".pdtree";
}
(*tid).printTree((char*)filename.c_str());
filename = params.out_prefix;
filename += ".";
filename += subsize;
filename += ".pdtaxa";
(*tid).printTaxa((char*)filename.c_str());
} else {
out << subsize << " " << (*tid).score << endl;
scoreout << subsize << " " << (*tid).score << endl;
(*tid).printTaxa(out);
}
}
if (params.nr_output == 1) {
out.close();
cout << "All taxa list(s) printed to " << filename << endl;
}
scoreout.close();
}
/**
run PD algorithm on trees
*/
void runPDTree(Params ¶ms)
{
if (params.run_mode == CALC_DIST) {
bool is_rooted = false;
MExtTree tree(params.user_file, is_rooted);
cout << "Tree contains " << tree.leafNum << " taxa." << endl;
cout << "Calculating distance matrix..." << endl;
tree.calcDist(params.dist_file);
cout << "Distances printed to " << params.dist_file << endl;
return;
}
double t_begin, t_end;
//char filename[300];
//int idx;
vector<PDTaxaSet> taxa_set;
if (params.run_mode == PD_USER_SET) {
// compute score of user-defined sets
t_begin = getCPUTime();
cout << "Computing PD score for user-defined set of taxa..." << endl;
PDTree tree(params);
PDRelatedMeasures pd_more;
tree.computePD(params, taxa_set, pd_more);
if (params.endemic_pd)
tree.calcPDEndemism(taxa_set, pd_more.PDEndemism);
if (params.complement_area != NULL)
tree.calcPDComplementarity(taxa_set, params.complement_area, pd_more.PDComplementarity);
t_end = getCPUTime();
params.run_time = (t_end-t_begin);
summarizeTree(params, tree, taxa_set, pd_more);
return;
}
/*********************************************
run greedy algorithm
*********************************************/
if (params.sub_size < 2) {
outError(ERR_NO_K);
}
bool detected_greedy = (params.run_mode != PRUNING);
Greedy test_greedy;
test_greedy.init(params);
if (params.root == NULL && !params.is_rooted)
cout << endl << "Running PD algorithm on UNROOTED tree..." << endl;
else
cout << endl << "Running PD algorithm on ROOTED tree..." << endl;
if (verbose_mode >= VB_DEBUG)
test_greedy.drawTree(cout, WT_INT_NODE + WT_BR_SCALE + WT_BR_LEN);
if (params.run_mode == GREEDY || params.run_mode == BOTH_ALG ||
(params.run_mode == DETECTED)) {
if (params.run_mode == DETECTED && params.sub_size >= test_greedy.leafNum * 7 / 10
&& params.min_size < 2)
detected_greedy = false;
if (detected_greedy) {
params.detected_mode = GREEDY;
t_begin=getCPUTime();
cout << endl << "Greedy Algorithm..." << endl;
taxa_set.clear();
test_greedy.run(params, taxa_set);
t_end=getCPUTime();
params.run_time = (t_end-t_begin);
cout << "Time used: " << params.run_time << " seconds." << endl;
if (params.min_size == params.sub_size)
cout << "Resulting tree length = " << taxa_set[0].score << endl;
if (params.nr_output > 0)
printTaxaSet(params, taxa_set, GREEDY);
PDRelatedMeasures pd_more;
summarizeTree(params, test_greedy, taxa_set, pd_more);
}
}
/*********************************************
run pruning algorithm
*********************************************/
if (params.run_mode == PRUNING || params.run_mode == BOTH_ALG ||
(params.run_mode == DETECTED)) {
Pruning test_pruning;
if (params.run_mode == PRUNING || params.run_mode == BOTH_ALG) {
//Pruning test_pruning(params);
test_pruning.init(params);
} else if (!detected_greedy) {
test_pruning.init(test_greedy);
} else {
return;
}
params.detected_mode = PRUNING;
t_begin=getCPUTime();
cout << endl << "Pruning Algorithm..." << endl;
taxa_set.clear();
test_pruning.run(params, taxa_set);
t_end=getCPUTime();
params.run_time = (t_end-t_begin) ;
cout << "Time used: " << params.run_time << " seconds.\n";
if (params.min_size == params.sub_size)
cout << "Resulting tree length = " << taxa_set[0].score << endl;
if (params.nr_output > 0)
printTaxaSet(params, taxa_set, PRUNING);
PDRelatedMeasures pd_more;
summarizeTree(params, test_pruning, taxa_set, pd_more);
}
}
void checkSplitDistance(ostream &out, PDNetwork &sg) {
mmatrix(double) dist;
sg.calcDistance(dist);
int ntaxa = sg.getNTaxa();
int i, j;
bool found = false;
for (i = 0; i < ntaxa-1; i++) {
bool first = true;
for (j = i+1; j < ntaxa; j++)
if (abs(dist[i][j]) <= 1e-5) {
if (!found) {
out << "The following sets of taxa (each set in a line) have very small split-distance" << endl;
out << "( <= 1e-5) as computed from the split system. To avoid a lot of multiple" << endl;
out << "optimal PD sets to be reported, one should only keep one taxon from each set" << endl;
out << "and exclude the rest from the analysis." << endl << endl;
}
if (first)
out << sg.getTaxa()->GetTaxonLabel(i);
found = true;
first = false;
out << ", " << sg.getTaxa()->GetTaxonLabel(j);
}
if (!first) out << endl;
}
if (found)
separator(out);
}
/**
check if the set are nested and there are no multiple optimal sets.
If yes, return the ranking as could be produced by a greedy algorithm
*/
bool makeRanking(vector<SplitSet> &pd_set, IntVector &indices, IntVector &ranking) {
vector<SplitSet>::iterator it;
IntVector::iterator inti;
ranking.clear();
bool nested = true;
Split *cur_sp = NULL;
int id = 1;
for (it = pd_set.begin(); it != pd_set.end(); it++) {
if ((*it).empty()) continue;
if ((*it).size() > 1) {
nested = false;
ranking.push_back(-10);
indices.push_back(0);
}
Split *sp = (*it)[0];
if (!cur_sp) {
IntVector sp_tax;
sp->getTaxaList(sp_tax);
ranking.insert(ranking.end(), sp_tax.begin(), sp_tax.end());
for (inti = sp_tax.begin(); inti != sp_tax.end(); inti++)
indices.push_back(id++);
} else {
if ( !cur_sp->subsetOf(*sp)) {
ranking.push_back(-1);
indices.push_back(0);
nested = false;
}
Split sp_diff(*sp);
sp_diff -= *cur_sp;
Split sp_diff2(*cur_sp);
sp_diff2 -= *sp;
IntVector sp_tax;
sp_diff2.getTaxaList(sp_tax);
ranking.insert(ranking.end(), sp_tax.begin(), sp_tax.end());
for (inti = sp_tax.begin(); inti != sp_tax.end(); inti++)
indices.push_back(-id);
sp_diff.getTaxaList(sp_tax);
ranking.insert(ranking.end(), sp_tax.begin(), sp_tax.end());
for (inti = sp_tax.begin(); inti != sp_tax.end(); inti++)
indices.push_back(id);
if ( !cur_sp->subsetOf(*sp)) {
ranking.push_back(-2);
indices.push_back(0);
}
id++;
}
cur_sp = sp;
}
return nested;
}
void printNexusSets(const char *filename, PDNetwork &sg, vector<SplitSet> &pd_set) {
try {
ofstream out;
out.open(filename);
out << "#NEXUS" << endl << "BEGIN Sets;" << endl;
vector<SplitSet>::iterator it;
for (it = pd_set.begin(); it != pd_set.end(); it++) {
int id = 1;
for (SplitSet::iterator sit = (*it).begin(); sit != (*it).end(); sit++, id++) {
IntVector taxa;
(*sit)->getTaxaList(taxa);
out << " TAXSET Opt_" << taxa.size() << "_" << id << " =";
for (IntVector::iterator iit = taxa.begin(); iit != taxa.end(); iit++) {
if (sg.isPDArea())
out << " '" << sg.getSetsBlock()->getSet(*iit)->name << "'";
else
out << " '" << sg.getTaxa()->GetTaxonLabel(*iit) << "'";
}
out << ";" << endl;
}
}
out << "END; [Sets]" << endl;
out.close();
cout << endl << "Optimal sets are written to nexus file " << filename << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, filename);
}
}
void computeTaxaFrequency(SplitSet &taxa_set, DoubleVector &freq) {
ASSERT(taxa_set.size());
int ntaxa = taxa_set[0]->getNTaxa();
int i;
freq.resize(ntaxa, 0);
for (SplitSet::iterator it2 = taxa_set.begin(); it2 != taxa_set.end(); it2++) {
for ( i = 0; i < ntaxa; i++)
if ((*it2)->containTaxon(i)) freq[i] += 1.0;
}
for ( i = 0; i < ntaxa; i++)
freq[i] /= taxa_set.size();
}
/**
summarize the running results
*/
void summarizeSplit(Params ¶ms, PDNetwork &sg, vector<SplitSet> &pd_set, PDRelatedMeasures &pd_more, bool full_report) {
int i;
if (params.nexus_output) {
string nex_file = params.out_prefix;
nex_file += ".pdsets.nex";
printNexusSets(nex_file.c_str(), sg, pd_set);
}
string filename;
if (params.out_file == NULL) {
filename = params.out_prefix;
filename += ".pda";
} else
filename = params.out_file;
try {
ofstream out;
out.open(filename.c_str());
/****************************/
/********** HEADER **********/
/****************************/
summarizeHeader(out, params, sg.isBudgetConstraint(), IN_NEXUS);
out << "Network size: " << sg.getNTaxa()-params.is_rooted << " taxa, " <<
sg.getNSplits()-params.is_rooted << " splits (of which " <<
sg.getNTrivialSplits() << " are trivial splits)" << endl;
out << "Network type: " << ((sg.isCircular()) ? "Circular" : "General") << endl;
separator(out);
checkSplitDistance(out, sg);
int c_num = 0;
//int subsize = (sg.isBudgetConstraint()) ? params.budget : (params.sub_size-params.is_rooted);
//subsize -= pd_set.size()-1;
int subsize = (sg.isBudgetConstraint()) ? params.min_budget : params.min_size-params.is_rooted;
int stepsize = (sg.isBudgetConstraint()) ? params.step_budget : params.step_size;
if (params.detected_mode != LINEAR_PROGRAMMING) stepsize = 1;
vector<SplitSet>::iterator it;
SplitSet::iterator it2;
if (params.run_mode == PD_USER_SET) {
printPDUser(out, params, pd_more);
}
/****************************/
/********** SUMMARY *********/
/****************************/
if (params.run_mode != PD_USER_SET && !params.num_bootstrap_samples) {
out << "Summary of the PD-score and the number of optimal PD-sets with the same " << endl << "optimal PD-score found." << endl;
if (sg.isBudgetConstraint())
out << endl << "Budget PD-score %PD-score #PD-sets" << endl;
else
out << endl << "Size-k PD-score %PD-score #PD-sets" << endl;
int sizex = subsize;
double total = sg.calcWeight();
for (it = pd_set.begin(); it != pd_set.end(); it++, sizex+=stepsize) {
out.width(6);
out << right << sizex << " ";
out.width(10);
out << right << (*it).getWeight() << " ";
out.width(10);
out << right << ((*it).getWeight()/total)*100.0 << " ";
out.width(6);
out << right << (*it).size();
out << endl;
}
out << endl;
if (!params.find_all)
out << "Note: You did not choose the option to find multiple optimal PD sets." << endl <<
"That's why we only reported one PD-set per size-k or budget. If you want" << endl <<
"to determine all multiple PD-sets, use the '-a' option.";
else {
out << "Note: The number of multiple optimal PD sets to be reported is limited to " << params.pd_limit << "." << endl <<
"There might be cases where the actual #PD-sets exceeds that upper-limit but" << endl <<
"won't be listed here. Please refer to the above list to identify such cases." << endl <<
"To increase the upper-limit, use the '-lim <limit_number>' option.";
}
out << endl;
separator(out);
}
if (!full_report) {
out.close();
return;
}
/****************************/
/********* BOOTSTRAP ********/
/****************************/
if (params.run_mode != PD_USER_SET && params.num_bootstrap_samples) {
out << "Summary of the bootstrap analysis " << endl;
for (it = pd_set.begin(); it != pd_set.end(); it++) {
DoubleVector freq;
computeTaxaFrequency((*it), freq);
out << "For k/budget = " << subsize << " the " << ((sg.isPDArea()) ? "areas" : "taxa")
<< " supports are: " << endl;
for (i = 0; i < freq.size(); i++)
out << ((sg.isPDArea()) ? sg.getSetsBlock()->getSet(i)->name : sg.getTaxa()->GetTaxonLabel(i))
<< "\t" << freq[i] << endl;
if ((it+1) != pd_set.end()) separator(out, 1);
}
out << endl;
separator(out);
}
/****************************/
/********** RANKING *********/
/****************************/
if (params.run_mode != PD_USER_SET && !params.num_bootstrap_samples) {
IntVector ranking;
IntVector index;
out << "Ranking based on the optimal sets" << endl;
if (!makeRanking(pd_set, index, ranking)) {
out << "WARNING: Optimal sets are not nested, so ranking should not be considered stable" << endl;
}
if (subsize > 1) {
out << "WARNING: The first " << subsize << " ranks should be treated equal" << endl;
}
out << endl << "Rank* ";
if (!sg.isPDArea())
out << "Taxon names" << endl;
else
out << "Area names" << endl;
for (IntVector::iterator intv = ranking.begin(), intid = index.begin(); intv != ranking.end(); intv ++, intid++) {
if (*intv == -10)
out << "<--- multiple optimal set here --->" << endl;
else if (*intv == -1)
out << "<--- BEGIN: greedy does not work --->" << endl;
else if (*intv == -2)
out << "<--- END --->" << endl;
else {
out.width(5);
out << right << *intid << " ";
if (sg.isPDArea())
out << sg.getSetsBlock()->getSet(*intv)->name << endl;
else
out << sg.getTaxa()->GetTaxonLabel(*intv) << endl;
}
}
out << endl;
out << "(*) Negative ranks indicate the point at which the greedy algorithm" << endl <<
" does not work. In that case, the corresponding taxon/area names" << endl <<
" should be deleted from the optimal set of the same size" << endl;
separator(out);
}
int max_len = sg.getTaxa()->GetMaxTaxonLabelLength();
/****************************/
/***** DETAILED SETS ********/
/****************************/
if (params.run_mode != PD_USER_SET)
out << "Detailed information of all taxa found in the optimal PD-sets" << endl;
if (pd_set.size() > 1) {
if (sg.isBudgetConstraint())
out << "with budget = " << params.min_budget <<
" to " << params.budget << endl << endl;
else
out << "with k = " << params.min_size-params.is_rooted <<
" to " << params.sub_size-params.is_rooted << endl << endl;
}
if (params.run_mode != PD_USER_SET)
separator(out,1);
for (it = pd_set.begin(); it != pd_set.end(); it++, subsize+=stepsize) {
// check if the pd-sets are the same as previous one
if (sg.isBudgetConstraint() && it != pd_set.begin()) {
vector<SplitSet>::iterator prev, next;
for (next=it, prev=it-1; next != pd_set.end() && next->getWeight() == (*prev).getWeight() &&
next->size() == (*prev).size(); next++ ) ;
if (next != it) {
// found something in between!
out << endl;
//out << endl << "**************************************************************" << endl;
out << "For budget = " << subsize << " -> " << subsize+(next-it-1)*stepsize <<
" the optimal PD score and PD sets" << endl;
out << "are identical to the case when budget = " << subsize-stepsize << endl;
//out << "**************************************************************" << endl;
subsize += (next-it)*stepsize;
it = next;
if (it == pd_set.end()) break;
}
}
if (it != pd_set.begin()) separator(out, 1);
int num_sets = (*it).size();
double weight = (*it).getWeight();
if (params.run_mode != PD_USER_SET) {
out << "For " << ((sg.isBudgetConstraint()) ? "budget" : "k") << " = " << subsize;
out << " the optimal PD score is " << weight << endl;
if (num_sets == 1) {
if (!sg.isBudgetConstraint())
out << "The optimal PD set has " << (*it)[0]->countTaxa()-params.is_rooted <<
((sg.isPDArea()) ? " areas" : " taxa");
else
out << "The optimal PD set has " << (*it)[0]->countTaxa()-params.is_rooted <<
((sg.isPDArea()) ? " areas" : " taxa") << " and requires " << sg.calcCost(*(*it)[0]) << " budget";
if (!sg.isPDArea()) out << " and covers " << sg.countSplits(*(*it)[0]) <<
" splits (of which " << sg.countInternalSplits(*(*it)[0]) << " are internal splits)";
out << endl;
}
else
out << "Found " << num_sets << " PD sets with the same optimal score." << endl;
}
for (it2 = (*it).begin(), c_num=1; it2 != (*it).end(); it2++, c_num++){
Split *this_set = *it2;
if (params.run_mode == PD_USER_SET && it2 != (*it).begin())
separator(out, 1);
if (params.run_mode == PD_USER_SET) {
if (!sg.isBudgetConstraint())
out << "Set " << c_num << " has PD score of " << this_set->getWeight();
else
out << "Set " << c_num << " has PD score of " << this_set->getWeight() <<
" and requires " << sg.calcCost(*this_set) << " budget";
} else if (num_sets > 1) {
if (!sg.isBudgetConstraint())
out << endl << "PD set " << c_num;
else
out << endl << "PD set " << c_num << " has " << this_set->countTaxa()-params.is_rooted <<
" taxa and requires " << sg.calcCost(*this_set) << " budget";
}
if (!sg.isPDArea() && (num_sets > 1 || params.run_mode == PD_USER_SET ))
out << " and covers " << sg.countSplits(*(*it)[0]) << " splits (of which "
<< sg.countInternalSplits(*(*it)[0]) << " are internal splits)";
out << endl;
if (params.run_mode != PD_USER_SET && sg.isPDArea()) {
for (i = 0; i < sg.getSetsBlock()->getNSets(); i++)
if (this_set->containTaxon(i)) {