source: branches/port5/PARSIMONY/AP_tree_edge.cxx

Last change on this file was 6100, checked in by westram, 16 years ago
  • fix warning "format not a string literal and no format arguments"
    • GB_export_error → GB_export_error/GB_export_errorf
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.5 KB
Line 
1#include <stdio.h>
2#include <stdlib.h>
3#include <math.h>
4#include <iostream>
5#include <iomanip>
6#include <memory.h>
7#include <arbdb.h>
8#include <arbdbt.h>
9#include <string.h>
10#include <awt_tree.hxx>
11
12#include "AP_buffer.hxx"
13#include "parsimony.hxx"
14#include "ap_tree_nlen.hxx"
15
16// #include <aw_root.hxx>
17
18using namespace std;
19
20// #define ap_assert(x) arb_assert(x)
21
22/**************************
23
24    Constructor
25    Destructor
26    initialize
27    relink
28    unlink
29
30**************************/
31long AP_tree_edge::timeStamp = 0;
32
33AP_tree_edge::AP_tree_edge(AP_tree_nlen *node1, AP_tree_nlen *node2)
34{
35    // not really necessary, but why not clear all:
36    memset((char *)this,0,sizeof(AP_tree_edge));
37    age  = timeStamp++;
38
39    // link the nodes:
40
41    relink(node1,node2);
42}
43
44AP_tree_edge::~AP_tree_edge()
45{
46    unlink();
47}
48
49static void buildSonEdges(AP_tree_nlen *tree)
50    // Builds edges between a node and his two sons.
51    // We assume there is already an edge to node's father and there are
52    // no edges to his sons.
53{
54    if (!tree->is_leaf)
55    {
56        buildSonEdges(tree->Leftson());
57        buildSonEdges(tree->Rightson());
58
59        // to ensure the nodes contain the correct distance to the border
60        // we MUST build all son edges before creating the father edge
61
62        new AP_tree_edge(tree, tree->Leftson());
63        new AP_tree_edge(tree, tree->Rightson());
64    }
65}
66
67void AP_tree_edge::initialize(AP_tree_nlen *tree)
68    // Builds all edges in the hole tree
69    // The root node is skipped - instead his two sons are connected with an edge
70{
71    while (tree->Father()) tree = tree->Father();   // go up to root
72    buildSonEdges(tree->Leftson());         // link left subtree
73    buildSonEdges(tree->Rightson());            // link right subtree
74
75    // to ensure the nodes contain the correct distance to the border
76    // we MUST build all son edges before creating the root edge
77
78    new AP_tree_edge(tree->Leftson(),tree->Rightson()); // link brothers
79}
80
81void AP_tree_edge::tailDistance(AP_tree_nlen *n)
82{
83    ap_assert(!n->is_leaf);    // otherwise call was not neccessary!
84
85    int i0 = n->indexOf(this);          // index of this
86    int i1 = i0==0 ? 1 : 0;             // the indices of the other two nodes (beside n)
87    int i2 = i1==1 ? 2 : (i0==1 ? 2 : 1);
88    AP_tree_edge *e1 = n->edge[i1];     // edges to the other two nodes
89    AP_tree_edge *e2 = n->edge[i2];
90
91    cout << "tail n=" << n << " d(n)=" << n->distance << " ";
92
93    if (e1 && e2)
94    {
95        AP_tree_nlen *n1 = e1->node[1-n->index[i1]]; // the other two nodes
96        AP_tree_nlen *n2 = e2->node[1-n->index[i2]];
97
98        cout <<  "n1=" << n1 << " d(n1)=" << n1->distance <<
99            " n2=" << n2 << " d(n2)=" << n2->distance << " ";
100
101        if (n1->distance==n2->distance)
102        {
103            if (n1->distance>n->distance && n2->distance>n->distance)
104            {
105                // both distances (of n1 and n2) are greather that distance of n
106                // so its possible that the nearest connection the border was
107                // via node n and we must recalculate the distance into the other
108                // directions
109
110                ap_assert(n1->distance==n2->distance);
111
112                cout << "special tailDistance-case\n";
113                e1->tailDistance(n1);
114                e2->tailDistance(n2);
115
116                if (n1->distance<n2->distance)
117                {
118                    n->distance = n1->distance+1;
119                    if (!e2->distanceOK()) e2->calcDistance();
120                }
121                else
122                {
123                    n->distance = n2->distance+1;
124                    if (!e1->distanceOK()) e1->calcDistance();
125                }
126            }
127            else
128            {
129                cout << "tail case 2\n";
130                n->distance = n1->distance+1;
131            }
132        }
133        else
134        {
135            ap_assert(n1->distance != n2->distance);
136
137            if (n1->distance<n2->distance)
138            {
139                if (n1->distance<n->distance)
140                {
141                    // in this case the distance via n1 is the same as
142                    // the distance via the cutted edge - so we do nothing
143
144                    cout << "tail case 3\n";
145                    ap_assert(n1->distance==(n->distance-1));
146                }
147                else
148                {
149                    cout << "tail case 4\n";
150                    ap_assert(n1->distance==n->distance);
151                    ap_assert(n2->distance==(n->distance+1));
152
153                    n->distance = n1->distance+1;
154                    e2->tailDistance(n2);
155                }
156            }
157            else
158            {
159                ap_assert(n2->distance<n1->distance);
160
161                if (n2->distance<n->distance)
162                {
163                    // in this case the distance via n2 is the same as
164                    // the distance via the cutted edge - so we do nothing
165
166                    cout << "tail case 5\n";
167                    ap_assert(n2->distance==(n->distance-1));
168                }
169                else
170                {
171                    cout << "tail case 6\n";
172                    ap_assert(n2->distance==n->distance);
173                    ap_assert(n1->distance==(n->distance+1));
174
175                    n->distance = n2->distance+1;
176                    e1->tailDistance(n1);
177                }
178            }
179        }
180
181        //  cout << "e1=" << *e1 << endl;
182        //  cout << "e2=" << *e2 << endl;
183
184        cout << "d(n)=" << n->distance <<
185            " d(n1)=" << n1->distance <<
186            " d(n2)=" << n2->distance <<
187            " D(e1)=" << e1->Distance() <<
188            " D(e2)=" << e2->Distance() <<
189            " dtb(e1)=" << e1->distanceToBorder(INT_MAX,n) <<
190            " dtb(e2)=" << e2->distanceToBorder(INT_MAX,n) << endl;
191
192        //  ap_assert(e1->Distance()==e1->distanceToBorder(INT_MAX,n));
193        //  ap_assert(e2->Distance()==e2->distanceToBorder(INT_MAX,n));
194    }
195    else
196    {
197        if (e1)
198        {
199            AP_tree_nlen *n1 = e1->node[1-n->index[i1]];
200
201            cout << "tail case 7\n";
202            ap_assert(n1!=0);
203            if (n1->distance>n->distance) e1->tailDistance(n1);
204            n->distance = n1->distance+1;
205
206            //      cout << "e1=" << *e1 << endl;
207
208            cout << "d(n)=" << n->distance <<
209                " d(n1)=" << n1->distance <<
210                " D(e1)=" << e1->Distance() <<
211                " dtb(e1)=" << e1->distanceToBorder(INT_MAX,n) << endl;
212
213
214            //      ap_assert(e1->Distance()==e1->distanceToBorder(INT_MAX,n));
215        }
216        else if (e2)
217        {
218            AP_tree_nlen *n2 = e2->node[1-n->index[i2]];
219
220            cout << "tail case 8\n";
221            ap_assert(n2!=0);
222            cout << "d(n2)=" << n2->distance << " d(n)=" << n->distance << endl;
223
224            if (n2->distance>n->distance) e2->tailDistance(n2);
225            n->distance = n2->distance+1;
226
227            //      cout << "e2=" << *e2 << endl;
228
229            cout << "d(n)=" << n->distance <<
230                " d(n2)=" << n2->distance <<
231                " D(e2)=" << e2->Distance() <<
232                " dtb(e2)=" << e2->distanceToBorder(INT_MAX,n) << endl;
233
234            //      ap_assert(e2->Distance()==e2->distanceToBorder(INT_MAX,n));
235        }
236        else
237        {
238            cout << "tail case 9\n";
239            n->distance = INT_MAX;
240        }
241    }
242}
243
244AP_tree_edge* AP_tree_edge::unlink()
245{
246    ap_assert(this!=0);
247
248    //    cout << "------ unlink" << endl;
249
250    //    switch (node[0]->distance-node[1]->distance)
251    //    {
252    //     case -1: // n1->distance > n0->distance
253    //  {
254    //      ap_assert(!node[1]->is_leaf);
255    //      tailDistance(node[1]);
256    //      break;
257    //  }
258    //     case 0:  // equal -> distances remain correct
259    //  {
260    //      break;
261    //  }
262    //     case 1:  // n0->distance > n1->distance
263    //  {
264    //      ap_assert(!node[0]->is_leaf);
265    //      tailDistance(node[0]);
266    //      break;
267    //  }
268    //     default:
269    //  {
270    //      cerr << "error in distances" << endl;
271    //  }
272    //    }
273
274    node[0]->edge[index[0]] = NULL;
275    node[1]->edge[index[1]] = NULL;
276
277    node[0] = NULL;
278    node[1] = NULL;
279
280    return this;
281}
282
283void AP_tree_edge::calcDistance()
284{
285    ap_assert(!distanceOK());  // otherwise call was not neccessary
286    ap_assert (node[0]->distance!=node[1]->distance);
287
288    if (node[0]->distance < node[1]->distance)  // node[1] has wrong distance
289    {
290        cout << "dist(" << node[1] << ") " << node[1]->distance;
291
292        if (node[1]->distance==INT_MAX) // not initialized -> do not recurse
293        {
294            node[1]->distance = node[0]->distance+1;
295            cout  << " -> " << node[1]->distance << endl;
296        }
297        else
298        {
299            node[1]->distance = node[0]->distance+1;
300            cout  << " -> " << node[1]->distance << endl;
301
302            if (!node[1]->is_leaf)
303            {
304                for (int e=0; e<3; e++)     // recursively correct distance where neccessary
305                {
306                    AP_tree_edge *ed = node[1]->edge[e];
307                    if (ed && ed!=this && !ed->distanceOK()) ed->calcDistance();
308                }
309            }
310        }
311    }
312    else                        // node[0] has wrong distance
313    {
314        cout << "dist(" << node[0] << ") " << node[0]->distance;
315
316        if (node[0]->distance==INT_MAX) // not initialized -> do not recurse
317        {
318            node[0]->distance = node[1]->distance+1;
319            cout  << " -> " << node[0]->distance << endl;
320        }
321        else
322        {
323            node[0]->distance = node[1]->distance+1;
324            cout  << " -> " << node[0]->distance << endl;
325
326            if (!node[0]->is_leaf)
327            {
328                for (int e=0; e<3; e++)     // recursively correct distance where neccessary
329                {
330                    AP_tree_edge *ed = node[0]->edge[e];
331                    if (ed && ed!=this && !ed->distanceOK()) ed->calcDistance();
332                }
333            }
334        }
335    }
336
337    ap_assert(distanceOK());   // invariant of AP_tree_edge (if fully constructed)
338}
339
340void AP_tree_edge::relink(AP_tree_nlen *node1,AP_tree_nlen *node2)
341{
342    //    cout << "------ relink" << endl;
343
344    node[0] = node1;
345    node[1] = node2;
346
347    node1->edge[index[0] = node1->unusedEdge()] = this;
348    node2->edge[index[1] = node2->unusedEdge()] = this;
349
350    node1->index[index[0]] = 0;
351    node2->index[index[1]] = 1;
352
353    //    if (node1->is_leaf) node1->distance = 0;
354    //    if (node2->is_leaf) node2->distance = 0;
355
356    //    cout << "relink (dist = (" << node1->distance << ","
357    //                     << node2->distance << "))" << endl;
358
359    //    if (!distanceOK()) calcDistance();
360}
361
362/**************************
363    test
364**************************/
365
366int AP_tree_edge::test() const
367{
368    int ok = 1;     // result is used by
369    int n;
370
371    for (n=0; n<2; n++)
372    {
373        if (node[n]->edge[index[n]]!=this)
374        {
375            int i;
376
377            for (i=0; i<3; i++)
378            {
379                if (node[n]->edge[i]==this) break;
380            }
381
382            if (i==3)
383            {
384                cout << *this << " points to wrong node " << node[n]
385                     << '\n';
386                ok = 0;
387            }
388            else
389            {
390                cout << *this << " has wrong index ("
391                     << index[n] << "instead of " << i << ")\n";
392                ok = 0;
393            }
394        }
395    }
396
397    if (!distanceOK() ||
398        (node[0]->is_leaf && node[0]->distance!=0) ||
399        (node[1]->is_leaf && node[1]->distance!=0))
400    {
401        cout << "distance not set correctly at" << *this << '\n';
402    }
403    else if (Distance()!=distanceToBorder())
404    {
405        cout << "Distance() != distanceToBorder()" << endl;
406    }
407
408    return ok;
409}
410
411/**************************
412
413Recursive methods:
414
415    clearValues
416
417**************************/
418
419/*
420int AP_tree_edge::clearValues(int deep, AP_tree_nlen *skip)
421{
422    int cnt = 1;
423
424    used = 0;
425    data.distance = 0;
426
427    if (deep--)
428    for (int n=0; n<2; n++)
429        if (node[n]!=skip && !node[n]->is_leaf)
430        for (int e=0; e<3; e++)
431            if (node[n]->edge[e]!=this)
432            cnt += node[n]->edge[e]->clearValues(deep,node[n]);
433
434    return cnt;
435}
436*/
437
438void AP_tree_edge::testChain(int deep)
439{
440    cout << "Building chain (deep=" << deep << ")\n";
441    buildChain(deep,GB_FALSE);
442    int inChain = dumpChain();
443    cout << "Edges in Chain = " << inChain << '\n';
444}
445
446int AP_tree_edge::dumpChain(void) const
447{
448    //    cout << this << '\n';
449    return next ? 1+next->dumpChain() : 1;
450}
451
452AP_tree_edge* AP_tree_edge::buildChain(int deep, GB_BOOL skip_hidden,
453                                       int distanceToInsert,
454                                       const AP_tree_nlen *skip,
455                                       AP_tree_edge *comesFrom)
456{
457    AP_tree_edge *last = this;
458
459    data.distance = distanceToInsert++;
460    if (comesFrom) comesFrom->next = this;
461    this->next = NULL;
462    if (skip_hidden){
463        if (node[0]->gr.hidden) return last;
464        if (node[1]->gr.hidden) return last;
465        if ( (!node[0]->gr.has_marked_children) && (!node[1]->gr.has_marked_children)) return last;
466    }
467
468    if (deep--)
469        for (int n=0; n<2; n++)
470            if (node[n]!=skip && !node[n]->is_leaf){
471                for (int e=0; e<3; e++){
472                    if (node[n]->edge[e]!=this){
473                        last = node[n]->edge[e]->buildChain(deep,skip_hidden,distanceToInsert,node[n],last);
474                    }
475                }
476            }
477
478    return last;
479}
480
481long AP_tree_edge::sizeofChain(void){
482    AP_tree_edge *f;
483    long c= 0;
484    for (f=this; f ; f = f->next) c++;
485    return c;
486}
487
488int AP_tree_edge::distanceToBorder(int maxsearch,AP_tree_nlen *skipNode) const
489    // return the minimal distance to the border of the tree
490    // a return value of 0 means: one of the nodes is a leaf
491{
492    if ((node[0] && node[0]->is_leaf) || (node[1] && node[1]->is_leaf))
493    {
494        //  cout << "dtb(" << *this << ")=" << 0 << endl;
495        return 0;
496    }
497
498    for (int n=0; n<2 && maxsearch; n++)
499    {
500        if (node[n] && node[n]!=skipNode)
501        {
502            for (int e=0; e<3; e++)
503            {
504                AP_tree_edge *ed = node[n]->edge[e];
505
506                if (ed && ed!=this)
507                {
508                    int dist = ed->distanceToBorder(maxsearch-1, node[n])+1;
509                    if (dist<maxsearch) maxsearch = dist;
510                }
511            }
512        }
513    }
514
515    //    cout << "dtb(" << *this << ")=" << maxsearch+1 << endl;
516    return maxsearch;
517}
518
519void AP_tree_edge::countSpecies(int deep,const AP_tree_nlen *skip)
520{
521    if (!skip)
522    {
523        speciesInTree = 0;
524        nodesInTree   = 0;
525    }
526
527    if (deep--)
528    {
529        for (int n=0; n<2; n++)
530        {
531            if (node[n]->is_leaf)
532            {
533                speciesInTree++;
534                nodesInTree++;
535            }
536            else if (node[n]!=skip)
537            {
538                nodesInTree++;
539
540                for (int e=0; e<3; e++)
541                {
542                    if (node[n]->edge[e]!=this)
543                    {
544                        node[n]->edge[e]->countSpecies(deep,node[n]);
545                    }
546                }
547            }
548        }
549    }
550}
551
552/**************************
553    tree optimization
554**************************/
555void ap_init_bootstrap_remark(AP_tree_nlen *son_node){
556    int seq_len = son_node->sequence->root->filter->real_len;
557    AP_sequence::static_mutation_per_site[0] = (char *)GB_calloc(sizeof(char),seq_len);
558    AP_sequence::static_mutation_per_site[1] = (char *)GB_calloc(sizeof(char),seq_len);
559    AP_sequence::static_mutation_per_site[2] = (char *)GB_calloc(sizeof(char),seq_len);
560}
561
562double fak(int n,int m){
563    double res = 1.0;
564    while (n>m){
565        res *= n;
566        n--;
567    }
568    return res;
569}
570
571
572double ap_calc_bootstrap_remark_sub(int seq_len, char *old, char *ne){
573    int i;
574    int sum[3];
575    sum[0] = 0;
576    sum[1] = 0;
577    sum[2] = 0;
578    for (i=0;i<seq_len;i++){
579        int diff = ne[i] - old[i];
580        if (diff > 1 || diff < -1){
581            GB_export_errorf("diff by nni at one position not in [-1,1]: %i:%i - %i",diff,old[i],ne[i]);
582            GB_print_error();
583            continue;
584        }
585        sum[diff+1] ++;
586    }
587    {
588        int msum = 0;
589        for (i=0;i<seq_len;i++){
590            msum += old[i];
591            msum += ne[i];
592        }
593        msum /= 2;
594    }
595    double prob = 0;
596    {
597        int asum = 0;
598        for (i=0;i<3;i++) asum += sum[i];
599        double freq[3];
600        double log_freq[3];
601        for (i=0;i<3;i++){
602            freq[i] = sum[i] / double(asum); // relative frequencies of -1, 0, 1
603            if (sum[i] >0){
604                log_freq[i] = log(freq[i]);
605            }else{
606                log_freq[i] = -1e100; // minus infinit
607            }
608        }
609
610        int max = seq_len;  // bootstrap can select seq_len ones maximum
611        double log_fak_seq_len = GB_log_fak(seq_len);
612        double log_eps = log(1e-11);
613
614        //printf("********* %i %i %i     max %i\n",sum[0],sum[1],sum[2],max);
615        // loop over all delta_mutations, begin in the middle
616        for ( int tsum_add = 1; tsum_add >= -1; tsum_add -= 2){
617            int tsum = sum[2]-sum[0];
618            if (tsum <=0) tsum = 1;
619            for (; tsum < max && tsum > 0; tsum += tsum_add){       // sum of mutations in bootstrap sample, loop over all possibilities
620                if (tsum_add < 0 && tsum == sum[2]-sum[0]) continue; // don't double count tsum
621
622
623
624                int max_minus = max;        // we need tsum + n_minus ones, we cannot have more than max_minux minus, reduce also
625                for (int minus_add = 1; minus_add>=-1;minus_add-=2){
626                    int first_minus = 1;
627                    for (int n_minus = sum[0]; n_minus<max_minus && n_minus>=0; first_minus = 0, n_minus+=minus_add){
628                        if (minus_add < 0 && first_minus) continue; // dont double count center
629                        int n_zeros = seq_len - n_minus * 2 - tsum; // number of minus
630                        int n_plus = tsum + n_minus; // number of plus ones  (n_ones + n_minus + n_zeros = seq_len)
631
632                        double log_a =
633                            n_minus * log_freq[0] +
634                            n_zeros * log_freq[1] +
635                            n_plus  * log_freq[2] +
636                            log_fak_seq_len - GB_log_fak(n_minus) - GB_log_fak(n_zeros) - GB_log_fak(n_plus);
637
638                        if (log_a < log_eps){
639                            if (first_minus && minus_add>0) goto end;
640                            break; // cannot go with so many minus, try next
641                        }
642                        double a = exp(log_a);
643                        //printf("\t\t%i %i %6f %e\n",tsum,n_minus,log_a,a);
644                        prob += a;
645                    }
646                }
647            }
648        end:;
649        }
650    }
651    //printf("&&&&&&&& result %e\n",prob);
652    return prob;
653}
654
655void ap_calc_bootstrap_remark(AP_tree_nlen *son_node,AP_BL_MODE mode){
656    if (!son_node->is_leaf){
657        int seq_len = son_node->sequence->root->filter->real_len;
658        float one = ap_calc_bootstrap_remark_sub(seq_len,
659                                                 &AP_sequence::static_mutation_per_site[0][0],
660                                                 &AP_sequence::static_mutation_per_site[1][0]);
661        float two = ap_calc_bootstrap_remark_sub(seq_len,
662                                                 &AP_sequence::static_mutation_per_site[0][0],
663                                                 &AP_sequence::static_mutation_per_site[2][0]);
664        if ((mode & AP_BL_BOOTSTRAP_ESTIMATE) == AP_BL_BOOTSTRAP_ESTIMATE){
665            one = one * two;    // assume independent bootstrap values for both nnis
666        }else{
667            if (two<one) one = two; // dependent bootstrap values, take minimum (safe)
668        }
669        const char *text = 0;
670        if (one < 1.0){ // was: < 0.99
671            text = GBS_global_string("%i%%",int(100.0 * one + 0.5));
672        }
673        else {
674            text = "100%";
675        }
676        freedup(son_node->remark_branch, text);
677        freedup(son_node->Brother()->remark_branch, text);
678    }
679   
680    freeset(AP_sequence::static_mutation_per_site[0], NULL);
681    freeset(AP_sequence::static_mutation_per_site[1], NULL);
682    freeset(AP_sequence::static_mutation_per_site[2], NULL);
683}
684
685
686void ap_calc_leaf_branch_length(AP_tree_nlen *leaf){
687    AP_FLOAT Seq_len = leaf->sequence->real_len();
688    if (Seq_len <=1.0) Seq_len = 1.0;
689
690    AP_FLOAT parsbest = rootNode()->costs();
691    ap_main->push();
692    leaf->remove();
693    AP_FLOAT Blen     = parsbest - rootNode()->costs();
694    ap_main->pop();
695    double   blen     = Blen/Seq_len;
696
697#if defined(DEBUG)
698    // printf("Blen=%f name=%s\n", Blen, leaf->name);
699#endif // DEBUG
700
701
702    if (!leaf->father->father){ // at root
703        leaf->father->leftlen = blen*.5;
704        leaf->father->rightlen = blen*.5;
705    }else{
706        if (leaf->father->leftson == leaf){
707            leaf->father->leftlen = blen;
708        }else{
709            leaf->father->rightlen = blen;
710        }
711    }
712}
713
714
715
716
717void ap_calc_branch_lengths(AP_tree_nlen */*root*/, AP_tree_nlen *son, double /*parsbest*/, double blen){
718    static double s_new = 0.0;
719    static double s_old = 0.0;
720
721    AP_FLOAT seq_len = son->sequence->real_len();
722    if (seq_len <=1.0) seq_len = 1.0;
723    blen *= 0.5 / seq_len * 2.0;        // doubled counted sum * corr
724
725    AP_tree_nlen *fathr = son->Father();
726    double old_len = 0.0;
727    if (!fathr->father){    // at root
728        old_len = fathr->leftlen + fathr->rightlen;
729        fathr->leftlen = blen *.5;
730        fathr->rightlen = blen *.5;
731    }else{
732        if (fathr->leftson == son){
733            old_len = fathr->leftlen;
734            fathr->leftlen = blen;
735        }else{
736            old_len = fathr->rightlen;
737            fathr->rightlen = blen;
738        }
739    }
740    if (old_len< 1e-5) old_len = 1e-5;
741    s_new += blen;
742    s_old += old_len;
743    //printf("slen %5i Old\t%f, new\t%f, :\t%f\t%f\n",int(seq_len),old_len,blen,blen/old_len,s_new/s_old);
744
745    if (son->leftson->is_leaf){
746        ap_calc_leaf_branch_length((AP_tree_nlen*)son->leftson);
747    }
748
749    if (son->rightson->is_leaf){
750        ap_calc_leaf_branch_length((AP_tree_nlen*)son->rightson);
751    }
752}
753const double ap_undef_bl = 10.5;
754
755void ap_check_leaf_bl(AP_tree_nlen *node){
756    if (node->is_leaf){
757        if (!node->father->father){
758            if (node->father->leftlen + node->father->rightlen == ap_undef_bl){
759                ap_calc_leaf_branch_length(node);
760            }
761        }else if (node->father->leftson == node){
762            if (node->father->leftlen == ap_undef_bl){
763                ap_calc_leaf_branch_length(node);
764            }
765        }else{
766            if (node->father->rightlen == ap_undef_bl){
767                ap_calc_leaf_branch_length(node);
768            }
769        }
770        return;
771    }else{
772        if (node->leftlen == ap_undef_bl)   ap_calc_leaf_branch_length((AP_tree_nlen *)node->leftson);
773        if (node->rightlen== ap_undef_bl)   ap_calc_leaf_branch_length((AP_tree_nlen *)node->rightson);
774    }
775}
776
777AP_FLOAT AP_tree_edge::nni_rek(AP_BOOL useStatus, int &Abort, int deep, GB_BOOL skip_hidden,
778                               AP_BL_MODE mode, AP_tree_nlen *skipNode)
779{
780    if (!rootNode())        return 0.0;
781    if (rootNode()->is_leaf)    return rootNode()->costs();
782
783    AP_tree_edge *oldRootEdge = rootEdge();
784
785    if (useStatus) aw_openstatus("Recursive NNI");
786    if (deep>=0) set_root();
787
788    AP_FLOAT old_parsimony = rootNode()->costs();
789    AP_FLOAT new_parsimony = old_parsimony;
790
791    buildChain(deep,skip_hidden,0,skipNode);
792    long cs = sizeofChain();
793    AP_tree_edge *follow;
794    long count = 0;
795    { // set all branch lengths to undef
796        for (follow = this;follow; follow = follow->next){
797            follow->node[0]->leftlen          = ap_undef_bl;
798            follow->node[0]->rightlen         = ap_undef_bl;
799            follow->node[1]->leftlen          = ap_undef_bl;
800            follow->node[1]->rightlen         = ap_undef_bl;
801            follow->node[0]->father->leftlen  = ap_undef_bl;
802            follow->node[0]->father->rightlen = ap_undef_bl;
803        }
804        rootNode()->leftlen  = ap_undef_bl *.5;
805        rootNode()->rightlen = ap_undef_bl *.5;
806    }
807
808    if (useStatus) aw_status(0.0);
809
810    for (follow = this; follow && Abort == 0; follow = follow->next){
811        AP_tree_nlen *son = follow->sonNode();
812        AP_tree_nlen *fath = son;
813
814        if (follow->otherNode(fath)==fath->Father()) fath = fath->Father();
815        if (fath->father){
816            if (fath->father->father){
817                fath->set_root();
818                new_parsimony = rootNode()->costs();
819            }
820        }
821        if (mode & AP_BL_BOOTSTRAP_LIMIT){
822            if (fath->father){
823                son->set_root();
824                new_parsimony = rootNode()->costs();
825            }
826            ap_init_bootstrap_remark(son);
827        }
828        new_parsimony = follow->nni(new_parsimony, mode);
829        if (mode & AP_BL_BOOTSTRAP_LIMIT){
830            ap_calc_bootstrap_remark(son,mode);
831        }
832        if (useStatus ? aw_status(++count/(double)cs) : aw_status()) { Abort = 1; break; }
833    }
834
835    if (useStatus) {
836        aw_status("Recalc modified branches");
837        aw_status(0.0);
838        count = 0;
839    }
840
841    for (follow = this; follow && Abort == 0; follow = follow->next){
842        ap_check_leaf_bl(follow->node[0]);
843        ap_check_leaf_bl(follow->node[1]);
844        if (useStatus ? aw_status(++count/(double)cs) : aw_status()) { Abort = 1; break; }
845    }
846    oldRootEdge->set_root();
847    new_parsimony = rootNode()->costs();
848    if (useStatus) aw_closestatus();
849
850    return new_parsimony;
851}
852
853int AP_tree_edge::dumpNNI = 0;
854int AP_tree_edge::distInsertBorder;
855int AP_tree_edge::basesChanged;
856int AP_tree_edge::speciesInTree;
857int AP_tree_edge::nodesInTree;
858
859AP_FLOAT AP_tree_edge::nni(AP_FLOAT pars_one, AP_BL_MODE mode)
860{
861    AP_tree_nlen *root = (AP_tree_nlen *) (*ap_main->tree_root);
862
863    if (node[0]->is_leaf || node[1]->is_leaf) { // a son at root
864#if 0
865        // calculate branch lengths at root
866        if (mode&AP_BL_BL_ONLY){
867            AP_tree_nlen *tip,*brother;
868
869            if (node[0]->is_leaf){
870                tip = node[0]; brother = node[1];
871            }else{
872                tip = node[1]; brother = node[0];
873            }
874
875            AP_FLOAT    Blen = pars_one - brother->costs();
876            AP_FLOAT    Seq_len = tip->sequence->real_len();
877
878            node[0]->father->leftlen = node[0]->father->rightlen = Blen/Seq_len*.5;
879        }
880#endif
881        return pars_one;
882    }
883
884    AP_tree_edge_data oldData = data;
885
886    AP_FLOAT    parsbest = pars_one,
887        pars_two,
888        pars_three;
889    AP_tree_nlen *son = sonNode();
890    int     betterValueFound = 0;
891    {               // ******** original tree
892        if ( (mode & AP_BL_BOOTSTRAP_LIMIT)){
893            root->costs();
894            char *ms = AP_sequence::static_mutation_per_site[0];
895            AP_sequence::mutation_per_site = ms;
896            son->unhash_sequence();
897            son->father->unhash_sequence();
898            ap_assert(!son->father->father);
899            AP_tree_nlen *brother = son->Brother();
900            brother->unhash_sequence();
901            pars_one = 0.0;
902        }
903        if (pars_one==0.0) pars_one = root->costs();
904    }
905    {               // ********* first nni
906        ap_main->push();
907        son->swap_assymetric(AP_LEFT);
908        char *ms = AP_sequence::static_mutation_per_site[1];
909        AP_sequence::mutation_per_site = ms;
910        pars_two = root->costs();
911
912        if (pars_two <= parsbest){
913            if ((mode & AP_BL_NNI_ONLY)==0) ap_main->pop();
914            else                ap_main->clear();
915            parsbest = pars_two;
916            betterValueFound = (int)(pars_one-pars_two);
917        }else{
918            ap_main->pop();
919        }
920    }
921    {               // ********** second nni
922        ap_main->push();
923        son->swap_assymetric(AP_RIGHT);
924        char *ms = AP_sequence::static_mutation_per_site[2];
925        AP_sequence::mutation_per_site = ms;
926        pars_three = root->costs();
927
928        if (pars_three <= parsbest){
929            if ((mode & AP_BL_NNI_ONLY)==0) ap_main->pop();
930            else                ap_main->clear();
931            parsbest = pars_three;
932            betterValueFound = (int)(pars_one-pars_three);
933        }else{
934            ap_main->pop();
935        }
936        AP_sequence::mutation_per_site = 0;
937    }
938
939    if (mode & AP_BL_BL_ONLY){  // ************* calculate branch lengths **************
940        AP_FLOAT blen = (pars_one + pars_two + pars_three) - (3.0 * parsbest) ;
941        if (blen <0) blen = 0;
942        ap_calc_branch_lengths(root,son,parsbest, blen);
943    }
944
945    // zu Auswertungszwecken doch unsortiert uebernehmen:
946
947    data.parsValue[0] = pars_one;
948    data.parsValue[1] = pars_two;
949    data.parsValue[2] = pars_three;
950
951
952    if (dumpNNI)
953    {
954        if (dumpNNI==2)
955        {
956            fprintf(stderr,"Fatal! NNI called between optimize and statistics!\n");
957            exit(1);
958        }
959        AP_tree_nlen *node0 = this->node[0];
960        AP_tree_nlen *node1 = this->node[1];
961        if (node0->gr.leave_sum > node1->gr.leave_sum){ //node0 is final son
962            node0 = node1;
963        }
964        static int num = 0;
965        delete node0->remark_branch;
966        node0->remark_branch = (char *)calloc(sizeof(char),100);
967        sprintf(node0->remark_branch, "%i %4.0f:%4.0f:%4.0f     %4.0f:%4.0f:%4.0f\n",num++,
968                oldData.parsValue[0],oldData.parsValue[1],oldData.parsValue[2],
969                data.parsValue[0],data.parsValue[1],data.parsValue[2]);
970
971
972        cout
973            << setw(4) << distInsertBorder
974            << setw(6) << basesChanged
975            << setw(4) << distanceToBorder()
976            << setw(4) << data.distance
977            << setw(4) << betterValueFound
978            << setw(8) << oldData.parsValue[0]
979            << setw(8) << oldData.parsValue[1]
980            << setw(8) << oldData.parsValue[2]
981            << setw(8) << data.parsValue[0]
982            << setw(8) << data.parsValue[1]
983            << setw(8) << data.parsValue[2]
984            << '\n';
985    }
986
987    return parsbest;
988}
989
990/**************************
991    operator <<
992**************************/
993
994ostream& operator<<(ostream& out, const AP_tree_edge& e)
995{
996    static int notTooDeep;
997
998    out << ' ';
999
1000    if (notTooDeep || &e==NULL)
1001    {
1002        out << e;
1003    }
1004    else
1005    {
1006        notTooDeep = 1;
1007        out << "AP_tree_edge(" << e
1008            << ", node[0]=" << *(e.node[0])
1009            << ", node[1]=" << *(e.node[1])
1010            << ")";
1011        notTooDeep = 0;
1012    }
1013
1014    return out << ' ';
1015}
1016
1017void AP_tree_edge::mixTree(int cnt)
1018{
1019    buildChain(-1);
1020
1021    while (cnt--)
1022    {
1023        AP_tree_edge *follow = this;
1024
1025        while (follow) {
1026            follow->sonNode()->swap_assymetric(GB_random(2) ? AP_LEFT : AP_RIGHT);
1027            follow = follow->next;
1028        }
1029    }
1030}
Note: See TracBrowser for help on using the repository browser.