source: tags/arb-6.0.2/STAT/ST_ml.cxx

Last change on this file was 12267, checked in by westram, 12 years ago
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.2 KB
Line 
1// =============================================================== //
2//                                                                 //
3//   File      : ST_ml.cxx                                         //
4//   Purpose   :                                                   //
5//                                                                 //
6//   Institute of Microbiology (Technical University Munich)       //
7//   http://www.arb-home.de/                                       //
8//                                                                 //
9// =============================================================== //
10
11#include "st_ml.hxx"
12#include "MostLikelySeq.hxx"
13
14#include <ColumnStat.hxx>
15#include <AP_filter.hxx>
16#include <AP_Tree.hxx>
17#include <arb_progress.h>
18#include <gui_aliview.hxx>
19#include <ad_cb.h>
20
21#include <cctype>
22#include <cmath>
23
24DNA_Table dna_table;
25
26DNA_Table::DNA_Table() {
27    int i;
28    for (i = 0; i < 256; i++) {
29        switch (toupper(i)) {
30            case 'A':
31                char_to_enum_table[i] = ST_A;
32                break;
33            case 'C':
34                char_to_enum_table[i] = ST_C;
35                break;
36            case 'G':
37                char_to_enum_table[i] = ST_G;
38                break;
39            case 'T':
40            case 'U':
41                char_to_enum_table[i] = ST_T;
42                break;
43            case '-':
44                char_to_enum_table[i] = ST_GAP;
45                break;
46            default:
47                char_to_enum_table[i] = ST_UNKNOWN;
48        }
49    }
50}
51
52// -----------------------
53//      ST_base_vector
54
55void ST_base_vector::setBase(const ST_base_vector& inv_frequencies, char base) {
56    base = toupper(base);
57   
58    memset((char *) &b[0], 0, sizeof(b));
59    DNA_Base     ub = dna_table.char_to_enum(base);
60
61    if (ub != ST_UNKNOWN) {
62        b[ub] = 1.0;                                // ill. access ?
63    }
64    else {
65        const double k = 1.0 / ST_MAX_BASE;
66        b[ST_A]   = k;
67        b[ST_C]   = k;
68        b[ST_G]   = k;
69        b[ST_T]   = k;
70        b[ST_GAP] = k;
71    }
72    for (int i = 0; i < ST_MAX_BASE; i++) {
73        b[i] *= inv_frequencies.b[i];
74    }
75    ld_lik = 0; // ? why not 1.0 ?
76    lik = 1.0;
77}
78
79inline void ST_base_vector::check_overflow() {
80    ST_FLOAT sum = summarize();
81
82    if (sum < .00001) {                             // what happend no data, extremely unlikely
83        setTo(0.25);                                // strange! shouldn't this be 1.0/ST_MAX_BASE ?
84        ld_lik -= 5;                                // ???
85    }
86    else {
87        while (sum < 0.25) {
88            sum    *= 4;
89            ld_lik -= 2;
90            multiplyWith(4);
91        }
92    }
93
94    if (ld_lik> 10000) printf("overflow\n");
95}
96
97inline ST_base_vector& ST_base_vector::operator*=(const ST_base_vector& other) {
98    b[ST_A]   *= other.b[ST_A];
99    b[ST_C]   *= other.b[ST_C];
100    b[ST_G]   *= other.b[ST_G];
101    b[ST_T]   *= other.b[ST_T];
102    b[ST_GAP] *= other.b[ST_GAP];
103   
104    ld_lik += other.ld_lik; // @@@ correct to use 'plus' here ? why ?
105    lik    *= other.lik;
106
107    return *this;
108}
109
110void ST_base_vector::print() {
111    int i;
112    for (i = 0; i < ST_MAX_BASE; i++) {
113        printf("%.3G ", b[i]);
114    }
115}
116
117// -----------------------
118//      ST_rate_matrix
119
120void ST_rate_matrix::set(double dist, double /* TT_ratio */) {
121    const double k = 1.0 / ST_MAX_BASE;
122    ST_FLOAT exp_dist = exp(-dist);
123
124    diag = k + (1.0 - k) * exp_dist;
125    rest = k - k * exp_dist;
126}
127
128void ST_rate_matrix::print() {
129    for (int i = 0; i < ST_MAX_BASE; i++) {
130        for (int j = 0; j < ST_MAX_BASE; j++) {
131            printf("%.3G ", i == j ? diag : rest);
132        }
133        printf("\n");
134    }
135}
136
137
138inline void ST_rate_matrix::transform(const ST_base_vector& in, ST_base_vector& out) const {
139    // optimized matrix/vector multiplication
140    // original version: http://bugs.arb-home.de/browser/trunk/STAT/ST_ml.cxx?rev=6403#L155
141
142    ST_FLOAT sum            = in.summarize();
143    ST_FLOAT diag_rest_diff = diag-rest;
144    ST_FLOAT sum_rest_prod  = sum*rest;
145
146    out.b[ST_A]   = in.b[ST_A]*diag_rest_diff + sum_rest_prod;
147    out.b[ST_C]   = in.b[ST_C]*diag_rest_diff + sum_rest_prod;
148    out.b[ST_G]   = in.b[ST_G]*diag_rest_diff + sum_rest_prod;
149    out.b[ST_T]   = in.b[ST_T]*diag_rest_diff + sum_rest_prod;
150    out.b[ST_GAP] = in.b[ST_GAP]*diag_rest_diff + sum_rest_prod;
151
152    out.ld_lik = in.ld_lik;
153    out.lik    = in.lik;
154}
155
156
157// -----------------------
158//      MostLikelySeq
159
160MostLikelySeq::MostLikelySeq(const AliView *aliview, ST_ML *st_ml_)
161    : AP_sequence(aliview)
162    , st_ml(st_ml_)
163    , sequence(new ST_base_vector[ST_MAX_SEQ_PART])
164    , up_to_date(false)
165    , color_out(NULL)
166    , color_out_valid_till(NULL)
167{
168}
169
170MostLikelySeq::~MostLikelySeq() {
171    delete [] sequence;
172    free(color_out);
173    free(color_out_valid_till);
174
175    unbind_from_species(true);
176}
177
178static void st_sequence_callback(GBDATA*, MostLikelySeq *seq) {
179    seq->sequence_change();
180}
181
182static void st_sequence_del_callback(GBDATA*, MostLikelySeq *seq) {
183    seq->unbind_from_species(false);
184}
185
186
187GB_ERROR MostLikelySeq::bind_to_species(GBDATA *gb_species) {
188    GB_ERROR error = AP_sequence::bind_to_species(gb_species);
189    if (!error) {
190        GBDATA *gb_seq = get_bound_species_data();
191        st_assert(gb_seq);
192
193        error             = GB_add_callback(gb_seq, GB_CB_CHANGED, makeDatabaseCallback(st_sequence_callback,     this));
194        if (!error) error = GB_add_callback(gb_seq, GB_CB_DELETE,  makeDatabaseCallback(st_sequence_del_callback, this));
195    }
196    return error;
197}
198void MostLikelySeq::unbind_from_species(bool remove_callbacks) {
199    GBDATA *gb_seq = get_bound_species_data();
200
201    if (gb_seq) { 
202        if (remove_callbacks) {
203            GB_remove_callback(gb_seq, GB_CB_CHANGED, makeDatabaseCallback(st_sequence_callback,     this));
204            GB_remove_callback(gb_seq, GB_CB_DELETE,  makeDatabaseCallback(st_sequence_del_callback, this));
205        }
206        AP_sequence::unbind_from_species();
207    }
208}
209
210void MostLikelySeq::sequence_change() {
211    st_ml->clear_all();
212}
213
214AP_sequence *MostLikelySeq::dup() const {
215    return new MostLikelySeq(get_aliview(), st_ml);
216}
217
218void MostLikelySeq::set(const char *) {
219    st_assert(0);                                   // hmm why not perform set_sequence() here ?
220}
221
222void MostLikelySeq::unset() {
223}
224
225void MostLikelySeq::set_sequence() {
226    /*! Transform the sequence from character to vector
227     * for current range [ST_ML::first_pos .. ST_ML::last_pos]
228     */
229
230    GBDATA *gb_data = get_bound_species_data();
231    st_assert(gb_data);
232
233    size_t                source_sequence_len = (size_t)GB_read_string_count(gb_data);
234    const char           *source_sequence     = GB_read_char_pntr(gb_data) + st_ml->get_first_pos();
235    ST_base_vector       *dest                = sequence;
236    const ST_base_vector *freq                = st_ml->get_inv_base_frequencies() + st_ml->get_first_pos();
237
238    size_t range_len = st_ml->get_last_pos() - st_ml->get_first_pos();
239    size_t data_len  = std::min(range_len, source_sequence_len);
240    size_t pos       = 0;
241
242    for (; pos<data_len;  ++pos) dest[pos].setBase(freq[pos], toupper(source_sequence[pos]));
243    for (; pos<range_len; ++pos) dest[pos].setBase(freq[pos], '.');
244
245    up_to_date = true;
246}
247
248AP_FLOAT MostLikelySeq::combine(const AP_sequence *, const AP_sequence *, char *) {
249    st_assert(0);
250    return -1.0;
251}
252
253void MostLikelySeq::partial_match(const AP_sequence *, long *, long *) const {
254    st_assert(0);                                   // function is expected to be unused
255}
256
257void MostLikelySeq::calculate_ancestor(const MostLikelySeq *lefts, double leftl, const MostLikelySeq *rights, double rightl) {
258    st_assert(!up_to_date);
259
260    ST_base_vector        hbv;
261    double                lc   = leftl / st_ml->get_step_size();
262    double                rc   = rightl / st_ml->get_step_size();
263    const ST_base_vector *lb   = lefts->sequence;
264    const ST_base_vector *rb   = rights->sequence;
265    ST_base_vector       *dest = sequence;
266
267    for (size_t pos = st_ml->get_first_pos(); pos < st_ml->get_last_pos(); pos++) {
268        st_assert(lb->lik == 1 && rb->lik == 1);
269
270        int distl = (int) (st_ml->get_rate_at(pos) * lc);
271        int distr = (int) (st_ml->get_rate_at(pos) * rc);
272
273        st_ml->get_matrix_for(distl).transform(*lb, *dest);
274        st_ml->get_matrix_for(distr).transform(*rb, hbv);
275
276        *dest *= hbv;
277        dest->check_overflow();
278
279        st_assert(dest->lik == 1);
280
281        dest++;
282        lb++;
283        rb++;
284    }
285
286    up_to_date = true;
287}
288
289ST_base_vector *MostLikelySeq::tmp_out = 0;
290
291void MostLikelySeq::calc_out(const MostLikelySeq *next_branch, double dist) {
292    // result will be in tmp_out
293
294    ST_base_vector *out   = tmp_out + st_ml->get_first_pos();
295    double          lc    = dist / st_ml->get_step_size();
296    ST_base_vector *lefts = next_branch->sequence;
297
298    for (size_t pos = st_ml->get_first_pos(); pos < st_ml->get_last_pos(); pos++) {
299        int distl = (int) (st_ml->get_rate_at(pos) * lc);
300        st_ml->get_matrix_for(distl).transform(*lefts, *out);
301
302        // correct frequencies
303#if defined(WARN_TODO)
304#warning check if st_ml->get_base_frequency_at(pos).lik is 1 - if so, use vec-mult here
305#endif
306        for (int i = ST_A; i < ST_MAX_BASE; i++) {
307            out->b[i] *= st_ml->get_base_frequency_at(pos).b[i];
308        }
309
310        lefts++;
311        out++;
312    }
313}
314
315void MostLikelySeq::print() {
316    const char *data = GB_read_char_pntr(get_bound_species_data());
317    for (size_t i = 0; i < ST_MAX_SEQ_PART; i++) {
318        printf("POS %3zu  %c     ", i, data[i]);
319        printf("\n");
320    }
321}
322
323AP_FLOAT MostLikelySeq::count_weighted_bases() const {
324    st_assert(0);
325    return -1.0;
326}
327
328// --------------
329//      ST_ML
330
331ST_ML::ST_ML(GBDATA *gb_maini) {
332    memset((char *) this, 0, sizeof(*this));
333    gb_main = gb_maini;
334}
335
336ST_ML::~ST_ML() {
337    delete tree_root;
338    free(alignment_name);
339    if (hash_2_ap_tree) GBS_free_hash(hash_2_ap_tree);
340    delete not_valid;
341    delete [] base_frequencies;
342    delete [] inv_base_frequencies;
343    delete [] rate_matrices;
344    if (!column_stat) {
345        // rates and ttratio have been allocated (see ST_ML::calc_st_ml)
346        delete [] rates;
347        delete [] ttratio;
348    }
349}
350
351
352void ST_ML::create_frequencies() {
353    //! Translate characters to base frequencies
354
355    size_t filtered_length = get_filtered_length();
356    base_frequencies       = new ST_base_vector[filtered_length];
357    inv_base_frequencies   = new ST_base_vector[filtered_length];
358
359    if (!column_stat) {
360        for (size_t i = 0; i < filtered_length; i++) {
361            base_frequencies[i].setTo(1.0);
362            base_frequencies[i].lik = 1.0;
363
364            inv_base_frequencies[i].setTo(1.0);
365            inv_base_frequencies[i].lik = 1.0;
366        }
367    }
368    else {
369        for (size_t i = 0; i < filtered_length; i++) {
370            const ST_FLOAT  NO_FREQ   = 0.01;
371            ST_base_vector& base_freq = base_frequencies[i];
372
373            base_freq.setTo(NO_FREQ);
374
375            static struct {
376                unsigned char c;
377                DNA_Base      b;
378            } toCount[] = {
379                { 'A', ST_A }, { 'a', ST_A },
380                { 'C', ST_C }, { 'c', ST_C },
381                { 'G', ST_G }, { 'g', ST_G },
382                { 'T', ST_T }, { 't', ST_T },
383                { 'U', ST_T }, { 'u', ST_T },
384                { '-', ST_GAP },
385                { 0, ST_UNKNOWN },
386            };
387
388            for (int j = 0; toCount[j].c; ++j) {
389                const float *freq = column_stat->get_frequencies(toCount[j].c);
390                if (freq) base_freq.b[toCount[j].b] += freq[i];
391            }
392
393            ST_FLOAT sum    = base_freq.summarize();
394            ST_FLOAT smooth = sum*0.01;             // smooth by %1 to avoid "crazy values"
395            base_freq.increaseBy(smooth);
396
397            sum += smooth*ST_MAX_BASE; // correct sum
398
399            ST_FLOAT min = base_freq.min_frequency();
400           
401            // @@@ if min == 0.0 all inv_base_frequencies will be set to inf ? correct ?
402            // maybe min should be better calculated after next if-else-clause ?
403
404            if (sum>NO_FREQ) {
405                base_freq.multiplyWith(ST_MAX_BASE/sum);
406            }
407            else {
408                base_freq.setTo(1.0); // columns w/o data
409            }
410
411            base_freq.lik = 1.0;
412           
413            inv_base_frequencies[i].makeInverseOf(base_freq, min);
414            inv_base_frequencies[i].lik = 1.0;
415        }
416    }
417}
418
419void ST_ML::insert_tree_into_hash_rek(AP_tree *node) {
420    node->gr.gc = 0;
421    if (node->is_leaf) {
422        GBS_write_hash(hash_2_ap_tree, node->name, (long) node);
423    }
424    else {
425        insert_tree_into_hash_rek(node->get_leftson());
426        insert_tree_into_hash_rek(node->get_rightson());
427    }
428}
429
430void ST_ML::create_matrices(double max_disti, int nmatrices) {
431    delete [] rate_matrices;
432    rate_matrices = new ST_rate_matrix[nmatrices];
433
434    max_dist          = max_disti;
435    max_rate_matrices = nmatrices;
436    step_size         = max_dist / max_rate_matrices;
437
438    for (int i = 0; i < max_rate_matrices; i++) {
439        rate_matrices[i].set((i + 1) * step_size, 0); // ttratio[i]
440    }
441}
442
443long ST_ML::delete_species(const char *key, long val, void *cd_st_ml) {
444    ST_ML *st_ml = (ST_ML*)cd_st_ml;
445
446    if (GBS_read_hash(st_ml->keep_species_hash, key)) {
447        return val;
448    }
449    else {
450        AP_tree *leaf   = (AP_tree *) val;
451        AP_tree *father = leaf->get_father();
452        leaf->remove();
453        delete father;                              // also deletes 'this'
454
455        return 0;
456    }
457}
458
459inline GB_ERROR tree_size_ok(AP_tree_root *tree_root) {
460    GB_ERROR error = NULL;
461
462    AP_tree *root = tree_root->get_root_node();
463    if (!root || root->is_leaf) {
464        const char *tree_name = tree_root->get_tree_name();
465        error = GBS_global_string("Too few species remained in tree '%s'", tree_name);
466    }
467    return error;
468}
469
470void ST_ML::cleanup() {
471    freenull(alignment_name);
472
473    if (MostLikelySeq::tmp_out) {
474        delete MostLikelySeq::tmp_out;
475        MostLikelySeq::tmp_out = NULL;
476    }
477
478    delete tree_root;
479    tree_root = NULL;
480
481    if (hash_2_ap_tree) {
482        GBS_free_hash(hash_2_ap_tree);
483        hash_2_ap_tree = NULL;
484    }
485
486    is_initialized = false;
487}
488
489GB_ERROR ST_ML::calc_st_ml(const char *tree_name, const char *alignment_namei,
490                           const char *species_names, int marked_only,
491                           ColumnStat *colstat, const WeightedFilter *weighted_filter)
492{
493    // acts as contructor, leaks as hell when called twice
494
495    GB_ERROR error = 0;
496
497    if (is_initialized) cleanup();
498
499    {
500        GB_transaction ta(gb_main);
501        arb_progress progress("Activating column statistic");
502
503        column_stat                = colstat;
504        GB_ERROR column_stat_error = column_stat->calculate(NULL);
505
506        if (column_stat_error) fprintf(stderr, "Column statistic error: %s (using equal rates/tt-ratio for all columns)\n", column_stat_error);
507
508        alignment_name = strdup(alignment_namei);
509        long ali_len   = GBT_get_alignment_len(gb_main, alignment_name);
510
511        if (ali_len<0) {
512            error = GB_await_error();
513        }
514        else if (ali_len<10) {
515            error = "alignment too short";
516        }
517        else {
518            {
519                AliView *aliview = NULL;
520                if (weighted_filter) {
521                    aliview = weighted_filter->create_aliview(alignment_name, error);
522                }
523                else {
524                    AP_filter filter(ali_len);      // unfiltered
525
526                    error = filter.is_invalid();
527                    if (!error) {
528                        AP_weights weights(&filter);
529                        aliview = new AliView(gb_main, filter, weights, alignment_name);
530                    }
531                }
532
533                st_assert(contradicted(aliview, error));
534
535                if (!error) {
536                    MostLikelySeq *seq_templ = new MostLikelySeq(aliview, this); // @@@ error: never freed! (should be freed when freeing tree_root!)
537                    tree_root = new AP_tree_root(aliview, new AP_TreeNodeFactory, seq_templ, false);
538                    // do not delete 'aliview' or 'seq_templ' (they belong to 'tree_root' now)
539                }
540            }
541
542            if (!error) {
543                tree_root->loadFromDB(tree_name);       // tree is not linked!
544
545                if (!tree_root->get_root_node()) { // no tree
546                    error = GBS_global_string("Failed to load tree '%s'", tree_name);
547                }
548                else {
549                    {
550                        size_t species_in_tree = count_species_in_tree();
551                        hash_2_ap_tree         = GBS_create_hash(species_in_tree, GB_MIND_CASE);
552                    }
553
554                    // delete species from tree:
555                    if (species_names) {                    // keep names
556                        tree_root->remove_leafs(AWT_REMOVE_ZOMBIES);
557
558                        error = tree_size_ok(tree_root);
559                        if (!error) {
560                            char *l, *n;
561                            keep_species_hash = GBS_create_hash(GBT_get_species_count(gb_main), GB_MIND_CASE);
562                            for (l = (char *) species_names; l; l = n) {
563                                n = strchr(l, 1);
564                                if (n) *n = 0;
565                                GBS_write_hash(keep_species_hash, l, 1);
566                                if (n) *(n++) = 1;
567                            }
568
569                            insert_tree_into_hash_rek(tree_root->get_root_node());
570                            GBS_hash_do_loop(hash_2_ap_tree, delete_species, this);
571                            GBS_free_hash(keep_species_hash);
572                            keep_species_hash = 0;
573                            GBT_link_tree(tree_root->get_root_node(), gb_main, true, 0, 0);
574                        }
575                    }
576                    else {                                  // keep marked/all
577                        GBT_link_tree(tree_root->get_root_node(), gb_main, true, 0, 0);
578                        tree_root->remove_leafs(marked_only ? AWT_KEEP_MARKED : AWT_REMOVE_ZOMBIES);
579
580                        error = tree_size_ok(tree_root);
581                        if (!error) insert_tree_into_hash_rek(tree_root->get_root_node());
582                    }
583                }
584            }
585
586            if (!error) {
587                // calc frequencies
588
589                progress.subtitle("calculating frequencies");
590
591                size_t filtered_length = get_filtered_length();
592                if (!column_stat_error) {
593                    rates   = column_stat->get_rates();
594                    ttratio = column_stat->get_ttratio();
595                }
596                else {
597                    float *alloc_rates   = new float[filtered_length];
598                    float *alloc_ttratio = new float[filtered_length];
599
600                    for (size_t i = 0; i < filtered_length; i++) {
601                        alloc_rates[i]   = 1.0;
602                        alloc_ttratio[i] = 2.0;
603                    }
604                    rates   = alloc_rates;
605                    ttratio = alloc_ttratio;
606
607                    column_stat = 0;                // mark rates and ttratio as "allocated" (see ST_ML::~ST_ML)
608                }
609                create_frequencies();
610                latest_modification = GB_read_clock(gb_main); // set update time
611                create_matrices(2.0, 1000);
612
613                MostLikelySeq::tmp_out = new ST_base_vector[filtered_length]; // @@@ error: never freed!
614                is_initialized         = true;
615            }
616        }
617
618        if (error) {
619            cleanup();
620            error = ta.close(error);
621        }
622    }
623    return error;
624}
625
626MostLikelySeq *ST_ML::getOrCreate_seq(AP_tree *node) {
627    MostLikelySeq *seq = DOWNCAST(MostLikelySeq*, node->get_seq());
628    if (!seq) {
629        seq = new MostLikelySeq(tree_root->get_aliview(), this); // @@@ why not use dup() ?
630
631        node->set_seq(seq);
632        if (node->is_leaf) {
633            st_assert(node->gb_node);
634            seq->bind_to_species(node->gb_node);
635        }
636    }
637    return seq;
638}
639
640const MostLikelySeq *ST_ML::get_mostlikely_sequence(AP_tree *node) {
641    /*! go through the tree and calculate the ST_base_vector from bottom to top
642     */
643
644    MostLikelySeq *seq = getOrCreate_seq(node);
645    if (!seq->is_up_to_date()) {
646        if (node->is_leaf) {
647            seq->set_sequence();
648        }
649        else {
650            const MostLikelySeq *leftSeq  = get_mostlikely_sequence(node->get_leftson());
651            const MostLikelySeq *rightSeq = get_mostlikely_sequence(node->get_rightson());
652
653            seq->calculate_ancestor(leftSeq, node->leftlen, rightSeq, node->rightlen);
654        }
655    }
656
657    return seq;
658}
659
660void ST_ML::clear_all() {
661    GB_transaction ta(gb_main);
662    undo_tree(tree_root->get_root_node());
663    latest_modification = GB_read_clock(gb_main);
664}
665
666void ST_ML::undo_tree(AP_tree *node) {
667    MostLikelySeq *seq = getOrCreate_seq(node);
668    seq->forget_sequence();
669    if (!node->is_leaf) {
670        undo_tree(node->get_leftson());
671        undo_tree(node->get_rightson());
672    }
673}
674
675#define GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT (ST_MAX_SEQ_PART-1) // workaround bug in get_ml_vectors
676
677MostLikelySeq *ST_ML::get_ml_vectors(const char *species_name, AP_tree *node, size_t start_ali_pos, size_t end_ali_pos) {
678    /* result will be in tmp_out
679     *
680     * assert end_ali_pos - start_ali_pos < ST_MAX_SEQ_PART
681     *
682     * @@@ CAUTION!!! get_ml_vectors has a bug:
683     * it does not calculate the last value, if (end_ali_pos-start_ali_pos+1)==ST_MAX_SEQ_PART
684     * (search for GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT)
685     *
686     * I'm not sure whether this is really a bug! Maybe it's only some misunderstanding about
687     * 'end_ali_pos', because it does not mark the last calculated position, but the position
688     * behind the last calculated position! @@@ Need to rename it!
689     *
690     */
691
692    if (!node) {
693        if (!hash_2_ap_tree) return 0;
694        node = (AP_tree *) GBS_read_hash(hash_2_ap_tree, species_name);
695        if (!node) return 0;
696    }
697
698    st_assert(start_ali_pos<end_ali_pos);
699    st_assert((end_ali_pos - start_ali_pos + 1) <= ST_MAX_SEQ_PART);
700
701    MostLikelySeq *seq = getOrCreate_seq(node);
702
703    if (start_ali_pos != first_pos || end_ali_pos > last_pos) {
704        undo_tree(tree_root->get_root_node());      // undo everything
705        first_pos = start_ali_pos;
706        last_pos  = end_ali_pos;
707    }
708
709    AP_tree *pntr;
710    for (pntr = node->get_father(); pntr; pntr = pntr->get_father()) {
711        MostLikelySeq *sequ = getOrCreate_seq(pntr);
712        if (sequ) sequ->forget_sequence();
713    }
714
715    node->set_root();
716
717    const MostLikelySeq *seq_of_brother = get_mostlikely_sequence(node->get_brother());
718
719    seq->calc_out(seq_of_brother, node->father->leftlen + node->father->rightlen);
720    return seq;
721}
722
723bool ST_ML::update_ml_likelihood(char *result[4], int& latest_update, const char *species_name, AP_tree *node) {
724    /*! calculates values for 'Detailed column statistics' in ARB_EDIT4
725     * @return true if calculated with sucess
726     *
727     * @param result if result[0] is NULL, memory will be allocated and assigned to result[0 .. 3].
728     *        You should NOT allocate result yourself, but you can reuse it for multiple calls.
729     * @param latest_update has to contain and will be set to the latest statistic modification time
730     *        (0 is a good start value)
731     * @param species_name name of the species (for which the column statistic shall be calculated)
732     * @param node of the current tree (for which the column statistic shall be calculated)
733     *
734     * Note: either 'species_name' or 'node' needs to be specified, but NOT BOTH
735     */
736
737    st_assert(contradicted(species_name, node));
738
739    if (latest_update < latest_modification) {
740        if (!node) {                                // if node isn't given search it using species name
741            st_assert(hash_2_ap_tree);              // ST_ML was not prepared for search-by-name
742            if (hash_2_ap_tree) node = (AP_tree *) GBS_read_hash(hash_2_ap_tree, species_name);
743            if (!node) return false;
744        }
745
746        DNA_Base adb[4];
747        int      i;
748
749        size_t ali_len = get_alignment_length();
750        st_assert(get_filtered_length() == ali_len); // assume column stat was calculated w/o filters
751
752        if (!result[0]) {                           // allocate Array-elements for result
753            for (i = 0; i < 4; i++) {
754                result[i] = (char *) GB_calloc(1, ali_len + 1); // [0 .. alignment_len[ + zerobyte
755            }
756        }
757
758        for (i = 0; i < 4; i++) {
759            adb[i] = dna_table.char_to_enum("ACGU"[i]);
760        }
761
762        for (size_t seq_start = 0; seq_start < ali_len; seq_start += GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT) {
763            size_t seq_end = std::min(ali_len, seq_start+GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT);
764            get_ml_vectors(0, node, seq_start, seq_end);
765        }
766
767        MostLikelySeq *seq = getOrCreate_seq(node);
768
769        for (size_t pos = 0; pos < ali_len; pos++) {
770            ST_base_vector& vec = seq->tmp_out[pos];
771            double          sum = vec.summarize();
772
773            if (sum == 0) {
774                for (i = 0; i < 4; i++) {
775                    result[i][pos] = -1;
776                }
777            }
778            else {
779                double div = 100.0 / sum;
780
781                for (i = 0; i < 4; i++) {
782                    result[i][pos] = char ((vec.b[adb[i]] * div) + 0.5);
783                }
784            }
785        }
786
787        latest_update = latest_modification;
788    }
789    return true;
790}
791
792ST_ML_Color *ST_ML::get_color_string(const char *species_name, AP_tree *node, size_t start_ali_pos, size_t end_ali_pos) {
793    /*! (Re-)Calculates the color string of a given node for sequence positions [start_ali_pos .. end_ali_pos[
794     */
795   
796    if (!node) {
797        // if node isn't given, search it using species name:
798        if (!hash_2_ap_tree) return 0;
799        node = (AP_tree *) GBS_read_hash(hash_2_ap_tree, species_name);
800        if (!node) return 0;
801    }
802
803    // align start_ali_pos/end_ali_pos to previous/next pos divisible by ST_BUCKET_SIZE:
804    start_ali_pos &= ~(ST_BUCKET_SIZE - 1);
805    end_ali_pos    = (end_ali_pos & ~(ST_BUCKET_SIZE - 1)) + ST_BUCKET_SIZE - 1;
806
807    size_t ali_len = get_alignment_length();
808    if (end_ali_pos > ali_len) {
809        end_ali_pos = ali_len;
810    }
811
812    double         val;
813    MostLikelySeq *seq = getOrCreate_seq(node);
814    size_t         pos;
815
816    if (!seq->color_out) {                          // allocate mem for color_out if we not already have it
817        seq->color_out = (ST_ML_Color *) GB_calloc(sizeof(ST_ML_Color), ali_len);
818        seq->color_out_valid_till = (int *) GB_calloc(sizeof(int), (ali_len >> LD_BUCKET_SIZE) + ST_BUCKET_SIZE);
819    }
820    // search for first out-dated position:
821    for (pos = start_ali_pos; pos <= end_ali_pos; pos += ST_BUCKET_SIZE) {
822        if (seq->color_out_valid_till[pos >> LD_BUCKET_SIZE] < latest_modification) break;
823    }
824    if (pos > end_ali_pos) {                        // all positions are up-to-date
825        return seq->color_out;                      // => return existing result
826    }
827
828    for (size_t start = start_ali_pos; start <= end_ali_pos; start += GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT) {
829        int end = std::min(end_ali_pos, start+GET_ML_VECTORS_BUG_WORKAROUND_INCREMENT);
830        get_ml_vectors(0, node, start, end);        // calculates tmp_out (see below)
831    }
832
833    const char *source_sequence = 0;
834    GBDATA *gb_data = seq->get_bound_species_data();
835    if (gb_data) source_sequence = GB_read_char_pntr(gb_data);
836
837    // create color string in 'outs':
838    ST_ML_Color    *outs   = seq->color_out  + start_ali_pos;
839    ST_base_vector *vec    = seq->tmp_out    + start_ali_pos; // tmp_out was calculated by get_ml_vectors above
840    const char     *source = source_sequence + start_ali_pos;
841
842    for (pos = start_ali_pos; pos <= end_ali_pos; pos++) {
843        {
844            DNA_Base b = dna_table.char_to_enum(*source); // convert seq-character to enum DNA_Base
845            *outs      = 0;
846
847            if (b != ST_UNKNOWN) {
848                ST_FLOAT max = vec->max_frequency();
849                val          = max / (0.0001 + vec->b[b]); // calc ratio of max/real base-char
850
851                if (val > 1.0) {                    // if real base-char is NOT the max-likely base-char
852                    *outs = (int) (log(val));       // => insert color
853                }
854            }
855        }
856        outs++;
857        vec++;
858        source++;
859
860        seq->color_out_valid_till[pos >> LD_BUCKET_SIZE] = latest_modification;
861    }
862    return seq->color_out;
863}
864
865void ST_ML::create_column_statistic(AW_root *awr, const char *awarname, AW_awar *awar_default_alignment) {
866    column_stat = new ColumnStat(get_gb_main(), awr, awarname, awar_default_alignment);
867}
868
869const GBT_TREE *ST_ML::get_gbt_tree() const {
870    return tree_root->get_root_node();
871}
872
873size_t ST_ML::count_species_in_tree() const {
874    ARB_tree_info info;
875    tree_root->get_root_node()->calcTreeInfo(info);
876    return info.leafs;
877}
878
879AP_tree *ST_ML::find_node_by_name(const char *species_name) {
880    AP_tree *node = NULL;
881    if (hash_2_ap_tree) node = (AP_tree *)GBS_read_hash(hash_2_ap_tree, species_name);
882    return node;
883}
884
885const AP_filter *ST_ML::get_filter() const { return tree_root->get_filter(); }
886size_t ST_ML::get_filtered_length() const { return get_filter()->get_filtered_length(); }
887size_t ST_ML::get_alignment_length() const { return get_filter()->get_length(); }
888
Note: See TracBrowser for help on using the repository browser.