source: tags/old_import_filter/STAT/ST_ml.cxx

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