-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSequences3.1.h
More file actions
4404 lines (3731 loc) · 132 KB
/
CSequences3.1.h
File metadata and controls
4404 lines (3731 loc) · 132 KB
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
/***************************************************************************************************
* The PolyMoSim project is distributed under the following license:
*
* Copyright (c) 2006-2025, Christoph Mayer, Leibniz Institute for the Analysis of Biodiversity Change,
* Bonn, Germany
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code (complete or in parts) must retain
* the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or any use of this software
* e.g. in publications must display the following acknowledgement:
* This product includes software developed by Christoph Mayer, Forschungsmuseum
* Alexander Koenig, Bonn, Germany.
* 4. Neither the name of the organization nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY CHRISTOPH MAYER ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHTHOLDER OR ITS ORGANISATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* IMPORTANT (needs to be included, if code is redistributed):
* Please not that this license is not compatible with the GNU Public License (GPL)
* due to paragraph 3 in the copyright. It is not allowed under any
* circumstances to use the code of this software in projects distributed under the GPL.
* Furthermore, it is not allowed to redistribute the code in projects which are
* distributed under a license which is incompatible with one of the 4 paragraphs above.
*
* This project makes use of code coming from other projects. What follows is a complete
* list of files which make use of external code. Please refer to the copyright within
* these files.
*
* Files in tclap foler: Copyright (c) 2003 Michael E. Smoot
* See copyright in tclap/COPYRIGHT file for details.
* discrete_gamma.c: Copyright 1993-2004 by Ziheng Yang.
* See copyright in this file for details.
* CRandom.h: Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura
* See copyright in this file for details.
***************************************************************************************************/
// TODO: Check all new whether they have a corresponding delete
// IMPORTANT:
// Some functions only work if the short names are unique. These are the sequence
// names before the first space or the full name if the name contains no spaces.
// Reading and writing work even if the short names are not unique. Accessing
// sequences by the short name does not work.
// Double check results when using this for library for sequences of different
// length. Only very basic tasks are allowed!
//////////////////////////////////////////////////////////////////////
// CSequences.h: interface for the CSequences class.
//
//////////////////////////////////////////////////////////////////////
// Next general goal: Use faststring::size_type instead of unsigned int for array sizes.
#ifndef CSEQUENCES3_H
#define CSEQUENCES3_H
#include <vector>
#include <map>
#include "faststring3.h"
#include "fast-realloc-vector.h"
#include "CSplit2.h"
#include "CSequence_Mol3.1.h"
#include <cassert>
#include <cmath>
#include <utility>
#include "basic-DNA-RNA-AA-routines.h"
#include <climits>
#include <algorithm>
//#include "basic-DNA-RNA-AA-routines.h"
#define PrintMessage_cerr(s1) fputs(s1, stderr)
#define ErrorMessage(s1) fputs(s1, stderr)
#define flush_cerr() fflush(stderr)
////////////////////////////////////////////////////////////////////
// Head file for a DNA or PROTEIN sequence collection.
//
// Characteristics:
// - most member functions assume that sequences have identical lengths, though this is not true for all.
// If sequences are not of equal length, it is recommended to revise the code in this head file first.
//
////////////////////////////////////////////////////////////////////
// Global Functions
//////////////////////////////////
// Criteria for reference taxa:
// - Original reference taxa have 2 pipes (3 sections), other sequences have 3 pipes (4 sections) in sequence names.
// - Hamstered reference taxa are those for which section 2 and 3 are identical in the first 4 characters.
//template<class T>
inline void add_or_count(std::map<faststring, unsigned> &m, const faststring &x)
{
std::map<faststring,unsigned>::iterator it;
it = m.find(x);
if (it == m.end() )
{
m[x] = 1;
}
else
{
++it->second;
}
}
inline unsigned add_or_count_return(std::map<faststring, unsigned> &m, const faststring &x)
{
std::map<faststring,unsigned>::iterator it;
it = m.find(x);
if (it == m.end() )
{
return m[x] = 1;
}
else
{
return (++it->second);
}
}
inline void vector_of_faststring_shorten_all(std::vector<faststring> &v, faststring::size_type len)
{
size_t N = v.size();
for (size_t i=0; i< N; ++i)
{
v[i].shorten(len);
}
}
// Shortens strings if they are longer then len, appends copies of fill if they are to short.
inline void vector_of_faststring_resize_all(std::vector<faststring> &v, faststring::size_type len, char fill)
{
size_t N = v.size();
for (size_t i=0; i< N; ++i)
{
v[i].resize(len, fill);
}
}
inline void vector_of_faststring_replace_characters(std::vector<faststring> &v, faststring &string_of_replacement_symbols, char skip_char)
{
unsigned char all_symbols_lookup[256];
for (unsigned j=0; j<256; ++j)
{
all_symbols_lookup[j] = (unsigned char)j;
}
faststring::size_type n = string_of_replacement_symbols.size();
for (faststring::size_type i=0; i<n; i+=2)
{
all_symbols_lookup[(unsigned char)string_of_replacement_symbols[i]] = string_of_replacement_symbols[i+1];
}
for (size_t i=0; i < v.size(); ++i)
{
char *pos = v[i].begin();
char *pos_end = v[i].end();
char *pos_write;
char c;
unsigned removed = 0;
size_t N = v[i].length();
pos_write = pos;
while (pos < pos_end)
{
c = all_symbols_lookup[(unsigned char)*pos];
if (c != skip_char)
{
*pos_write = c;
++pos_write;
}
else
{
++removed;
}
++pos;
}
v[i].shorten(N-removed);
}
}
inline void vector_of_faststring_unique(std::vector<faststring> &v, faststring::size_type len)
{
unsigned digits = (unsigned)log10(v.size()) + 1;
unsigned mlen;
if (digits+1 >= len)
mlen = 0;
else
mlen = (unsigned)(len-digits-1);
std::map<faststring, unsigned> m_names, m_names_short;
std::map<faststring, unsigned>::iterator f_it, f_it2;
faststring tmp;
for (size_t i=0; i < v.size(); ++i)
{
add_or_count(m_names, v[i]);
}
for (size_t i=0; i < v.size(); ++i)
{
if (m_names[v[i]] > 1)
{
v[i].shorten(mlen);
}
add_or_count(m_names_short, v[i]);
}
m_names.clear();
char s = '_';
if (mlen == 0)
s = 'S';
unsigned n;
for (unsigned i=0; i < v.size(); ++i)
{
if (m_names_short[v[i]] > 1)
{
n = add_or_count_return(m_names, v[i]);
v[i] += s + faststring(n, '0', digits);
}
}
}
inline void vector_of_faststring_trimSpaces_front_back(std::vector<faststring> &v)
{
unsigned N = (unsigned)v.size();
for (unsigned i=0; i< N; ++i)
{
v[i].removeSpacesFront();
v[i].removeSpacesBack();
}
}
//////////////////////////////////
// Data types
//////////////////////////////////
//////////////////////////////////
// Class CSequences
//////////////////////////////////
// Class for aligned sequences
class CSequences3
{
public:
typedef char chartype;
private:
SequenceDataTypesEnum datatype; // DNA, Protein, or other
unsigned taxaNum;
char ambig_char;
bool originalPosNumbers_supplied;
faststring::size_type posNum; // Stores 0 if sequences have unequal lengths.
// Checked for fasta. Phylip input guarantees
// equal lengths.
std::vector<faststring::size_type> originalPosNumbers; // In case we excluded positions from the alignment, we want to remember the original positions.
std::vector<CSequence_Mol*> seqData; // The vector of pointers to sequences
// Map of short names. Only makes sense if the short names are unique!
std::map<faststring, CSequence_Mol*> sn_map; // Obtain pointer to the sequence by sequence name. Is map of short names.
// Short names are normal names
bool short_names_unique; // The short_name is the name before the first space or the full name if the name has no spaces.
void add_seq(CSequence_Mol* seq)
{
// std::cerr << "Adding: " << seq->getName() << '\n';
if (sn_map.find(seq->getName()) != sn_map.end() )
short_names_unique = false;
seqData.push_back(seq);
sn_map[seq->getName()] = seq;
}
void determine_map_of_sequence_names()
{
short_names_unique = true;
// Creates/recreates the map of short names.
if (sn_map.size() == 0)
{
std::vector<CSequence_Mol*>::size_type N=seqData.size();
for(std::vector<CSequence_Mol*>::size_type i=0; i<N; ++i)
{
if (sn_map.find(seqData[i]->getName()) != sn_map.end() )
short_names_unique = false;
sn_map[seqData[i]->getName()] = seqData[i];
}
}
}
void recompute_are_shortnames_unique()
{
sn_map.clear();
determine_map_of_sequence_names();
}
public:
// Minimal constructor: Empty sequences object
CSequences3(SequenceDataTypesEnum Dt, char set_ambig_char='?'):
datatype(Dt), taxaNum(0), ambig_char(set_ambig_char), originalPosNumbers_supplied(false),posNum(0), short_names_unique(true)
{}
// Constructor for a set of empty sequences with names and length.
CSequences3(SequenceDataTypesEnum Dt, std::vector<faststring> names, faststring::size_type len):
datatype(Dt), taxaNum((unsigned)names.size()), ambig_char('?'), originalPosNumbers_supplied(false),posNum(0), short_names_unique(true)
{
seqData.reserve(taxaNum);
CSequence_Mol *seq;
for (unsigned i=0; i<taxaNum; ++i)
{
seq = new CSequence_Mol (SeqType_dna, names[i], len, ambig_char);
add_seq(seq);
}
}
~CSequences3()
{
int n=taxaNum;
for (int i=0; i<n; ++i)
{
delete seqData[i];
}
}
// This constructor can be used as/to
// - general copy constructor
// - extract a range of sites
// Coordinates:
// pos1 must be the first column. Is 0 based index.
// pos2 must be the index after the last column. Is 0 based index.
// pos2-pos1 must be the number of bases that are copied to this sequence.
CSequences3(const CSequences3 &s, faststring::size_type pos1 = 0, faststring::size_type pos2 = faststring::npos):
datatype(s.datatype), taxaNum(s.taxaNum), ambig_char(s.ambig_char),
originalPosNumbers_supplied(false), posNum(0), short_names_unique(true)
{
unsigned n=taxaNum;
CSequence_Mol *seq;
if (n > 0)
{
// This is taken out of the loop to silence the warning that seq is used uninitialised below.
seq = new CSequence_Mol ( *(s.seqData[0]), pos1, pos2);
add_seq(seq);
for (unsigned i=1; i<n; ++i)
{
seq = new CSequence_Mol ( *(s.seqData[i]), pos1, pos2);
add_seq(seq);
}
// The following code does not check anything - remove later.
// if (i != n)
// {
// std::cerr << "Critical error in CSequences3 constructor: taxaNum and number of sequences found disagree.\n";
// }
posNum = seq->length();
}
}
bool are_short_names_unique()
{
return short_names_unique;
}
bool equal_length_of_all_sequences()
{
faststring::size_type len;
if (taxaNum==0)
return true;
len = seqData[0]->length();
for (unsigned i=1; i<taxaNum; ++i)
{
if (len != seqData[i]->length())
return false;
}
return true;
}
void trim_seq_names(faststring::size_type max_len)
{
for (unsigned i=0; i<taxaNum; ++i)
{
seqData[i]->trim_seq_name(max_len);
}
recompute_are_shortnames_unique();
}
void trim_seq_names(const char *trim_at_these_symbols)
{
for (unsigned i=0; i<taxaNum; ++i)
{
seqData[i]->trim_seq_name(trim_at_these_symbols);
}
recompute_are_shortnames_unique();
}
unsigned long memory_usage(unsigned long &value1, unsigned long &value2, unsigned long &value3, float &mean2)
{
unsigned long tmp1=sizeof(*this);
unsigned long tmp2=0, tmp3=0;
unsigned long i,N;
for (i=0, N=seqData.size(); i<N; ++i)
tmp2 += seqData[i]->memory_usage();
std::map<faststring, CSequence_Mol*>::iterator it;
it = sn_map.begin();
while (it != sn_map.end() )
{
tmp3 += it->first.memory_usage();
tmp3 += sizeof(it->first);
tmp3 += sizeof(it->second);
++it;
}
value1 = tmp1;
value2 = tmp2;
value3 = tmp3;
mean2 = (float)tmp2/N;
return tmp1 + tmp2 + tmp3;
}
CSequence_Mol* get_seq_by_name(faststring name) // Must be short name.
{
// Test code:
{
// print_DEBUG(cerr, 0);
}
std::map<faststring, CSequence_Mol*>::iterator find_it = sn_map.find(name);
if (find_it != sn_map.end() )
return find_it->second;
else
return NULL;
}
CSequence_Mol* get_seq_by_index(unsigned id)
{
if (id >= seqData.size())
{
return NULL;
}
else
{
return seqData[id];
}
}
// Depreciated: Use get_seq_by_index instead
/*
CSequence_Mol* get_seq(unsigned id)
{
return get_seq_by_index(id);
}
*/
const char* get_Seq_Data(unsigned id)
{
if (id >= seqData.size())
{
return NULL;
}
else
{
return seqData[id]->getSeqStr();
}
}
const char* get_Seq_Name(unsigned id)
{
if (id >= seqData.size())
{
return NULL;
}
else
{
return seqData[id]->getName();
}
}
const char* get_Seq_FullName(unsigned id)
{
if (id >= seqData.size())
{
return NULL;
}
else
{
return seqData[id]->getFullName();
}
}
unsigned GetTaxaNum() { return taxaNum;}
faststring::size_type GetPosNum() { return posNum;}
SequenceDataTypesEnum get_datatype()
{
return datatype;
}
chartype GetChar(unsigned TaxaIndex, faststring::size_type PosIndex) const
{
assert(TaxaIndex < taxaNum);
assert(PosIndex < posNum);
return seqData[TaxaIndex]->get_pos(PosIndex);
}
void print_DEBUG(std::ostream &os, unsigned flag=1)
{
if (flag & 1) // scalars:
{
os << "Debug output CSequences3 object, flag==0\n";
os << "Data type: " << (int)datatype<< '\n';
os << "taxaNum: " << taxaNum << '\n';
os << "posNum: " << posNum << '\n';
os << "ambig_char: " << ambig_char << '\n';
os << "originalPosNumbers_supplied " << (int)originalPosNumbers_supplied << '\n';
os << "size of originalPosNumbers vector: " << originalPosNumbers.size() << '\n';
os << "size of seqData : " << seqData.size() << '\n';
os << "size of sn_map : " << sn_map.size() << '\n';
}
if (flag & 2)
{
faststring::size_type n=seqData.size();
os << "Data types of sequences:\n";
for (unsigned i=0; i<n; ++i)
{
os << i << ": " << seqData[i]->get_datatype() << " " << seqData[i]->type_as_string() << '\n';
}
}
}
/* void SetChar(unsigned TaxaIndex, unsigned PosIndex, chartype mychar) */
/* { */
/* assert(TaxaIndex < taxaNum); */
/* assert(PosIndex < posNum); */
/* seqData[TaxaIndex]->set_pos(PosIndex, mychar); */
/* } */
void SetOriginalPosNumber(faststring::size_type index, faststring::size_type theOriginalPosNumber)
{
originalPosNumbers_supplied = true;
assert(index < posNum);
originalPosNumbers[index] = theOriginalPosNumber;
}
faststring::size_type GetOriginalPosNumber(faststring::size_type index) const
{
assert(index < posNum);
if (originalPosNumbers_supplied)
return originalPosNumbers[index];
else
return UINT_MAX;
}
// Moves taxon with index index to top, preserving the order of all other taxa.
// Of course this changes all indices with the only exception that this taxon is
// already at the top of the vector.
// The index is of course 0 based.
void reorder_move_seq_to_top(unsigned index)
{
if (index < taxaNum && index > 0)
{
seqData.insert(seqData.begin(), seqData[index]);
seqData.erase(seqData.begin()+index+1); // We have to add 1 since we have one additional entry at the beginning
}
}
// TODO: Not very efficient!!
// Return true if taxon_name has been found, false otherwise
bool reorder_move_seq_to_top(faststring &taxon_name)
{
for (unsigned i=0; i< taxaNum; ++i)
{
faststring iname = seqData[i]->getFullName();
if (seqData[i]->getFullName() == taxon_name)
{
std::cerr << "Move to top: " << i << '\n';
reorder_move_seq_to_top(i);
return true;
}
}
return false;
}
// Reorder the sequences such the those in the given vector are at the top
// in the order given by the vector.
// TODO: Not very efficient! - Very simple and thus secure implementation.
bool reorder_sort_by(std::vector<faststring> &names)
{
std::vector<faststring*>::size_type n=names.size();
bool success = true;
for (int i=(int)n-1; i>=0; --i)
{
success = success & reorder_move_seq_to_top(names[i]);
}
return success;
}
// Reorder the sequences according to the
// in the order given by the vector.
// TODO: Not very efficient! - Very simple and thus secure implementation.
void reorder_sort_by_first_number_in_seqquence_names()
{
sort(seqData.begin(), seqData.end(), less_than_sequence_name_first_unsigned_in_fullname_pointer);
}
bool get_Originalposnumbers_Supplied()
{
return originalPosNumbers_supplied;
}
char get_ambiguity_character()
{
return ambig_char;
}
void trimSeqNamesAtSymbolsInString(const char *symbol_list)
{
for (unsigned i=0; i < taxaNum; ++i)
{
seqData[i]->trim_seq_name(symbol_list);
}
}
// Returns the sequence names upto the first space
void get_short_sequence_names(std::vector<faststring> &snames)
{
snames.clear();
snames.reserve(taxaNum);
// unsigned max=0;
for (unsigned i=0; i < taxaNum; ++i)
{
snames.push_back(seqData[i]->getName_faststring());
}
// return max;
}
// Returns the maximum sequence, length
void get_full_sequence_names(std::vector<faststring> &snames)
{
snames.clear();
snames.reserve(taxaNum);
// unsigned max=0;
for (unsigned i=0; i < taxaNum; ++i)
{
snames.push_back(seqData[i]->getFullName());
/* if (snames[i].size() > max) */
/* { */
/* max = snames[i].size(); */
/* } */
}
// return max;
}
// Only works for recoded sequences!!!!
void ConsensusSequence(faststring& conSeq,
const CSplit& setOfTaxa,
unsigned char numDistCharacters, // Distinguishable characters. Recoded characters have indices 0, ..., numDistCharacters-1
unsigned char numSymbols,
double consensusThreshold )
{
unsigned char maxindex, equalindex;
unsigned taxaCount = 0;
unsigned consensusSymMinimum;
std::vector<unsigned> counterSymbolsVec(numSymbols,0);
for (faststring::size_type pos=0; pos < posNum; ++pos)
{
// Initialise variable
for (unsigned char i=0; i < numDistCharacters; ++i)
counterSymbolsVec[i] = 0;
// Count number of occuring symbols for this position over all taxa
for (unsigned taxon = 0; taxon < taxaNum; ++taxon)
{
if (setOfTaxa.test(taxon))
{
++taxaCount;
++counterSymbolsVec[seqData[taxon]->get_pos(pos)];
}
}
consensusSymMinimum = (unsigned) std::ceil(consensusThreshold * taxaCount);
maxindex = 0;
equalindex = numDistCharacters;
for (unsigned char i = 1; i < numDistCharacters; ++i)
{
if (counterSymbolsVec[i] >= counterSymbolsVec[maxindex])
{
if (counterSymbolsVec[i] == counterSymbolsVec[maxindex])
equalindex = i;
maxindex = i;
}
}
if (counterSymbolsVec[maxindex] >= consensusSymMinimum &&
maxindex != equalindex)
conSeq[pos] = maxindex;
else // Default value, in case consensus cannot be determined
conSeq[pos] = numDistCharacters;
}
}
// This version works for any kind of sequence, not only for recoded sequences.
// See also special version for DNA sequences with additional features.
void ConsensusSequence(faststring& conSeq,
double consensusThreshold,
char default_char = '\0')
{
unsigned maxindex, equalindex;
unsigned taxaCount = 0;
unsigned consensusSymMinimum;
const char **seq_strs;
seq_strs = new const char* [taxaNum];
for (unsigned seq_index=0; seq_index<taxaNum; ++seq_index)
{
seq_strs[seq_index] = get_Seq_Data(seq_index);
}
conSeq.clear();
if (default_char == '\0')
{
if (get_datatype() == SeqType_dna && default_char == '\0')
{
default_char = 'N';
}
else if (get_datatype() == SeqType_protein)
{
default_char = 'X';
}
}
// std::cout << "Default char is: " << default_char << '\n';
unsigned *counterSymbolsVec = new unsigned[256];
for (faststring::size_type pos=0; pos < posNum; ++pos)
{
// std::cout << "--- \n";
// Initialise variable
taxaCount = 0;
std::memset(counterSymbolsVec, 0, 256*sizeof(unsigned));
unsigned char c;
// Count number of occuring symbols for this position over all taxa
for (unsigned taxon = 0; taxon < taxaNum; ++taxon)
{
// char c = toupper_lookup[(unsigned char)seqData[taxon]->get_pos(pos)];
c = (unsigned char)seq_strs[taxon][pos];
++counterSymbolsVec[(unsigned char)c];
// std::cout << "Counting << " << c << " in this column " << counterSymbolsVec[c] << '\n';
}
// All gaps
if (taxaNum == counterSymbolsVec[(unsigned char)'-'])
{
conSeq.push_back('-');
}
else
{
taxaCount = taxaNum - counterSymbolsVec[(unsigned char)'-'];
consensusSymMinimum = (unsigned) std::ceil(consensusThreshold * taxaCount);
maxindex = 0;
equalindex = UINT_MAX;
for (unsigned char i = 0; i < 254; ++i)
{
if (counterSymbolsVec[i] >= counterSymbolsVec[maxindex] && i != '-')
{
if (counterSymbolsVec[i] == counterSymbolsVec[maxindex])
equalindex = i;
maxindex = i;
}
}
// std::cout << "Pos: " << pos << " maxindex: " << (char) maxindex << " equalindex " << (char)equalindex << '\n';
if (counterSymbolsVec[maxindex] >= consensusSymMinimum && maxindex != equalindex)
conSeq.push_back(maxindex);
else // Default value, in case consensus cannot be determined
conSeq.push_back(default_char);
}
// std::cout << "conSeq: " << conSeq << '\n';
}
delete [] counterSymbolsVec;
}
void ConsensusSequence_DNA(faststring& conSeq,
double consensusThreshold,
unsigned minimum_uppercase_coverage,
unsigned minimum_total_coverage,
char default_char = '\0')
{
ConsensusSequence_DNA(conSeq, consensusThreshold, minimum_uppercase_coverage, minimum_total_coverage, NULL, default_char='\0');
}
void ConsensusSequence_DNA(faststring& conSeq,
double consensusThreshold,
unsigned minimum_uppercase_coverage,
unsigned minimum_total_coverage,
std::vector<unsigned> *Pointer_coverage_vec,
char default_char = '\0')
{
unsigned taxaCount = 0;
unsigned consensusSymMinimum;
const char **seq_strs;
seq_strs = new const char* [taxaNum];
for (unsigned seq_index=0; seq_index<taxaNum; ++seq_index)
{
seq_strs[seq_index] = get_Seq_Data(seq_index);
}
conSeq.clear();
if (Pointer_coverage_vec)
Pointer_coverage_vec->clear();
if (default_char == '\0')
{
default_char = 'N';
}
// std::cout << "Default char is: " << default_char << '\n';
unsigned *counterSymbolsVec = new unsigned[256];
std::memset(counterSymbolsVec, 0, 256*sizeof(unsigned));
for (faststring::size_type pos=0; pos < posNum; ++pos)
{
// std::cout << "--- \n";
// Initialise variable
taxaCount = 0;
unsigned char c;
// Count number of occuring symbols for this position over all taxa
for (unsigned taxon = 0; taxon < taxaNum; ++taxon)
{
// char c = toupper_lookup[(unsigned char)seqData[taxon]->get_pos(pos)];
c = (unsigned char)seq_strs[taxon][pos];
++counterSymbolsVec[(unsigned char)c];
// std::cout << "Counting << " << c << " in this column " << counterSymbolsVec[c] << '\n';
}
// All gaps
if (taxaNum == counterSymbolsVec[(unsigned char)'-'])
{
conSeq.push_back('-');
}
else
{
unsigned cA = counterSymbolsVec[(unsigned char)'A']+counterSymbolsVec[(unsigned char)'a'];
unsigned cC = counterSymbolsVec[(unsigned char)'C']+counterSymbolsVec[(unsigned char)'c'];
unsigned cG = counterSymbolsVec[(unsigned char)'G']+counterSymbolsVec[(unsigned char)'g'];
unsigned cT = counterSymbolsVec[(unsigned char)'T']+counterSymbolsVec[(unsigned char)'t'];
unsigned ctilde = counterSymbolsVec[(unsigned char)'~'];
// unsigned cN = counterSymbolsVec[(unsigned char)'N']+counterSymbolsVec[(unsigned char)'n'];
/*
if (verbosity > 0)
{
std::cout << "Consensus at index: " << pos << '\n';
std::cout << cA << " " << cC << " " << cG << " " << cT << '\n';
std::cout << counterSymbolsVec[(unsigned char)'A'] << " " << counterSymbolsVec[(unsigned char)'a'] << '\n';
std::cout << counterSymbolsVec[(unsigned char)'C'] << " " << counterSymbolsVec[(unsigned char)'c'] << '\n';
std::cout << counterSymbolsVec[(unsigned char)'G'] << " " << counterSymbolsVec[(unsigned char)'g'] << '\n';
std::cout << counterSymbolsVec[(unsigned char)'T'] << " " << counterSymbolsVec[(unsigned char)'t'] << '\n';
}
*/
taxaCount = cA + cC + cG + cT + ctilde;
consensusSymMinimum = (unsigned) std::ceil(consensusThreshold * taxaCount);
if (consensusSymMinimum < minimum_total_coverage)
consensusSymMinimum = minimum_total_coverage;
if (cA > cC && cA > cG && cA > cT && cA > ctilde)
{
if (cA >= consensusSymMinimum && counterSymbolsVec[(unsigned char)'A'] >= minimum_uppercase_coverage)
conSeq.push_back('A');
else
conSeq.push_back(default_char);
}
else if (cC > cA && cC > cG && cC > cT && cC > ctilde)
{
if (cC >= consensusSymMinimum && counterSymbolsVec[(unsigned char)'C'] >= minimum_uppercase_coverage)
conSeq.push_back('C');
else
conSeq.push_back(default_char);
}
else if (cG > cA && cG > cC && cG > cT && cG > ctilde)
{
if (cG >= consensusSymMinimum && counterSymbolsVec[(unsigned char)'G'] >= minimum_uppercase_coverage)
conSeq.push_back('G');
else
conSeq.push_back(default_char);
}
else if (cT > cA && cT > cC && cT > cG && cT > ctilde)
{
if (cT >= consensusSymMinimum && counterSymbolsVec[(unsigned char)'T'] >= minimum_uppercase_coverage)
conSeq.push_back('T');
else
conSeq.push_back(default_char);
}
else if (ctilde > cA && ctilde > cC && ctilde > cG && ctilde > cT)
{
if (ctilde >= consensusSymMinimum && ctilde >= minimum_uppercase_coverage)
conSeq.push_back('~');
else
conSeq.push_back(default_char);
}
else // No consensus, the larger two or more are equal
{
conSeq.push_back(default_char);
}
/*
if (verbosity > 0)
{
std::cout << "Decision: " << conSeq.back() << '\n';
}
*/
} // END else of all gaps
// std::cout << "conSeq: " << conSeq << '\n';
if (Pointer_coverage_vec)
Pointer_coverage_vec->push_back(taxaCount);
// Reset the counter array:
counterSymbolsVec[(unsigned char)'A'] = 0;
counterSymbolsVec[(unsigned char)'a'] = 0;
counterSymbolsVec[(unsigned char)'C'] = 0;
counterSymbolsVec[(unsigned char)'c'] = 0;
counterSymbolsVec[(unsigned char)'G'] = 0;
counterSymbolsVec[(unsigned char)'g'] = 0;
counterSymbolsVec[(unsigned char)'T'] = 0;
counterSymbolsVec[(unsigned char)'t'] = 0;