forked from diepthihoang/mpboot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdnetwork.cpp
More file actions
1964 lines (1729 loc) · 55.3 KB
/
pdnetwork.cpp
File metadata and controls
1964 lines (1729 loc) · 55.3 KB
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. *
***************************************************************************/
#include "mtree.h"
#include "pdnetwork.h"
#include "ncl/ncl.h"
#include "msetsblock.h"
#include "myreader.h"
#include "lpwrapper.h"
#include "gurobiwrapper.h"
extern void summarizeSplit(Params ¶ms, PDNetwork &sg, vector<SplitSet> &pd_set, PDRelatedMeasures &pd_more, bool full_report);
PDNetwork::PDNetwork()
: SplitGraph()
{
extra_pd = 0;
min_pd = false;
}
PDNetwork::PDNetwork(Params ¶ms) : SplitGraph(params) {
extra_pd = 0;
min_pd = false;
if (params.is_rooted)
readRootNode(ROOT_NAME);
// read the parameter file
if (params.param_file != NULL)
readParams(params);
if (params.budget_file != NULL) {
if (isPDArea())
pda->readBudgetAreaFile(params);
else
pda->readBudgetFile(params);
}
// identify the root
if (params.root != NULL)
readRootNode(params.root);
// initial PD min
if (params.find_pd_min)
initPDMin();
// read the initial set of taxa, incoporate info into the split system
if (params.initial_file != NULL && params.eco_dag_file == NULL)
readInitialSet(params);
if (!initialset.empty() && !isPDArea())
proceedInitialSet();
if (params.initial_area_file != NULL)
readInitialAreas(params);
}
/**
Identify the root node if specified, include it into the initial set
@param root_name name of the root node
*/
void PDNetwork::readRootNode(const char *root_name) {
int id = -1;
try {
id = taxa->FindTaxon(root_name);
} catch (NxsTaxaBlock::NxsX_NoSuchTaxon) {
outError(ERR_NO_TAXON, root_name);
}
initialset.clear();
initialset.push_back(id);
//if (sets->getNSets() == 0)
}
void PDNetwork::readParams(Params ¶ms) {
int ntaxa = getNTaxa() - params.is_rooted;
// read parameters from file
double scale;
StrVector tax_name;
DoubleVector ori_weight, tax_weight;
readWeightFile(params, ntaxa, scale, tax_name, ori_weight);
// now convert the weights
tax_weight.resize(ntaxa, 0);
for (int i = 0; i < tax_name.size(); i++) {
int id = -1;
try {
string name = "";
name.append(tax_name[i]);
id = taxa->FindTaxon(NxsString(name.c_str()));
} catch (NxsTaxaBlock::NxsX_NoSuchTaxon) {
outError(ERR_NO_TAXON, tax_name[i]);
}
tax_weight[id] = ori_weight[i];
}
if (params.scaling_factor >= 0) {
if (params.scaling_factor > 1) outError("Scaling factor must be between 0 and 1");
cout << "Rescaling split weights with " << params.scaling_factor <<
" and taxa weights with " << 1 - params.scaling_factor << endl;
scale = params.scaling_factor;
for (DoubleVector::iterator it = tax_weight.begin(); it != tax_weight.end(); it++)
(*it) *= (1 - scale);
}
// incoporate into the split system
for (iterator it = begin(); it != end(); it++) {
int id = (*it)->trivial();
// first, multiply split weight with the coefficient
(*it)->weight *= scale;
// if a trivial split, add the important parameter f
if (id >= 0)
(*it)->weight += tax_weight[id];
}
}
/**
read the initial set of taxa to be included into PD-tree
@param params program parameters
*/
void PDNetwork::readInitialSet(Params ¶ms) {
extra_pd = 0.0;
int ntaxa = getNTaxa() - params.is_rooted;
StrVector tax_name;
readInitTaxaFile(params, ntaxa, tax_name);
if (tax_name.empty())
outError("No taxa found");
for (StrVector::iterator it = tax_name.begin(); it != tax_name.end(); it++) {
int id = -1;
try {
string name = "";
name.append(*it);
id = taxa->FindTaxon(NxsString(name.c_str()));
} catch (NxsTaxaBlock::NxsX_NoSuchTaxon) {
outError(ERR_NO_TAXON, *it);
}
initialset.push_back(id);
}
if (isPDArea()) return;
if (isBudgetConstraint()) {
int budget = (params.budget >= 0) ? params.budget : pda->budget;
if (calcCost(initialset) > budget)
outError(ERR_TOO_SMALL_BUDGET);
} else {
int sub_size = (params.sub_size > 1) ? params.sub_size : pda->sub_size;
if (initialset.size() > sub_size)
outError(ERR_TOO_SMALL_K);
}
}
void PDNetwork::proceedInitialSet() {
double total_w = trunc(abs(calcWeight())+1);
// get the set of initial taxa
set<int> iset;
for (IntVector::iterator it2 = initialset.begin(); it2 != initialset.end(); it2++)
iset.insert(*it2);
// now modifying the split weights
for (iterator it = begin(); it != end(); it++) {
// get the taxa id of trivial split
int id = (*it)->trivial();
// if not trivial split, continue
if (id < 0) continue;
if (iset.find(id) != iset.end()) {
// increase the trivial split weight
(*it)->weight += total_w;
extra_pd += total_w;
}
}
}
void PDNetwork::readInitialAreas(Params ¶ms) {
if (!isPDArea())
outError("Invalid -ia option: no areas specified");
int nareas = sets->getNSets();
StrVector area_name;
readInitAreaFile(params, nareas, area_name);
if (area_name.empty())
outError("No area found");
for (StrVector::iterator it = area_name.begin(); it != area_name.end(); it++) {
int id = -1;
id = sets->findArea(*it);
if (id < 0)
outError(ERR_NO_AREA, *it);
initialareas.push_back(id);
}
if (isBudgetConstraint()) {
int budget = (params.budget >= 0) ? params.budget : pda->budget;
if (calcCost(initialareas) > budget)
outError(ERR_TOO_SMALL_BUDGET);
} else {
int sub_size = (params.sub_size >= 1) ? params.sub_size : pda->sub_size;
if (initialareas.size() > sub_size)
outError(ERR_TOO_SMALL_K);
}
}
void PDNetwork::initPDMin() {
min_pd = true;
for (iterator it = begin(); it != end(); it++) {
(*it)->weight = -(*it)->weight;
}
}
/**
compute the required costs to conserve a taxa set
@param taxset set of taxa
@return minimum budget required
*/
int PDNetwork::calcCost(IntVector &taxset) {
int sum = 0;
for (IntVector::iterator it = taxset.begin(); it != taxset.end(); it++)
sum += pda->costs[*it];
return sum;
}
/**
compute the required costs to conserve a taxa set
@param taxset set of taxa
@return minimum budget required
*/
int PDNetwork::calcCost(Split &taxset) {
IntVector invec;
taxset.getTaxaList(invec);
return calcCost(invec);
}
/********************************************************
Now comes PD related stuff
********************************************************/
void PDNetwork::calcPD(Split &id_set) {
if (initialset.empty()) {
id_set.weight = calcWeight(id_set);
return;
}
Split id(id_set);
for (IntVector::iterator it = initialset.begin(); it != initialset.end(); it++)
id.addTaxon(*it);
id_set.weight = calcWeight(id);
}
void PDNetwork::calcExclusivePD(Split &id_set) {
id_set.invert();
calcPD(id_set);
id_set.invert();
id_set.weight = calcWeight() - id_set.weight;
}
void PDNetwork::computePD(Params ¶ms, SplitSet &pd_set, PDRelatedMeasures &pd_more) {
//MSetsBlock *sets;
//sets = new MSetsBlock();
//sets->Report(cout);
TaxaSetNameVector *allsets = sets->getSets();
TaxaSetNameVector::iterator i;
for (i = allsets->begin(); i != allsets->end(); i++) {
Split *id_set = new Split(getNTaxa());
/*
for (IntVector::iterator it = initialset.begin(); it != initialset.end(); it++)
id_set->addTaxon(*it);
*/
for (vector<string>::iterator it2 = (*i)->taxlist.begin(); it2 != (*i)->taxlist.end(); it2++) {
int id = -1;
try {
id = taxa->FindTaxon(NxsString(it2->c_str()));
} catch (NxsTaxaBlock::NxsX_NoSuchTaxon) {
outError(ERR_NO_TAXON, *it2);
}
if (id >= 0)
id_set->addTaxon(id);
}
pd_more.setName.push_back((*i)->name);
if (params.exclusive_pd) {
calcExclusivePD(*id_set);
pd_more.exclusivePD.push_back(id_set->getWeight());
}
calcPD(*id_set);
pd_more.PDScore.push_back(id_set->weight);
pd_set.push_back(id_set);
}
//delete sets;
}
/********************************************************
EXHAUSTIVE FUNCTION
********************************************************/
void PDNetwork::updateSplitVector(Split &curset, SplitSet &best_set)
{
if (curset.weight > best_set[0]->weight) {
for (int it = best_set.size()-1; it >= 0; it--)
delete best_set[it];
best_set.clear();
}
best_set.push_back(new Split(curset));
}
/**
calculate sum of weights of preserved splits in the taxa_set
@param taxa_set a set of taxa
*/
double PDNetwork::calcRaisedWeight(Split &taxa_set,
IntList &rem_splits, IntList::iterator &rem_it)
{
double sum = 0.0;
for (IntList::iterator it = rem_splits.begin(); it != rem_it;)
if ((*this)[*it]->preserved(taxa_set)) {
sum += (*this)[*it]->weight;
IntList::iterator prev_it = rem_it;
prev_it--;
int temp = *it;
*it = *prev_it;
*prev_it = temp;
rem_it = prev_it;
} else it++;
return sum;
}
int PDNetwork::calcMaxBudget() {
int sum = 0;
for (DoubleVector::iterator it = pda->costs.begin(); it != pda->costs.end(); it++)
sum += (*it);
return sum;
}
void PDNetwork::enterFindPD(Params ¶ms) {
// check parameters
if (params.pd_proportion == 0.0) {
if (isBudgetConstraint()) {
int budget = (params.budget >= 0) ? params.budget : pda->getBudget();
if (budget < 0) {
outError(ERR_NO_BUDGET);
}
} else {
int min_accepted = !isPDArea() + 1;
int sub_size = (params.sub_size >= min_accepted) ? params.sub_size : pda->getSubSize();
if (sub_size < min_accepted && params.pdtaxa_file == NULL) {
outError(ERR_NO_K);
}
}
}
if (initialset.size() > 0) {
cout << "Consider split network as ROOTED." << endl;
} else {
cout << "Consider split network as UNROOTED." << endl;
}
cout << "Total split weights: " << calcWeight() << endl;
cout << " Internal split weights: " << calcWeight() - calcTrivialWeight() << endl;
cout << " Trivial split weights : " << calcTrivialWeight() << endl;
if (params.pd_proportion == 0.0) {
if (isBudgetConstraint()) {
// fix the budget and min_budget first
if (params.budget < 0) params.budget = pda->budget;
if (verbose_mode >= VB_DEBUG) {
pda->Report(cout);
}
cout << "Budget constraint with budget = " << params.budget << " ..." << endl;
if (params.min_budget < 0)
params.min_budget = pda->min_budget;
if (params.min_budget < 0) params.min_budget = params.budget;
// resize the taxa_set
int max_budget = calcMaxBudget();
if (params.budget > max_budget) {
cout << "Only maximum budget of " << max_budget << " required, truncating to that value..." << endl;
params.budget = max_budget;
if (params.min_budget > params.budget)
params.min_budget = params.budget;
}
} else {
int min_accepted = !isPDArea() + 1;
if (params.sub_size <= 0) params.sub_size = pda->sub_size;
if (!isPDArea()) {
if (params.sub_size < 2 || params.sub_size > getNTaxa()) {
ostringstream str;
str <<"k must be between 2 and " << getNTaxa()-params.is_rooted;
outError(str.str());
}
} else if (params.sub_size < 1 || params.sub_size > sets->getNSets()) {
ostringstream str;
str << "k must be between 1 and " << sets->getNSets();
outError(str.str());
}
if (params.min_size < min_accepted) params.min_size = params.sub_size;
}
}
}
void printLPVersion(bool gurobi_format) {
if (gurobi_format)
cout << "Using GUROBI" << endl;
else {
//int lp_majorversion, lp_minorversion, lp_release, lp_build;
//lp_solve_version_info(&lp_majorversion, &lp_minorversion, &lp_release, &lp_build);
//cout << "Using LP_SOLVE " << lp_majorversion << "." << lp_minorversion << "." << lp_release << "." << lp_build << endl;
}
}
void PDNetwork::findPD(Params ¶ms, vector<SplitSet> &taxa_set, vector<int> &taxa_order) {
// call the entering function
enterFindPD(params);
int ntaxa = getNTaxa();
int nsplits = getNSplits();
Split curset(ntaxa, 0.0);
IntList rem_splits;
for (int i = 0; i < nsplits; i++)
rem_splits.push_back(i);
IntList::iterator rem_it = rem_splits.end();
params.detected_mode = EXHAUSTIVE;
if (isPDArea()) {
params.detected_mode = LINEAR_PROGRAMMING;
printLPVersion(params.gurobi_format);
cout << "Optimizing PD over " << sets->getNSets() << " areas..." << endl;
cout << "Linear programming on general split network..." << endl;
findPDArea_LP(params, taxa_set);
} else if (params.run_mode == GREEDY) {
// greedy search, not ensure to give the optimal sets!
cout << "Start greedy search..." << endl;
greedyPD(params.sub_size, curset, taxa_order);
localSearchPD(params.sub_size, curset, taxa_order);
taxa_set.resize(1);
taxa_set[0].push_back(new Split(curset));
} else if (params.run_mode != EXHAUSTIVE) {
params.detected_mode = LINEAR_PROGRAMMING;
printLPVersion(params.gurobi_format);
cout << "Linear programming on general split network..." << endl;
findPD_LP(params, taxa_set);
}
else if (isBudgetConstraint()) {
// exhaustive search by the order
cout << endl << "Start exhaustive search..." << endl;
taxa_set.resize(1);
taxa_set[0].push_back(new Split(ntaxa, 0.0));
exhaustPDBudget(params.budget, -1, curset, params.find_all, taxa_set[0], taxa_order, rem_splits, rem_it);
} else {
// exhaustive search by the order
cout << endl << "Start exhaustive search..." << endl;
taxa_set.resize(1);
taxa_set[0].push_back(new Split(ntaxa, 0.0));
exhaustPD2(params.sub_size, -1, curset, params.find_all, taxa_set[0], taxa_order, rem_splits, rem_it);
}
// call the leaving function
leaveFindPD(taxa_set);
}
void PDNetwork::leaveFindPD(vector<SplitSet> &taxa_set) {
// subtract the weights from the extra_pd
if (extra_pd > 0)
for (vector<SplitSet>::iterator it = taxa_set.begin(); it != taxa_set.end(); it++)
for (SplitSet::iterator it2 = (*it).begin(); it2 != (*it).end(); it2++)
(*it2)->weight -= extra_pd;
if (min_pd)
for (vector<SplitSet>::iterator it = taxa_set.begin(); it != taxa_set.end(); it++)
for (SplitSet::iterator it2 = (*it).begin(); it2 != (*it).end(); it2++)
(*it2)->weight = -(*it2)->weight;
}
/**
exhaustive search VERSION 2 for maximal phylogenetic diversity of a given size
@param subsize the subset size
@param best_set (OUT) the set of taxa in the maximal PD set
@param cur_tax current taxon
@param curset current set
@param taxa_order (OUT) order of inserted taxa
@param rem_splits (IN) remaining splits
@return the PD score of the maximal set
*/
double PDNetwork::exhaustPD2(int subsize, int cur_tax, Split &curset,
bool find_all,SplitSet &best_set, vector<int> &taxa_order,
IntList &rem_splits, IntList::iterator &rem_it )
{
int ntaxa = getNTaxa();
double saved_score = curset.weight;
for (int tax = cur_tax+1; tax <= ntaxa - subsize; tax ++) {
curset.addTaxon(taxa_order[tax]);
IntList::iterator saved_it = rem_it;
curset.weight += calcRaisedWeight(curset, rem_splits, rem_it);
if (subsize > 1)
exhaustPD2(subsize-1, tax, curset, find_all, best_set, taxa_order, rem_splits, rem_it);
else {
if (curset.weight >= best_set[0]->weight) {
updateSplitVector(curset, best_set);
//curset.report(cout);
}
//curset.report(cout);
}
curset.removeTaxon(taxa_order[tax]);
curset.weight = saved_score;
rem_it = saved_it;
//restoreSplit(subsize, rem_splits, out_splits);
}
return best_set[0]->weight;
}
double PDNetwork::exhaustPDBudget(int cur_budget, int cur_tax, Split &curset,
bool find_all,SplitSet &best_set, vector<int> &taxa_order,
IntList &rem_splits, IntList::iterator &rem_it )
{
int ntaxa = getNTaxa();
double saved_score = curset.weight;
for (int tax = cur_tax+1; tax < ntaxa; tax ++)
if (pda->costs[taxa_order[tax]] <= cur_budget)
{
curset.addTaxon(taxa_order[tax]);
IntList::iterator saved_it = rem_it;
curset.weight += calcRaisedWeight(curset, rem_splits, rem_it);
if (curset.weight >= best_set[0]->weight) {
updateSplitVector(curset, best_set);
//curset.report(cout);
}
if (tax < ntaxa-1)
exhaustPDBudget(cur_budget - pda->costs[taxa_order[tax]], tax,
curset, find_all, best_set, taxa_order, rem_splits, rem_it);
//curset.report(cout);
curset.removeTaxon(taxa_order[tax]);
curset.weight = saved_score;
rem_it = saved_it;
//restoreSplit(subsize, rem_splits, out_splits);
}
return best_set[0]->weight;
}
/********************************************************
GREEDY SEARCH!
********************************************************/
/**
greedy algorithm for phylogenetic diversity of a given size
@param subsize the subset size
@param taxa_set (OUT) the set of taxa in the PD-set
@return the PD score of the maximal set, also returned in taxa_set.weight
*/
double PDNetwork::greedyPD(int subsize, Split &taxa_set, vector<int> &taxa_order) {
int ntaxa = getNTaxa();
taxa_set.setNTaxa(ntaxa);
taxa_set.weight = 0;
taxa_order.clear();
taxa_order.reserve(ntaxa);
int besti, bestj, i, j;
// start from the PD-2 set
for (i = 0; i < ntaxa - 1; i++)
for (j = 0; j < ntaxa; j++) {
Split curset;
curset.setNTaxa(ntaxa);
curset.addTaxon(i);
curset.addTaxon(j);
curset.weight = calcWeight(curset);
if (curset.weight > taxa_set.weight) {
taxa_set = curset;
besti = i;
bestj = j;
}
}
//taxa_set.report(cout);
taxa_order.push_back(besti);
taxa_order.push_back(bestj);
for (int step = 2; step < subsize; step++) {
Split pdk_set = taxa_set;
besti = -1;
for (i = 0; i < ntaxa; i++)
if (!pdk_set.containTaxon(i)) {
Split curset;
curset.setNTaxa(ntaxa);
curset = pdk_set;
curset.addTaxon(i);
curset.weight = calcWeight(curset);
if (curset.weight > taxa_set.weight || besti == -1) {
taxa_set = curset;
besti = i;
}
}
//taxa_set.report(cout);
taxa_order.push_back(besti);
}
return taxa_set.getWeight();
}
/**
testing algorithm for phylogenetic diversity of a given size
@param subsize the subset size
@param taxa_set (OUT) the set of taxa in the PD-set
@return the PD score of the maximal set, also returned in taxa_set.weight
*/
double PDNetwork::localSearchPD(int subsize, Split &taxa_set, vector<int> &taxa_order) {
int ntaxa = getNTaxa();
//int nsplits = getNSplits();
int i;
taxa_set.setNTaxa(ntaxa);
for (i = 0; i < subsize; i++)
taxa_set.addTaxon(taxa_order[i]);
taxa_set.weight = calcWeight(taxa_set);
taxa_set.report(cout);
bool stop;
do {
stop = true;
for (i = 0; i < ntaxa; i++) if (taxa_set.containTaxon(i)) {
for (int j = 0; j < ntaxa; j++) if (!taxa_set.containTaxon(j))
{
taxa_set.addTaxon(j);
taxa_set.removeTaxon(i);
double new_w = calcWeight(taxa_set);
if (new_w > taxa_set.weight) {
taxa_set.weight = new_w;
stop = false;
taxa_set.report(cout);
break;
}
taxa_set.removeTaxon(j);
taxa_set.addTaxon(i);
}
if (!stop) break;
}
} while (!stop);
return taxa_set.getWeight();
}
void PDNetwork::calcPDGain(vector<SplitSet> &pd_set, matrix(double) &delta) {
vector<SplitSet>::iterator it;
int ntaxa = pd_set.front().front()->getNTaxa();
delta.resize(pd_set.size());
int cnt = 0;
for (cnt = 0; cnt < delta.size(); cnt++)
delta[cnt].resize(ntaxa, 0);
for (it = pd_set.begin(), cnt = 0; it != pd_set.end(); it++, cnt++) {
assert(!(*it).empty());
// take only the first split for calculation
Split *sp = (*it).front();
for (int tax = 0; tax < ntaxa; tax++)
if (!sp->containTaxon(tax)) {
sp->addTaxon(tax);
delta[cnt][tax] = calcWeight(*sp) - sp->weight;
sp->removeTaxon(tax);
}
}
}
void PDNetwork::calcPDEndemism(SplitSet &area_set, DoubleVector &pd_endem) {
SplitSet::iterator it_s;
// make union of all id_sets
Split id_union(getNTaxa());
for (it_s = area_set.begin(); it_s != area_set.end(); it_s++)
id_union += *(*it_s);
// calculate PD of union
calcPD(id_union);
// now calculate PD endemism
pd_endem.clear();
for (it_s = area_set.begin(); it_s != area_set.end(); it_s++) {
// make union of all other set
Split id_other(getNTaxa());
for (SplitSet::iterator it_s2 = area_set.begin(); it_s2 != area_set.end(); it_s2++)
if (it_s2 != it_s) id_other += *(*it_s2);
// calculate PD of all other sets
calcPD(id_other);
// calc PD endemism
pd_endem.push_back(id_union.weight - id_other.weight);
}
}
void PDNetwork::calcPDComplementarity(SplitSet &area_set, char *area_names,
vector<string> &all_names, DoubleVector &pd_comp) {
set<string> given_areas;
parseAreaName(area_names, given_areas);
/*
for (set<string>::iterator it = given_areas.begin(); it != given_areas.end(); it++)
cout << (*it) << "!";
cout << endl;
*/
SplitSet::iterator it_s;
vector<string>::iterator it_n;
Split given_id(getNTaxa());
// convert taxa set to id set
for (it_s = area_set.begin(), it_n = all_names.begin(); it_s != area_set.end(); it_s++, it_n++) {
if (given_areas.find(*it_n) != given_areas.end())
given_id += *(*it_s);
}
if (given_id.countTaxa() == 0)
outError("Complementary area name(s) not correct");
calcPD(given_id);
// now calculate PD complementarity
pd_comp.clear();
for (it_s = area_set.begin(); it_s != area_set.end(); it_s++) {
// make union the two sets
Split id_both(*(*it_s));
id_both += given_id;
// calculate PD of both sets
calcPD(id_both);
// calc PD complementarity
pd_comp.push_back(id_both.weight - given_id.weight);
}
}
void PDNetwork::transformLP2(Params ¶ms, const char *outfile, int total_size, bool make_bin) {
Split included_tax(getNTaxa());
IntVector::iterator it2;
for (it2 = initialset.begin(); it2 != initialset.end(); it2++)
included_tax.addTaxon(*it2);
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(outfile);
vector<int> y_value;
checkYValue(total_size, y_value);
lpObjectiveMaxSD(out, params, y_value, total_size);
lpSplitConstraint_TS(out, params, y_value, total_size);
lpK_BudgetConstraint(out, params, total_size);
lpVariableBound(out, params, included_tax, y_value);
if (make_bin)
lpVariableBinary(out, params, included_tax);
out.close();
//cout << "Transformed LP problem printed to " << outfile << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, outfile);
}
}
//Olga:ECOpd split system
void PDNetwork::transformEcoLP(Params ¶ms, const char *outfile, int total_size) {
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(outfile);
vector<int> y_value;
y_value.resize(getNSplits(), -1);
lpObjectiveMaxSD(out, params, y_value, total_size);
lpSplitConstraint_TS(out, params, y_value, total_size);
out.close();
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, outfile);
}
}
void PDNetwork::findPD_LP(Params ¶ms, vector<SplitSet> &taxa_set) {
if (params.find_all)
outError("Current linear programming does not support multiple optimal sets!");
string ofile = params.out_prefix;
ofile += ".lp";
double score;
int lp_ret, i, ntaxa = getNTaxa();
int k, min_k, max_k, step_k, index;
double *variables = new double[ntaxa];
if (isBudgetConstraint()) { // non-budget case
min_k = params.min_budget;
max_k = params.budget;
step_k = params.step_budget;
} else {
min_k = params.min_size;
max_k = params.sub_size;
step_k = params.step_size;
}
taxa_set.resize((max_k - min_k)/step_k + 1);
// now construction the optimal PD sets
if (isBudgetConstraint())
cout << "running budget = ";
else
cout << "running k = ";
for (k = min_k; k <= max_k; k += step_k) {
index = (k - min_k) / step_k;
if (!params.binary_programming) {
transformLP2(params, ofile.c_str(), k, false);
cout << " " << k;
cout.flush();
if (params.gurobi_format)
lp_ret = gurobi_solve((char*)ofile.c_str(), ntaxa, &score, variables, verbose_mode, params.gurobi_threads);
else
lp_ret = lp_solve((char*)ofile.c_str(), ntaxa, &score, variables, verbose_mode);
} else lp_ret = 7;
if (lp_ret != 0 && lp_ret != 7)
outError("Something went wrong with LP solver!");
if (lp_ret == 7) { // fail with non-binary case, do again with strict binary
if (params.binary_programming)
transformLP2(params, ofile.c_str(), k, true);
else
lpVariableBinary(ofile.c_str(), params, initialset);
cout << " " << k << "(bin)";
cout.flush();
if (params.gurobi_format)
lp_ret = gurobi_solve((char*)ofile.c_str(), ntaxa, &score, variables, verbose_mode, params.gurobi_threads);
else
lp_ret = lp_solve((char*)ofile.c_str(), ntaxa, &score, variables, verbose_mode);
if (lp_ret != 0) // check error again without allowing non-binary
outError("Something went wrong with LP solver!");
}
Split *pd_set = new Split(ntaxa, score);
for (i = 0; i < ntaxa; i++)
if (1.0 - variables[i] < tolerance) {
//pd_set->addTaxon(taxa_order[i]);
pd_set->addTaxon(i);
}
calcPD(*pd_set);
taxa_set[index].push_back(pd_set);
}
cout << endl;
delete variables;
}
void PDNetwork::transformLP_Area2(Params ¶ms, const char *outfile, int total_size, bool make_bin) {
int nareas = getNAreas();
Split included_area(nareas);
IntVector::iterator it2;
for (it2 = initialareas.begin(); it2 != initialareas.end(); it2++)
included_area.addTaxon(*it2);
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(outfile);
vector<int> y_value, count1, count2;
checkYValue_Area(total_size, y_value, count1, count2);
lpObjectiveMaxSD(out, params, y_value, total_size);
lpSplitConstraint_RS(out, params, y_value, count1, count2, total_size);
lpInitialArea(out, params);
lpK_BudgetConstraint(out, params, total_size);
lpBoundaryConstraint(out, params);
lpVariableBound(out, params, included_area, y_value);
if (make_bin)
lpVariableBinary(out, params, included_area);
out.close();
//cout << "Transformed LP problem printed to " << outfile << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, outfile);
}
}
void PDNetwork::transformMinK_Area2(Params ¶ms, const char *outfile, double pd_proportion, bool make_bin) {
int nareas = getNAreas();
Split included_area(nareas);
IntVector::iterator it2;
for (it2 = initialareas.begin(); it2 != initialareas.end(); it2++)
included_area.addTaxon(*it2);
try {
ofstream out;
out.exceptions(ios::failbit | ios::badbit);
out.open(outfile);
vector<int> y_value, count1, count2;
checkYValue_Area(0, y_value, count1, count2);
lpObjectiveMinK(out, params);
lpMinSDConstraint(out, params, y_value, pd_proportion);
lpSplitConstraint_RS(out, params, y_value, count1, count2, 0);
lpInitialArea(out, params);
lpBoundaryConstraint(out, params);
lpVariableBound(out, params, included_area, y_value);
if (make_bin)
lpVariableBinary(out, params, included_area);
out.close();
//cout << "Transformed LP problem printed to " << outfile << endl;
} catch (ios::failure) {
outError(ERR_WRITE_OUTPUT, outfile);
}
}
double PDNetwork::findMinKArea_LP(Params ¶ms, const char* filename, double pd_proportion, Split &area) {
int nareas = area_taxa.size();
double *variables = new double[nareas];
double score;
int lp_ret, i;
if (!params.binary_programming) {
cout << " " << pd_proportion;
cout.flush();
transformMinK_Area2(params, filename, pd_proportion, false);
if (params.gurobi_format)
lp_ret = gurobi_solve((char*)filename, nareas, &score, variables, verbose_mode, params.gurobi_threads);
else
lp_ret = lp_solve((char*)filename, nareas, &score, variables, verbose_mode);
} else lp_ret = 7;
if (lp_ret != 0 && lp_ret != 7)
outError("Something went wrong with LP solver!");
if (lp_ret == 7) { // fail with non-binary case, do again with strict binary
cout << " " << pd_proportion << "(bin)";
cout.flush();
if (params.binary_programming)
transformMinK_Area2(params, filename, pd_proportion, true);
else
lpVariableBinary(filename, params, initialareas);
if (params.gurobi_format)
lp_ret = gurobi_solve((char*)filename, nareas, &score, variables, verbose_mode, params.gurobi_threads);
else
lp_ret = lp_solve((char*)filename, nareas, &score, variables, verbose_mode);
if (lp_ret != 0) // check error again without allowing non-binary
outError("Something went wrong with LP solver!");
}
area.setNTaxa(nareas);
for (i = 0; i < nareas; i++)
if (1.0 - variables[i] < tolerance) {
//pd_set->addTaxon(taxa_order[i]);
area.addTaxon(i);
}
calcPDArea(area);
cout << " score: " << area.weight;
double budget_k;
if (isBudgetConstraint()) {
budget_k = calcCost(area);
} else {
budget_k = area.countTaxa();
}
delete variables;
return budget_k;
}
void PDNetwork::computeFeasibleBudget(Params ¶ms, IntVector &ok_budget) {
if (!isBudgetConstraint()) {
ok_budget.resize(params.sub_size+1, 1);
return;
}
cout << "Computing feasible budget values..." << endl;