-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhyloMerge.cppBUP
2685 lines (2472 loc) · 77.9 KB
/
PhyloMerge.cppBUP
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
//
// File: PhyloMerge.cpp
// Created by: Julien Dutheil, Bastien Boussau
// Created on: Sunday, December 2nd 2007 16:48
//
/*
Copyright or or Copr. CNRS
This software is a computer program whose purpose is to estimate
phylogenies and evolutionary parameters from a dataset according to
the maximum likelihood principle.
This software is governed by the CeCILL license under French law and
abiding by the rules of distribution of free software. You can use,
modify and/ or redistribute the software under the terms of the CeCILL
license as circulated by CEA, CNRS and INRIA at the following URL
"http://www.cecill.info".
As a counterpart to the access to the source code and rights to copy,
modify and redistribute granted by the license, users are provided only
with a limited warranty and the software's author, the holder of the
economic rights, and the successive licensors have only limited
liability.
In this respect, the user's attention is drawn to the risks associated
with loading, using, modifying and/or developing or reproducing the
software by the user in light of its specific status of free software,
that may mean that it is complicated to manipulate, and that also
therefore means that it is reserved for developers and experienced
professionals having in-depth computer knowledge. Users are therefore
encouraged to load and test the software's suitability as regards their
requirements in conditions enabling the security of their systems and/or
data to be ensured and, more generally, to use and operate it in the
same conditions as regards security.
The fact that you are presently reading this means that you have had
knowledge of the CeCILL license and that you accept its terms.
*/
// From the STL:
#include <iostream>
#include <iomanip>
#include <string.h>
#include <unordered_set>
using namespace std;
#include <Bpp/App/BppApplication.h>
#include <Bpp/App/ApplicationTools.h>
#include <Bpp/Io/FileTools.h>
#include <Bpp/Text/TextTools.h>
#include <Bpp/Numeric/DataTable.h>
#include <Bpp/Numeric/Random/RandomTools.h>
// From SeqLib:
#include <Bpp/Seq/Alphabet.all>
#include <Bpp/Seq/Container.all>
#include <Bpp/Seq/Io.all>
#include <Bpp/Seq/SiteTools.h>
#include <Bpp/Seq/SequenceTools.h>
#include <Bpp/Seq/App/SequenceApplicationTools.h>
// From PhylLib:
#include <Bpp/Phyl/Tree.h>
#include <Bpp/Phyl/Distance.all>
#include <Bpp/Phyl/App/PhylogeneticsApplicationTools.h>
#include <Bpp/Phyl/Io/PhylipDistanceMatrixFormat.h>
#include <Bpp/Phyl/Io/Nhx.h>
#include <Bpp/Phyl/Io/Newick.h>
//#include <../../home/boussau/Programs/Boost/boost_1_57_0/boost/concept_check.hpp>
const
std::string
ONE = "E"; //Property used to store the taxon corresponding to parent and son0 nodes
const
std::string
TWO = "Fu"; //Property used to store the taxon corresponding to parent and son1 nodes
const
std::string
THREE = "S"; //Property used to store the taxon corresponding to son0 and son1 nodes
//Compilation:
//g++ -pipe -o phylomerge bppPhyloSampler.cpp -I/usr/local/include -L. -L/usr/local/lib -g -Wall -fopenmp -std=c++0x -lbpp-core -lbpp-seq -lbpp-phyl
using
namespace
bpp;
void
help ()
{
(*ApplicationTools::message <<
"__________________________________________________________________________").endLine
();
(*ApplicationTools::message <<
"phylomerge parameter1_name=parameter1_value").endLine ();
(*ApplicationTools::message <<
" parameter2_name=parameter2_value ... param=option_file").endLine ();
(*ApplicationTools::message).endLine ();
(*ApplicationTools::message << " Options considered: ").endLine ();
(*ApplicationTools::message <<
" - input.method='tree' (could also be a distance matrix with the option 'matrix')").endLine
();
(*ApplicationTools::message <<
" - input.tree.file=file with the tree in it.").endLine ();
(*ApplicationTools::message <<
" - deletion.method='threshold' ou 'random' ou 'sample' ou 'taxon'. 'threshold' removes sequences that are so close in the tree that their distance is lower than the 'threshold' value (which is given as another option to the program, default is 0.01). 'sample': random choice of sample_size sequences (default is 10). 'taxon': choice is guided by the identity of the species the sequences come from. In cases several sequences from the same species are monophyletic, a choice will be made according to the 'choice.criterion' option").endLine
();
(*ApplicationTools::message <<
" - choice.criterion='length' ou 'length.complete' ou 'merge'. 'length' means the longest sequence is selected. 'length.complete' : means the largest number of complete sites (no gaps). 'merge' means that the set of monophyletic sequences is used to build one long 'chimera' sequence corresponding to the merging of them.").endLine
();
(*ApplicationTools::
message << " - selection.by.taxon='no' ou 'yes'").endLine ();
(*ApplicationTools::message <<
" - sequence.to.taxon=linkfile: format: sequence name: species name. Can be replaced by the option taxon.to.sequence").endLine
();
(*ApplicationTools::message <<
" - taxon.to.sequence=linkfile: format: species name: sequence name. Can be replaced by the option sequence.to.taxon").endLine
();
(*ApplicationTools::message <<
" - taxons.to.remove= file containing set of species from which sequences should be removed").endLine
();
(*ApplicationTools::message <<
" - taxons.to.refine= file containing set of species on which the sampling/merging should be done. If not specified, all species are concerned.").endLine
();
(*ApplicationTools::message <<
" - prescreening.on.size.by.taxon='no' : removes the sequences that are very short compared to other sequences of the same species. If there is only one sequence in this species, it is not removed.").endLine
();
(*ApplicationTools::
message << " - output.sequence.file=refined alignment").endLine ();
(*ApplicationTools::message <<
"__________________________________________________________________________").endLine
();
}
/****************************************************************
* Annotate nodes with taxon names when possible.
****************************************************************/
void
postOrderAnnotateNodesWithTaxa (TreeTemplate < Node > &tree, Node * node,
const std::map < std::string,
std::string > &seqSp)
{
if (node->isLeaf ())
{
// node->setNodeProperty(ONE, BppString(seqSp[node->getName()]));
// node->setNodeProperty(TWO, BppString(seqSp[node->getName()]));
//if at the root, we annotate the two properties including the (absent) father node
if (tree.getRootNode () == node)
{
node->setNodeProperty (ONE,
BppString (seqSp.at (node->getName ())));
node->setNodeProperty (TWO,
BppString (seqSp.at (node->getName ())));
postOrderAnnotateNodesWithTaxa (tree, node->getSon (0), seqSp);
node->setNodeProperty (THREE,
*(node->
getSon (0)->getNodeProperty (THREE)));
}
else
{
node->setNodeProperty (THREE,
BppString (seqSp.at (node->getName ())));
}
}
else
{
vector < string > sonTaxa;
for (unsigned int i = 0; i < node->getNumberOfSons (); i++)
{
postOrderAnnotateNodesWithTaxa (tree, node->getSon (i), seqSp);
sonTaxa.push_back ((dynamic_cast <
const BppString *
>(node->getSon (i)->
getNodeProperty (THREE)))->toSTL ());
}
vector < string > sonTaxaUnique = VectorTools::unique (sonTaxa);
if (sonTaxaUnique.size () > 1)
{
node->setNodeProperty (THREE, BppString ("#"));
}
else
{
node->setNodeProperty (THREE, BppString (sonTaxaUnique[0]));
}
}
return;
}
/****************************************************************
* Annotate nodes with taxon names when possible.
****************************************************************/
void
preOrderAnnotateNodesWithTaxa (TreeTemplate < Node > &tree, Node * node,
const std::map < std::string,
std::string > seqSp)
{
if ((node->isLeaf ()) && node->hasFather ())
{ //A leaf that is not the root
string fatherTaxa;
//Here we assume bifurcation.
if (node == node->getFather ()->getSon (0))
{
fatherTaxa =
((dynamic_cast <
const BppString *
>(node->getFather ()->getNodeProperty (TWO)))->toSTL ());
}
else
{
fatherTaxa =
((dynamic_cast <
const BppString *
>(node->getFather ()->getNodeProperty (ONE)))->toSTL ());
}
string
sonTaxa =
((dynamic_cast <
const BppString * >(node->getNodeProperty (THREE)))->toSTL ());
if (fatherTaxa == sonTaxa)
{
node->setNodeProperty (ONE, BppString (sonTaxa));
node->setNodeProperty (TWO, BppString (sonTaxa));
}
else
{
node->setNodeProperty (ONE, BppString ("#"));
node->setNodeProperty (TWO, BppString ("#"));
}
}
if ((!node->isLeaf ()) && node->hasFather ())
{ //Not a leaf, not at the root
string fatherTaxa;
//Here we assume bifurcation.
if (node == node->getFather ()->getSon (0))
{
/* std::cout <<"node id: "<<node->getFather()->getId()<<std::endl;
std::cout <<"root id: "<<tree.getRootNode()->getId()<<std::endl;
std::cout <<"root is leaf?: "<<tree.getRootNode()->isLeaf()<<std::endl;
std::cout <<"root numSons?: "<<tree.getRootNode()->getNumberOfSons()<<std::endl;*/
fatherTaxa =
((dynamic_cast <
const BppString *
>(node->getFather ()->getNodeProperty (TWO)))->toSTL ());
}
else
{
fatherTaxa =
((dynamic_cast <
const BppString *
>(node->getFather ()->getNodeProperty (ONE)))->toSTL ());
}
string
son0Taxa =
((dynamic_cast <
const BppString *
>(node->getSon (0)->getNodeProperty (THREE)))->toSTL ());
string
son1Taxa =
((dynamic_cast <
const BppString *
>(node->getSon (1)->getNodeProperty (THREE)))->toSTL ());
if (fatherTaxa == son0Taxa)
{
node->setNodeProperty (ONE, BppString (son0Taxa));
}
else
{
node->setNodeProperty (ONE, BppString ("#"));
}
if (fatherTaxa == son1Taxa)
{
node->setNodeProperty (TWO, BppString (son1Taxa));
}
else
{
node->setNodeProperty (TWO, BppString ("#"));
}
}
for (unsigned int i = 0; i < node->getNumberOfSons (); i++)
{
preOrderAnnotateNodesWithTaxa (tree, node->getSon (i), seqSp);
}
return;
}
/****************************************************************
* Annotate all nodes of a tree with taxon names when possible.
****************************************************************/
void
annotateTreeWithSpecies (TreeTemplate < Node > &tree,
const std::map < std::string, std::string > &seqSp)
{
//Now we have to go through the tree and remove sequences in groups of sequences from the same taxon
//We do a double-recursive tree traversal to annotate nodes by taxa below them, in all three directions.
//We use 3 node properties:
//ONE: subtree defined by parent and son 0
//TWO: subtree defined by parent and son 1
//THREE: subtree defined by son 0 and son 1.
//First, cleaning all annotations.
vector<Node*> nodes = tree.getNodes();
for (auto n = nodes.begin(); n != nodes.end(); ++n) {
if ((*n)->hasNodeProperty(ONE) )
(*n)->removeNodeProperty(ONE);
if ((*n)->hasNodeProperty(TWO) )
(*n)->removeNodeProperty(TWO);
if ((*n)->hasNodeProperty(THREE) )
(*n)->removeNodeProperty(THREE);
}
postOrderAnnotateNodesWithTaxa (tree, tree.getRootNode (), seqSp);
//Filling the 2 missing properties at the root
Node *
root = tree.getRootNode ();
if (!root->hasNodeProperty (TWO))
{
/* root->setNodeProperty(ONE, BppString("#"));
root->setNodeProperty(TWO, BppString("#")); */
root->setNodeProperty (ONE,
BppString (dynamic_cast <
const BppString *
>(root->
getSon (0)->getNodeProperty
(THREE))->toSTL ()));
root->setNodeProperty (TWO,
BppString (dynamic_cast <
const BppString *
>(root->
getSon (1)->getNodeProperty
(THREE))->toSTL ()));
/*
vector<string> sonTaxa;
//We assume bifurcation
sonTaxa.push_back((dynamic_cast<const BppString*>(root->getSon(0)->getNodeProperty(THREE)))->toSTL());
sonTaxa.push_back((dynamic_cast<const BppString*>(root->getSon(1)->getNodeProperty(THREE)))->toSTL());
vector<string> sonTaxaUnique = VectorTools::unique(sonTaxa);
if (sonTaxaUnique.size() >1)
{
root->setNodeProperty(ONE, BppString("#"));
root->setNodeProperty(TWO, BppString("#"));
}
else
{
root->setNodeProperty(ONE, BppString( sonTaxaUnique[0] ));
root->setNodeProperty(TWO, BppString( sonTaxaUnique[0] ));
} */
}
preOrderAnnotateNodesWithTaxa (tree, tree.getRootNode (), seqSp);
//Now the tree has nodes annotated with taxon names
// Nhx *nhx = new Nhx ();
// nhx->write (tree, cout);
// delete nhx;
}
double
getBootstrapValueOnBranchBetweenTheseTwoNodes (Node * it, Node * next)
{
if (it->hasFather () && it->getFather () == next)
{
if (it->hasBootstrapValue ())
{
return (it->getBootstrapValue ());
}
else return 0.0;
}
else
{
if (next->hasBootstrapValue ())
{
return (next->getBootstrapValue ());
}
else return 0.0;
}
}
/****************************************************************
* Moves cutNode to be placed next to newBrother
****************************************************************/
void
group (Node * newBrother, Node * cutNode, TreeTemplate < Node > &tree)
{
Node *
oldFather, *
oldGrandFather, *
brother, *
newBrothersFather, *
N;
double
dist = 0.12345;
bool wasRoot = false;
if (tree.getRootNode () != newBrother)
{
newBrothersFather = newBrother->getFather ();
}
else
{
wasRoot = true;
}
oldFather = cutNode->getFather ();
//Get all old brothers ; a binary tree is assumed here (because of the "break")
for (unsigned int i = 0; i < oldFather->getNumberOfSons (); i++)
if (oldFather->getSon (i) != cutNode)
{
brother = oldFather->getSon (i);
break;
}
if (!(oldFather->hasFather ()))
{ //we displace the outgroup, need to reroot the tree
//NB : brother is the other son of the root
int
id0 = oldFather->getId ();
int
idBrother = brother->getId ();
N = new Node ();
N->addSon (newBrother);
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
newBrother->setDistanceToFather (dist);
//we remove cutNode from its old neighborhood
for (unsigned int i = 0; i < oldFather->getNumberOfSons (); i++)
{
if (oldFather->getSon (i) == cutNode)
{
oldFather->removeSon (i);
break;
}
}
// we move node cutNode
N->addSon (cutNode);
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
cutNode->setDistanceToFather (dist);
// update N neighbours
for (unsigned int i = 0; i < newBrothersFather->getNumberOfSons (); i++)
if (newBrothersFather->getSon (i) == newBrother)
{
newBrothersFather->setSon (i, N);
break;
}
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
N->setDistanceToFather (dist);
unsigned int
oldFatherId = oldFather->getId ();
tree.rootAt (brother->getId ());
for (unsigned int i = 0; i < brother->getNumberOfSons (); i++)
{
if (brother->getSon (i) == oldFather)
{
brother->removeSon (i);
break;
}
}
if (tree.hasNode (oldFatherId))
delete oldFather;
//We renumber the nodes
brother->setId (id0);
N->setId (idBrother);
}
else
{
int
id0 = oldFather->getId ();
//we create a new node N which will be the father of cutNode and newBrother
N = new Node ();
N->setId(3000000);
const Number<double> noSupport ( 0.0 ) ;
if ( !wasRoot ) {
newBrothersFather->removeSon (newBrother);
newBrothersFather->addSon(N);
N->setDistanceToFather (dist);
N->setBranchProperty(TreeTools::BOOTSTRAP, noSupport );
}
N->addSon (newBrother);
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
newBrother->setDistanceToFather (dist);
if ( ! newBrother->hasBootstrapValue () ) {
newBrother->setBranchProperty(TreeTools::BOOTSTRAP, noSupport );
}
// we move node cutNode
oldFather->removeSon(cutNode);
N->addSon (cutNode);
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
cutNode->setDistanceToFather (dist);
if ( ! cutNode->hasBootstrapValue () ) {
cutNode->setBranchProperty(TreeTools::BOOTSTRAP, noSupport );
}
/*
// update N neighbours
if (!wasRoot)
{
for (unsigned int i = 0; i < newBrothersFather->getNumberOfSons ();
i++)
if (newBrothersFather->getSon (i) == newBrother)
{
newBrothersFather->setSon (i, N);
break;
}
std::cout << "group 52 " << std::endl;
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
N->setDistanceToFather (dist);
}*/
oldGrandFather = oldFather->getFather ();
oldFather->removeSon(brother);
oldGrandFather->removeSon(oldFather);
oldGrandFather->addSon (brother);
/* for (unsigned int i = 0; i < oldGrandFather->getNumberOfSons (); i++)
if (oldGrandFather->getSon (i) == oldFather)
{
oldGrandFather->setSon (i, brother);
break;
}*/
// BY DEFAULT RIGHT NOW. MAY NEED TO CHANGE IN THE FUTURE
brother->setDistanceToFather (dist);
delete oldFather;
N->setId (id0);
if (wasRoot) {
tree.setRootNode ( N );
}
}
return;
}
/****************************************************************
* Simple function to tell whether a node belongs to a given species.
****************************************************************/
bool
isNodeFromSpecies (Node * node, string species)
{
string
nodeTaxa1 =
((dynamic_cast <
const BppString * >(node->getNodeProperty (ONE)))->toSTL ());
string
nodeTaxa2 =
((dynamic_cast <
const BppString * >(node->getNodeProperty (TWO)))->toSTL ());
string
nodeTaxa3 =
((dynamic_cast <
const BppString * >(node->getNodeProperty (THREE)))->toSTL ());
//std::cout << "species: "<<species << " nodeTaxa1 " << nodeTaxa1 << " nodeTaxa2 " <<nodeTaxa2 << " nodeTaxa3 " << nodeTaxa3 ;
if (nodeTaxa1 == species || nodeTaxa2 == species || nodeTaxa3 == species)
{
return true;
}
else
{
return false;
}
}
/****************************************************************
* Finds sets of connected nodes that share the same origin species.
****************************************************************/
void
searchForConnectedComponents (Node * node,
vector < vector < Node * > >&connectedNodes,
const string & species);
void
findConnectedNodes (Node * node, vector < vector < Node * > >&connectedNodes,
size_t i, const string species)
{
if (isNodeFromSpecies (node, species))
{
connectedNodes[i].push_back (node);
if (node->getNumberOfSons () > 0)
{
vector < Node * >nodes = node->getSons ();
for (auto n = nodes.begin (); n != nodes.end (); ++n)
{
findConnectedNodes (*n, connectedNodes, i, species);
}
}
}
else
{
if (node->getNumberOfSons () > 0)
{
vector < Node * >nodes = node->getSons ();
for (auto n = nodes.begin (); n != nodes.end (); ++n)
{
searchForConnectedComponents (*n, connectedNodes, species);
}
}
}
}
void
searchForConnectedComponents (Node * node,
vector < vector < Node * > >&connectedNodes,
const string & species)
{
if (isNodeFromSpecies (node, species))
{
vector < Node * >nodes;
connectedNodes.push_back (nodes);
findConnectedNodes (node, connectedNodes, connectedNodes.size () - 1,
species);
}
else
{
if (node->getNumberOfSons () > 0)
{
vector < Node * >sons = node->getSons ();
for (auto n = sons.begin (); n != sons.end (); ++n)
{
searchForConnectedComponents (*n, connectedNodes, species);
}
}
}
}
/****************************************************************
* Reorganizes the tree to group sequences coming from the same species.
****************************************************************/
bool
groupSequencesFromSpecies (TreeTemplate < Node > &tree,
const string & species,
const double &bootstrapThreshold,
const std::map < std::string, std::string > &seqSp)
{
annotateTreeWithSpecies (tree, seqSp);
bool weHaveDoneARearrangement = false;
vector < Node * >nodes = tree.getNodes ();
vector < Node * >nodesOfSpecies;
for (auto node = nodes.begin (); node != nodes.end (); ++node)
{
if (isNodeFromSpecies (*node, species))
nodesOfSpecies.push_back (*node);
}
//Now we have a subset of nodes from species "species".
if (nodesOfSpecies.size () == 1) //only one node
{
return weHaveDoneARearrangement;
}
//Are they all connected?
vector < vector < Node * > >connectedNodes;
searchForConnectedComponents (tree.getRootNode (), connectedNodes, species);
//Now connectedNodes contains all connected components
if (connectedNodes.size () == 1) //They are all connected, we exit
{
return weHaveDoneARearrangement;
}
//Several connected components, we need to see if we can group them.
for (size_t i = 0; i < connectedNodes.size () - 1; ++i)
{
for (size_t j = i + 1; j < connectedNodes.size (); ++j)
{
if (j != i + 1)
{
//We reroot the tree by a leaf
Node *
newOutgroup = tree.getLeaves ()[0];
tree.newOutGroup (newOutgroup);
if (!tree.isRooted ())
{
//std::cout << "Tree not rooted, rerooting." << std::endl;
tree.newOutGroup (tree.getLeaves ()[1]);
}
if (!newOutgroup->hasDistanceToFather ())
{
Node *
father = newOutgroup->getFather ();
Node *
brother;
if (father->getSon (0) == newOutgroup)
{
brother = father->getSon (1);
}
else
{
brother = father->getSon (0);
}
double
dist = brother->getDistanceToFather ();
brother->setDistanceToFather (dist / 2);
newOutgroup->setDistanceToFather (dist / 2);
}
else
{
}
annotateTreeWithSpecies (tree, seqSp);
}
vector < Node * >path =
TreeTemplateTools::getPathBetweenAnyTwoNodes (*
(connectedNodes[i]
[0]),
*(connectedNodes[j]
[0]));
//We have the path. We are only interested in nodes not annotated with the species of interest
vector < Node * >pathBetweenComponents;
size_t index = 0;
for (auto it = path.begin (); it != path.end (); ++it)
{
if (!isNodeFromSpecies (*it, species))
{
if (pathBetweenComponents.size () == 0)
{
pathBetweenComponents.push_back (path[index - 1]);
}
pathBetweenComponents.push_back (*it);
}
else if (pathBetweenComponents.size () > 0)
{
pathBetweenComponents.push_back (path[index]);
break;
}
index++;
}
// std::cout <<
// "groupSequencesFromSpecies 3; pathBetweenComponents.size(): " <<
// pathBetweenComponents.size () << "; List of nodes in the path: "
// << std::endl;
// for (auto it = pathBetweenComponents.begin ();
// it != pathBetweenComponents.end (); ++it)
// {
// std::cout << (*it)->getId () << std::endl;
// }
//Now we have the path between the components, with one node in the first component, and one in the last
//Does any of these nodes include a high bootstrap branch, which would mean we can't join them?
bool canJoinThem = !pathBetweenComponents.empty ();
if (canJoinThem)
{
for (auto it = pathBetweenComponents.begin ();
it != pathBetweenComponents.end (); ++it)
{
if (it + 1 == pathBetweenComponents.end ())
{
break;
}
Node *
next = *(it + 1);
//Find the branch on which we want to check the bootstrap
if (!
((*it) == tree.getRootNode ()
|| next == tree.getRootNode () || (*it)->isLeaf ()
|| next->isLeaf ()))
{
double
bootstrap =
getBootstrapValueOnBranchBetweenTheseTwoNodes (*it,
next);
if (bootstrap > 1)
{
bootstrap = bootstrap / 100.0;
}
if (bootstrap > bootstrapThreshold)
{
canJoinThem = false;
break;
}
}
}
}
if (canJoinThem)
{
//Need to rearrange the tree.
Node *
node1 = *(pathBetweenComponents.begin ());
Node *
node2 = *(pathBetweenComponents.end () - 1);
if (!
(node1->hasFather ()
&& node1->getFather () == pathBetweenComponents[1]))
{
group (node1, node2, tree);
}
else
{
group (node2, node1, tree);
}
weHaveDoneARearrangement = true;
return weHaveDoneARearrangement;
}
}
}
return weHaveDoneARearrangement;
}
/****************************************************************
* Refines the tree to group sequences according to their species in situations where
* there is no highly supported edge that separates the said sequences.
****************************************************************/
void
refineTree (TreeTemplate < Node > &tree,
const std::map < std::string, std::string > &seqSp,
const unordered_set < string > &speciesToRefine,
const double &bootstrapThreshold)
{
std::cout << "Rearranging the tree... " << std::
endl;
if (!speciesToRefine.empty ())
{ //Then only a few species could be rearranged
for (auto it = speciesToRefine.begin (); it != speciesToRefine.end ();
++it)
{
std::cout << "Working with species: " << *it << std::endl;
if (*it != "") {
bool rearrangementsAreDone = true;
while (rearrangementsAreDone)
rearrangementsAreDone = groupSequencesFromSpecies (tree, *it, bootstrapThreshold, seqSp);
}
}
}
else
{ //all species could be rearranged
std::set < string > species;
for (auto it = seqSp.begin (); it != seqSp.end (); ++it)
{
species.insert (it->second);
}
for (auto it = species.begin (); it != species.end (); ++it)
{
if (*it != "") {
bool rearrangementsAreDone = true;
while (rearrangementsAreDone)
rearrangementsAreDone = groupSequencesFromSpecies (tree, *it, bootstrapThreshold, seqSp);
}
}
}
}
/****************************************************************
* Merges sequences to produce one new sequence.
****************************************************************/
string
buildMergedSequence (vector < string > &descendantSequences,
const VectorSiteContainer & seqs)
{
vector < string > uniqueSequences =
VectorTools::unique (descendantSequences);
/*VectorTools::print (descendantSequences);
VectorTools::print (uniqueSequences); */
/*
string sequence = seqs.getSequence(descendantSequences[0]).toString();
for (unsigned int i = 0; i < seqs.getNumberOfSites(); i++)
{
const int* element = &seqs(seqs.getSequencePosition (descendantSequences[0]), i);
if (seqs.getAlphabet()->isGap(*element) || seqs.getAlphabet()->isUnresolved(*element) ) {
for (unsigned int j = 1; j < descendantSequences.size() ; j++)
{
const int* element2 = &seqs(seqs.getSequencePosition (descendantSequences[j]), i);
if ( ! ( seqs.getAlphabet()->isGap(*element2) || seqs.getAlphabet()->isUnresolved(*element2) ) )
//Put the site in the right place in the string sequence
sequence.replace(i, 1, seqs.getAlphabet()->intToChar(*element2));
// sequence[i] = string( ( seqs.getAlphabet()->intToChar(*element2) ) );
break;
}
}
} */
VectorSequenceContainer *
selSeqs = new VectorSequenceContainer (seqs.getAlphabet ());
//SequenceContainer* selSeqs = 0;
SequenceContainerTools::getSelectedSequences (seqs, descendantSequences,
*selSeqs, true);
//use consensus instead:
VectorSiteContainer *
selSeqsSites = new VectorSiteContainer (*selSeqs);
// Sequence* sequence = SiteContainerTools::getConsensus(*(dynamic_cast <const SiteContainer*> (selSeqs) ), "consensus", true, false);
Sequence *
sequence =
SiteContainerTools::getConsensus (*selSeqsSites, "consensus", true,
false);
string toReturn = sequence->toString ();
delete selSeqs;
delete selSeqsSites;
delete sequence;
return toReturn;
}
/****************************************************************
* Select only one sequence in a vector of sequence names.
****************************************************************/
string
selectSequenceAmongSequences (vector < string > &descendantSequences,
string critMeth, VectorSiteContainer & seqs,
string name = "")
{
if (critMeth == "length" || critMeth == "length.complete")
{
vector < double >
seqLen;
for (unsigned int i = 0; i < descendantSequences.size (); i++)
{
if (critMeth == "length.complete")
seqLen.push_back (SequenceTools::getNumberOfCompleteSites
(seqs.getSequence (descendantSequences[i])));
else
seqLen.push_back (SequenceTools::getNumberOfSites
(seqs.getSequence (descendantSequences[i])));
}
return descendantSequences[VectorTools::whichMax (seqLen)];
}
else if (critMeth == "random")
{
return
descendantSequences
[RandomTools::giveIntRandomNumberBetweenZeroAndEntry
(descendantSequences.size ())];
}
else if (critMeth == "merge")
{
string seq = buildMergedSequence (descendantSequences, seqs);
BasicSequence
bseq =
BasicSequence (name + "_" + descendantSequences[0], seq,
seqs.getAlphabet ());
//MYSTERY
if (!seqs.hasSequence (name + "_" + descendantSequences[0]))
seqs.addSequence (bseq);
return name + "_" + descendantSequences[0];
}
else
throw Exception ("Unknown criterion: " + critMeth);
}
/****************************************************************
* Build a map containing distances between ancestor node and leaves.
****************************************************************/
map < string, double >
computeDistanceBetweenLeavesAndAncestor (TreeTemplate < Node > &tree,
Node & node,
vector < string > &sameTaxaSequences)
{
map < string, double >
sequenceDistances;
for (unsigned int i = 0; i < sameTaxaSequences.size (); i++)
{
sequenceDistances.insert (pair < string,
double >(sameTaxaSequences[i],
TreeTemplateTools::getDistanceBetweenAnyTwoNodes
(node,
*(tree.getNode
(sameTaxaSequences[i])))));
}
return sequenceDistances;
}