-
Notifications
You must be signed in to change notification settings - Fork 4
/
stepwise_addition_pro.cpp
2455 lines (1730 loc) · 75.5 KB
/
stepwise_addition_pro.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2009-2012 Simon A. Berger
*
* This file is part of papara.
*
* papara is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* papara is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with papara. If not, see <http://www.gnu.org/licenses/>.
*/
// #include "pch.h"
// someone down the line tries to sabotage us by including a windows header,
// which will clutter the whole namespace with macros. I don't know who it is,
// but disable_shit.h takes care of restricting the damage...
#include "ivymike/disable_shit.h"
#include <cctype>
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
#include <fstream>
#include <iterator>
#include <deque>
#include <thread>
#include <iomanip>
#define BOOST_UBLAS_NDEBUG
#include <boost/bind.hpp>
#include <boost/dynamic_bitset.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include "pairwise_seq_distance.h"
#include "stepwise_align.h"
#include "raxml_interface.h"
#include "sequence_model.h"
#include "pvec.h"
#include "ivymike/time.h"
#include "ivymike/getopt.h"
#include "ivymike/smart_ptr.h"
#include "ivymike/tree_parser.h"
#include "ivymike/tdmatrix.h"
#include "ivymike/algorithm.h"
#include "ivymike/tree_traversal_utils.h"
#include "ivymike/tree_split_utils.h"
#include "ivymike/flat_map.h"
#include "ivymike/fasta.h"
#include "ivymike/thread.h"
namespace tree_parser = ivy_mike::tree_parser_ms;
using ivy_mike::tree_parser_ms::ln_pool;
using ivy_mike::tree_parser_ms::lnode;
using sequence_model::tag_aa;
using sequence_model::tag_dna;
using ivy_mike::apply_lnode;
using ivy_mike::apply_lnode;
using ivy_mike::back_insert_ifer;
using ivy_mike::iterate_lnode;
using ivy_mike::rooted_bifurcation;
using ivy_mike::back_insert_ifer;
using ivy_mike::iterate_lnode;
using ivy_mike::rooted_bifurcation;
using ivy_mike::scoring_matrix;
namespace ublas = boost::numeric::ublas;
typedef std::vector<unsigned char> sequence;
namespace {
// double g_delta = log(0.1);
// double g_epsilon = log(0.5);
}
class log_odds {
public:
log_odds( double bg_prob ) : bg_prob_(bg_prob) {}
inline double operator()( double p ) {
return std::max( -100.0, log( p / bg_prob_ ));
}
private:
const double bg_prob_;
};
static std::vector<uint8_t> gapstream_to_alignment( const std::vector<uint8_t> &gaps, const std::vector<uint8_t> &raw, uint8_t gap_char, bool upper ) {
std::vector<uint8_t> out;
std::vector<uint8_t>::const_reverse_iterator rit = raw.rbegin();
// 'gap indicator': if upper is set, insert gap into reference (=if gaps[i] == 2).
const uint8_t gap_ind = upper ? 2 : 1;
for ( std::vector<uint8_t>::const_iterator git = gaps.begin(); git != gaps.end(); ++git ) {
if ( *git == gap_ind ) {
out.push_back(gap_char);
} else {
if( rit != raw.rend() ) {
out.push_back(*rit);
++rit;
} else {
out.push_back( 'X' );
}
}
}
if( rit != raw.rend() ) {
std::cerr << "too short tb: " << raw.rend() - rit << " upper: " << upper << "\n";
}
std::reverse(out.begin(), out.end());
return out;
}
class log_odds_viterbi {
typedef ublas::matrix<double> dmat;
typedef std::vector<double> dsvec;
// lof_t: log-odds-float = float type good enough to hold/calculate log-odds scores.
// 32bit float should be enough
typedef float lof_t;
typedef ublas::matrix<lof_t> lomat;
typedef std::vector<lof_t> losvec;
public:
log_odds_viterbi( const dmat &state, const dmat &gap, boost::array<double,4> state_freq )
:
ref_state_prob_(state), ref_gap_prob_(gap), ref_len_(state.size2()),
state_freq_(state_freq),
neg_inf_( -std::numeric_limits<lof_t>::infinity() ),
m_(state.size2() + 1),
d_(state.size2() + 1),
i_(state.size2() + 1),
max_matrix_height_(0),
delta_(lof_t(log(0.01))),
epsilon_(lof_t(log(0.1)))
{
ref_gap_prob_log_ = ref_gap_prob_;
{
auto &d = ref_gap_prob_log_.data();
//std::transform( d.begin(), d.end(), d.begin(), log );
std::transform( d.begin(), d.end(), d.begin(), [](double v){ return log(v); } );
}
// for( auto it1 = ref_gap_prob_.begin1(); it1 != ref_gap_prob_.end1(); ++it1 ) {
// std::copy( it1.begin(), it1.end(), std::ostream_iterator<float>( std::cout, " " ));
// std::cout << "\n";
//
// }
precalc_log_odds();
}
void setup( size_t qlen ) {
assert( ref_gap_prob_.size2() == ref_len_ );
// init first rows
std::fill( m_.begin(), m_.end(), 0.0 );
//std::fill( d_.begin(), d_.end(), 0.0 );
{
int i = 0; // TODO: still wearing my STL hat. Not really sure if std::generate + lambda is better than a for loop...
std::generate( d_.begin(), d_.end(), [&]() { return delta_ + (i++) * epsilon_; });
m_.assign( d_.begin(), d_.end() );
}
std::fill( i_.begin(), i_.end(), neg_inf_ );
std::fill( traceback_.begin1().begin(), traceback_.begin1().end(), tb_d_to_d | tb_m_to_d );
traceback_(0, 0) = tb_m_to_m;
// init first columns
m_[0] = 0.0;
d_[0] = neg_inf_;
i_[0] = delta_;
}
void precalc_log_odds() {
ref_state_lo_.resize( ref_state_prob_.size1(), ref_state_prob_.size2() );
for( size_t i = 0; i < 4; ++i ) {
const ublas::matrix_row<dmat> prow( ref_state_prob_, i );
ublas::matrix_row<lomat> lorow( ref_state_lo_, i );
std::transform( prow.begin(), prow.end(), lorow.begin(), log_odds(state_freq_[i]));
}
// {
// odds odds_ngap( 1 - g_gap_freq );
// odds odds_gap( g_gap_freq );
//
// ref_ngap_odds_.resize(ref_gap_prob_.size());
// ref_gap_odds_.resize(ref_gap_prob_.size());
// for( size_t i = 0; i < ref_gap_prob_.size(); ++i ) {
// ref_ngap_odds_[i] = odds_ngap(1 - ref_gap_prob_[i]);
// ref_gap_odds_[i] = odds_gap( ref_gap_prob_[i] );
// }
// }
}
template<typename T, typename T2>
static inline std::pair<T,T2> max2( const T &a, const T &b, const T2 &a2, const T2 &b2 ) {
if( a > b ) {
return std::make_pair( a, a2 );
} else {
return std::make_pair( b, b2 );
}
}
template<typename T, typename T2>
static inline std::pair<T,T2> max3( const T &a, const T &b, const T &c, const T2 &a2, const T2 &b2, const T2 &c2, bool dump = false ) {
//return std::max( a, std::max( b, c ));
if( dump ) {
std::cout << "(" << a << " " << b << " " << c << ")";
}
if( a > b ) {
return max2( a, c, a2, c2 );
} else {
return max2( b, c, b2, c2 );
}
}
double align( const std::vector<uint8_t> &qs ) {
const size_t qlen = qs.size();
traceback_.resize(qlen + 1, m_.size(), false);
setup( qlen );
//dmat ref_state_trans = trans(ref_state_prob_);
assert( m_.size() == ref_len_ + 1 );
best_score_ = neg_inf_;
best_i_ = -1;
best_j_ = -1;
short last_state = 0;
for( size_t i = 1; i < qlen + 1; ++i ) {
const int b = qs[i-1];
// std::cout << "b: " << b << "\n";
//const double b_freq = state_freq_.at(b);
//const ublas::matrix_column<dmat> b_state( ref_state_prob_, b );
const ublas::matrix_row<lomat> b_state_lo( ref_state_lo_, b );
// const ublas::matrix_column<dmat> ngap_prob( ref_gap_prob_, 0 );
// const ublas::matrix_column<dmat> gap_prob( ref_gap_prob_, 1 );
i_[0] = delta_ + (i-1) * epsilon_;
m_[0] = i_[0];
lof_t diag_m = m_[0];
lof_t diag_d = d_[0];
lof_t diag_i = i_[0];
losvec::iterator m0 = m_.begin() + 1;
losvec::iterator d0 = d_.begin() + 1;
losvec::iterator i0 = i_.begin() + 1;
losvec::iterator m1 = m_.begin();
losvec::iterator d1 = d_.begin();
losvec::iterator i1 = i_.begin();
ublas::matrix_row<lomat>::const_iterator bsl = b_state_lo.begin();
ublas::matrix_row<ublas::matrix<short>> traceback_row( traceback_, i );
auto traceback_iter = traceback_row.begin();
*traceback_iter = tb_i_to_i | tb_m_to_i;
++traceback_iter;
// losvec::iterator rg = ref_gap_odds_.begin();
// losvec::iterator rng = ref_ngap_odds_.begin();
auto gap_prob_log = ref_gap_prob_log_.begin2();
const losvec::iterator m_end = m_.end();
for( size_t j = 1; m0 != m_end; m1 = m0++, d1 = d0++, i1 = i0++, ++bsl, ++gap_prob_log, ++traceback_iter, ++j ) {
//ublas::matrix_row<dmat> a_state(ref_state_prob_, j-1 );
//ublas::matrix_row<dmat> a_gap(ref_gap_prob_, j-1 );
//double match_log_odds = log( b_state[j-1] / b_freq );
//lof_t match_log_odds = b_state_lo[j-1];
const lof_t match_log_odds = *bsl;
//lof_t gap_log_odds = ref_gap_lo_[j-1];
//lof_t ngap_log_odds = ref_ngap_lo_[j-1];
// const lof_t gap_odds = *rg;
// const lof_t ngap_odds = *rng;
lof_t p_ngap_log = *gap_prob_log;
lof_t p_gap_log = *(gap_prob_log.begin() + 1);
// p_gap = std::max( p_gap, 0.01f );
// lof_t m_log_sum = log(
// exp(diag_m) * p_ngap
// + exp(diag_d) * p_gap
// + exp(diag_i)
// );
// std::cout << "logp: " << log(p_gap) << " ";
// std::cout << "\t";
auto m_log_max = max3<float>(
diag_m + p_ngap_log,
diag_d,
diag_i,
tb_m_to_m,
tb_m_to_d,
tb_m_to_i,
!true
);
diag_m = *m0;
*m0 = m_log_max.first + match_log_odds;
*traceback_iter = m_log_max.second; // do not or, because it's the first value tritten to the tb matrix
// std::cout << *m0 << " ";
#if 0
std::cout << i << " " << j << " " << m_(i,j) << " : " << m_(i-1, j-1) + ngap_log_odds
<< " " << d_(i-1, j-1) + gap_log_odds << " " << i_(i-1, j-1) + gap_log_odds << " " << match_log_odds << " " << gap_log_odds << " " << ngap_log_odds << " max: " << m_max << "\n";
#endif
diag_i = *i0;
// the two 'diags' have already been updated, so they're both actually containing the current 'aboves',
// which is exactly what we need to calculate the new i
// lof_t i_log_sum = log(
// exp(diag_m) /** delta_*/
// + exp(diag_i) /** epsilon_*/
// );
auto i_log_max = max3<float>(
diag_m + delta_,
diag_i + epsilon_,
diag_d + delta_,
tb_i_to_m,
tb_i_to_i,
tb_i_to_d
);
*i0 = i_log_max.first;
*traceback_iter |= i_log_max.second;
#if 1
// lof_t d_log_sum = log(
// exp(*m1) /** delta_*/
// + exp(*d1) /** epsilon_*/
// );
auto d_log_max = max3<float>(
*m1 + delta_,
*d1 + epsilon_,
*i1 + delta_,
tb_d_to_m,
tb_d_to_d,
tb_d_to_i
);
#else
lof_t d_log_sum = *m1 + math_approx::log(
delta_
+ math_approx::exp(*d1 - *m1) * epsilon_
);
#endif
diag_d = *d0;
*d0 = d_log_max.first + p_gap_log;
*traceback_iter |= d_log_max.second;
last_state = m_log_max.second;
// if( m0 == m_end - 1 || i == qlen ) {
// if( *m0 > best_score_ ) {
// best_score_ = *m0;
// best_i_ = i;
// best_j_ = j;
// best_state_ = m_log_max.second;
// }
//
// }
//end_state_ = max3( *m0, *i0, *d0, tb_m_to_m, tb_m_to_i, tb_m_to_d );
//std::cout << end_state_.first << " ";
// std::cout << match_log_odds << " ";
//lof_t old_m = m_[j];
}
// std::cout << "\n";
}
//return m_.back();
best_score_ = m_.back();
best_i_ = qlen;
best_j_ = m_.size() - 1;
best_state_ = last_state;
return best_score_;
}
std::vector<uint8_t> traceback() {
std::cout << "end state: " << std::hex << int(end_state_.second) << std::dec << "\n";
int ia = traceback_.size1() - 1;
int ib = traceback_.size2() - 1;
int max_a = best_i_;
int max_b = best_j_;
assert( ia == max_a || ib == max_b );
// for( auto it1 = traceback_.begin1(); it1 != traceback_.end1(); ++it1 ) {
// std::cout << std::hex;
// std::copy( it1.begin(), it1.end(), std::ostream_iterator<int>( std::cout, " " ));
// std::cout << std::dec << "\n";
//
// }
bool in_l = false;
bool in_u = false;
std::vector<uint8_t> tb_out;
tb_out.reserve( ia + ib );
while( ia > max_a ) {
tb_out.push_back(2);
--ia;
}
while( ib > max_b ) {
tb_out.push_back(1);
--ib;
}
{
char tb_end = best_state_;
in_u = (tb_end & tb_m_to_i) != 0;
in_l = (tb_end & tb_m_to_d) != 0;
assert( !in_u || !in_l );
}
while( ia > 0 && ib > 0 ) {
auto tb = traceback_( ia, ib );
// std::cout << std::hex;
// std::cout << "tb: " << int(tb) << "\n";
// std::cout << std::dec;
if( !in_l && !in_u ) {
in_l = (tb & tb_m_to_d) != 0;
in_u = (tb & tb_m_to_i) != 0;
// if( !in_l && !in_u ) {
//
//
// }
tb_out.push_back(0);
--ia;
--ib;
} else if( in_u ) {
tb_out.push_back(2);
--ia;
in_u = (tb & tb_i_to_i) != 0;
in_l = (tb & tb_i_to_d) != 0;
} else if( in_l ) {
tb_out.push_back(1);
--ib;
in_l = (tb & tb_d_to_d) != 0;
in_u = (tb & tb_d_to_i) != 0;
}
}
while( ia > 0 ) {
tb_out.push_back(2);
--ia;
}
while( ib > 0 ) {
tb_out.push_back(1);
--ib;
}
//return std::vector<char>( tb_out.rbegin(), tb_out.rend() );
return tb_out;
}
private:
ublas::matrix<short> traceback_;
static const short tb_i_to_i;// = 0x1;
static const short tb_i_to_m;// = 0x2;
static const short tb_d_to_d;// = 0x4;
static const short tb_d_to_m;// = 0x8;
static const short tb_m_to_m;// = 0x10;
static const short tb_m_to_i;// = 0x20;
static const short tb_m_to_d;// = 0x40;
static const short tb_i_to_d;// = 0x80;
static const short tb_d_to_i;// = 0x100;
dmat ref_state_prob_;
dmat ref_gap_prob_;
dmat ref_gap_prob_log_;
lomat ref_state_lo_;
// losvec ref_gap_odds_;
// losvec ref_ngap_odds_;
const size_t ref_len_;
const boost::array<double,4> state_freq_;
const float neg_inf_;
losvec m_;
losvec d_;
losvec i_;
std::pair<lof_t, char> end_state_;
size_t max_matrix_height_;
const lof_t delta_;// = log(0.1);
const lof_t epsilon_;// = log(0.5);
// size_t max_col_;
// size_t max_row_;
double best_score_;
size_t best_i_;
size_t best_j_;
short best_state_;
};
const short log_odds_viterbi::tb_i_to_i = 0x1;
const short log_odds_viterbi::tb_i_to_m = 0x2;
const short log_odds_viterbi::tb_d_to_d = 0x4;
const short log_odds_viterbi::tb_d_to_m = 0x8;
const short log_odds_viterbi::tb_m_to_m = 0x10;
const short log_odds_viterbi::tb_m_to_i = 0x20;
const short log_odds_viterbi::tb_m_to_d = 0x40;
const short log_odds_viterbi::tb_i_to_d = 0x80;
const short log_odds_viterbi::tb_d_to_i = 0x100;
namespace {
template<class pvec_t,typename seq_tag>
class my_adata_gen : public ivy_mike::tree_parser_ms::adata {
public:
// int m_ct;
my_adata_gen() {
// std::cout << "my_adata\n";
}
virtual ~my_adata_gen() {
// std::cout << "~my_adata\n";
}
void init_sequence( const sequence &seq ) {
assert( seq_.empty() );
seq_.assign( seq.begin(), seq.end() );
}
void update_pvec() {
pvec_.init2( seq_, sequence_model::model<seq_tag>() );
}
pvec_t &pvec() {
return pvec_;
}
const ublas::matrix<float> &calculate_anc_gap_probs() {
const auto &pgap = pvec_.get_pgap();
anc_probs_.resize(pgap.size1(), pgap.size2());
auto oit = anc_probs_.begin2();
for( auto iit = pgap.begin2(); iit != pgap.end2(); ++iit, ++oit ) {
double v1 = *iit * (1-pvec_pgap::pgap_model->gap_freq());
double v2 = *(iit.begin() + 1) * pvec_pgap::pgap_model->gap_freq();
*oit = v1 / (v1 + v2);
*(oit.begin() + 1) = v2 / (v1 + v2);
}
return anc_probs_;
// for( it =
}
private:
pvec_t pvec_;
ublas::matrix<float> anc_probs_;
sequence seq_;
};
// inline void newview_parsimony( std::vector<parsimony_state> &p, const std::vector<parsimony_state> &c1, const std::vector<parsimony_state> &c2 ) {
//
// }
// inline std::ostream &operator<<( std::ostream &os, const my_adata &rb ) {
//
// os << "my_adata: " << rb.m_ct;
// }
template<class ndata_t>
class my_fact : public ivy_mike::tree_parser_ms::node_data_factory {
virtual ndata_t *alloc_adata() {
return new ndata_t;
}
};
typedef sequence_model::model<tag_dna> seq_model;
typedef my_adata_gen<pvec_pgap,tag_dna> my_adata;
}
template<typename iiter>
bool is_sorted( iiter start, iiter end ) {
if( std::distance(start,end) < 2 ) {
return true;
}
while( start != end - 1) {
if( start > start++ ) {
return false;
}
}
return true;
}
class tree_deconstructor {
public:
tree_deconstructor( lnode *t, const std::vector<std::string> &addition_order ) {
remove_order_.assign( addition_order.rbegin(), addition_order.rend() );
ivy_mike::flat_map<std::string,size_t> tip_name_map;
std::vector<lnode*> edges;
std::vector<boost::dynamic_bitset<> > splits;
std::vector<lnode *> sorted_tips;
ivy_mike::get_all_splits_by_node( t, edges, splits, sorted_tips );
for( size_t i = 0; i < sorted_tips.size(); ++i ) {
tip_name_map.put_fast( sorted_tips[i]->m_data->tipName, i );
}
tip_name_map.sort();
assert( remove_order_.size() > 2 );
for( size_t i = 0; i < remove_order_.size(); ++i ) {
auto name = remove_order_.at(i);
const size_t * idx_ptr = tip_name_map.get(name);
assert( idx_ptr != nullptr );
lnode *tip = sorted_tips.at(*idx_ptr);
if( !tip->m_data->isTip ) {
tip = tip->back;
}
assert( tip->m_data->isTip );
lnode *remove_node = tip->back;
// ivy_mike::tree_parser_ms::prune_with_rollback pwr(remove_node);
// pwr_stack_.push_back( std::move(pwr));
pwr_stack_.emplace_back(remove_node);
}
}
~tree_deconstructor() {
while( !pwr_stack_.empty() ) {
pwr_stack_.pop_back();
}
}
lnode *get_save_node() const {
// return node from the current tree
return pwr_stack_.back().get_save_node();
}
void pop() {
assert( !pwr_stack_.empty() );
pwr_stack_.pop_back();
}
bool empty() const {
return pwr_stack_.empty();
}
size_t size() const {
return pwr_stack_.size();
}
private:
std::vector<ivy_mike::tree_parser_ms::prune_with_rollback> pwr_stack_;
std::vector<std::string> remove_order_;
};
class addition_order {
public:
addition_order( const scoring_matrix &sm, const std::vector<sequence> &mapped_seqs )
: used_seqs_( mapped_seqs.size() )
{
const size_t num_seqs = mapped_seqs.size();
std::cout << "size: " << num_seqs << "\n";
pw_dist_.init_size(num_seqs, num_seqs);
ivy_mike::tdmatrix<int> out_scores( mapped_seqs.size(), mapped_seqs.size() );
const size_t num_ali_threads = 4;
pairwise_seq_distance(mapped_seqs, out_scores, sm, -5, -2, num_ali_threads, 64);
init_pw_dist_from_msa_score_matrix(out_scores);
}
size_t find_next_candidate() {
if( pw_dist_.size() == 0 ) {
throw std::runtime_error( "find_next_candidate called with empty pw-dist matrix");
}
if( dist_acc_.empty() ) {
//
// create initial distance accumulator if it does not exist.
//
size_t f = used_seqs_.find_first();
std::vector<float> dist_sum;
while( f != used_seqs_.npos ) {
ivy_mike::odmatrix<float> slice = pw_dist_[f];
if( dist_sum.empty() ) {
dist_sum.assign( slice.begin(), slice.end() );
} else {
std::transform( dist_sum.begin(), dist_sum.end(), slice.begin(), dist_sum.begin(), std::plus<float>() );
}
f = used_seqs_.find_next(f);
}
dist_acc_.swap( dist_sum );
}
float min_dist = 1e8;
size_t min_element = size_t(-1);
for( size_t i = 0; i < dist_acc_.size(); i++ ) {
if( !used_seqs_[i] && dist_acc_[i] < min_dist ) {
min_dist = dist_acc_[i];
min_element = i;
}
}
assert( min_element != size_t(-1) || used_seqs_.count() == used_seqs_.size() );
if( min_element != size_t(-1) ) {
// update accumulator
assert( min_element != size_t(-1));
ivy_mike::odmatrix<float> slice = pw_dist_[min_element];
assert( slice.size() == dist_acc_.size() );
// element-wise calculate dist_acc_ = dist_acc_ + slice;
std::transform( dist_acc_.begin(), dist_acc_.end(), slice.begin(), dist_acc_.begin(), std::plus<float>() );
used_seqs_[min_element] = true;
}
return min_element;
}
std::pair<size_t,size_t> first_pair() const {
return first_pair_;
}
private:
void init_pw_dist_from_msa_score_matrix( ivy_mike::tdmatrix<int> &out_scores ) {
size_t li = -1, lj = -1;
float lowest_dist = 1e8;
int min = *(std::min_element( out_scores.begin(), out_scores.end() ));
int max = *(std::max_element( out_scores.begin(), out_scores.end() ));
for( size_t i = 0; i < out_scores.size(); i++ ) {
for( size_t j = 0; j < out_scores[i].size(); j++ ) {
// three modes for normalizing: min, max and mean
//const float norm = min( ma[i][i], ma[j][j] );
// const float norm = max( ma[i][i], ma[j][j] );
const float norm = (out_scores[i][j] - min) / float(max-min);
const float dist = 1.0 - norm;
pw_dist_[i][j] = dist;
if( i != j && dist < lowest_dist ) {
lowest_dist = dist;
li = i;
lj = j;
}
}
}
used_seqs_[li] = used_seqs_[lj] = true;
first_pair_ = std::make_pair( li, lj );
}
ivy_mike::tdmatrix<float> pw_dist_;
std::vector<float> dist_acc_;
boost::dynamic_bitset<> used_seqs_;
std::pair<size_t,size_t> first_pair_;
// scoring_matrix scoring_matrix_;
};
template<typename K, typename V>
class flat_map {
public:
flat_map() : sorted_(true) {}
void sort() {
if( !sorted_ ) {
std::sort( pairs_.begin(), pairs_.end() );
sorted_ = true;
}
}
void put_fast( const K &key, const V &value ) {
pairs_.emplace_back( key, value );
sorted_ = false;
}
void put_fast( const K &key, V &&value ) {
pairs_.emplace_back( key, value );
sorted_ = false;
}
template<typename... Args>
void emplace_fast( const K &key, Args&&... args) {
pairs_.emplace_back( key, args... );
sorted_ = false;
}
void put( const K &key, const V &value ) {
if( !sorted_ ) {
throw std::runtime_error( "flat_map::put on unsorted map" );
}
ipair p{key, value};
auto lb = std::lower_bound( pairs_.begin(), pairs_.end(), p );
pairs_.insert(lb, std::move(p));
}
const V * get( const K &key ) const {
if( !sorted_ ) {
throw std::runtime_error( "flat_map::get on unsorted map" );
}
auto lb = std::lower_bound( pairs_.begin(), pairs_.end(), ipair(key, V()) );
if( lb == pairs_.end() || lb->key_ != key ) {
return nullptr;
} else {
return &lb->value_;
}
}
void reserve( size_t s ) {
pairs_.reserve(s);
}
private:
struct ipair {
K key_;
V value_;
ipair( const K &key, const V &value ) : key_(key), value_(value) {}
inline bool operator<( const ipair &other ) const {
return key_ < other.key_;
}
};
std::vector<ipair> pairs_;
bool sorted_;