-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSequences2.h
1992 lines (1645 loc) · 53.7 KB
/
CSequences2.h
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
/* fast_TIGER (version 1.0), a program for computing TIGER rates
* (TIGER: Tree Independent Generation of Evolutionary Rates).
*
* Copyright (C) January 2015 by Paul Frandsen and Christoph Mayer
*
* This program 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 2 of the License, or
* (at your option) any later version.
* This program 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 this program; if not, see <http://www.gnu.org/licenses/>.
*
* For any enquiries send an email to
* Paul Frandsen: paulbfrandsen@gmail.com
* or
* Christoph Mayer: c.mayer.zfmk@uni-bonn.de
*
* When publishing work that is based on the results of Fast_Tiger please cite:
*
* Frandsen, P.B., Calcott, B., Mayer, C., Lanfear, R., 2015, Automatic selection of
* partitioning schemes for phylogenetic analyses using iterative k-means clustering
* of site rates, BMC Evolutionary Biology 15:13.
*
*/
//////////////////////////////////////////////////////////////////////
// CSequences.h: interface for the CSequences class.
//
//////////////////////////////////////////////////////////////////////
#ifndef CSEQUENCES2_H
#define CSEQUENCES2_H
#include <vector>
#include <map>
#include "faststring2.h"
#include "CSplit2.h"
#include "CSequence_Mol2_1.h"
#include <cassert>
#include <cmath>
#include <utility>
//#include "basic-DNA-RNA-AA-routines.h"
#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)
//////////////////////////////////
// Global Functions
//////////////////////////////////
//template<class T>
inline void add_or_count(std::map<faststring, unsigned> &m, faststring &x)
{
std::map<faststring,unsigned>::iterator it;
it = m.find(x);
if (it == m.end() )
{
m[x] = 1;
}
else
{
++it->second;
}
}
//////////////////////////////////
// Data types
//////////////////////////////////
//////////////////////////////////
// Class CSequences
//////////////////////////////////
// Class for aligned sequences
class CSequences2
{
public:
typedef char chartype;
private:
CSequence_Mol::DataTypesEnum datatype; // DNA, Protein, or other
unsigned taxaNum;
char ambig_char;
bool originalPosNumbers_supplied;
unsigned posNum;
std::vector<unsigned> 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
std::map<faststring, CSequence_Mol*> sn_map; // Obtain pointer to the sequence by sequence name.
void add_seq(CSequence_Mol* seq)
{
// std::cerr << "Adding: " << seq->getName() << std::endl;
seqData.push_back(seq);
sn_map[seq->getName()] = seq;
}
bool equal_length_of_all_sequences()
{
size_t len;
unsigned i;
if (taxaNum==0)
return true;
len = seqData[0]->length();
for (i=1; i<taxaNum; ++i)
{
if (len != seqData[i]->length())
return false;
}
return true;
}
void determine_map_of_sequence_names()
{
if (sn_map.size() == 0)
{
int i, N=seqData.size();
for(i=0; i<N; ++i)
{
sn_map[seqData[i]->getName()] = seqData[i];
}
}
}
public:
// Minimal constructor: Empty sequences object
CSequences2(CSequence_Mol::DataTypesEnum Dt):
datatype(Dt), taxaNum(0), ambig_char('?'), originalPosNumbers_supplied(false),posNum(0)
{}
// Constructor for a set of empty sequences with names and length.
CSequences2(CSequence_Mol::DataTypesEnum Dt, std::vector<faststring> names, unsigned len):
datatype(Dt), taxaNum(names.size()), ambig_char('?'), originalPosNumbers_supplied(false),posNum(0)
{
seqData.reserve(taxaNum);
unsigned i;
CSequence_Mol *seq;
for (i=0; i<taxaNum; ++i)
{
seq = new CSequence_Mol (CSequence_Mol::dna, names[i], len, ambig_char);
add_seq(seq);
}
}
~CSequences2()
{
int i, n=taxaNum;
for (i=0; i<n; ++i)
{
delete seqData[i];
}
}
// This constructor can be used to
// - general copy constructor
// - extract a range of sites
// Coordinates:
// pos1 must be the first column starting with 0.
// pos2 must be the index after the last column.
// pos2-pos1 must be the number of bases that are copied to this sequence.
CSequences2(const CSequences2 &s, unsigned pos1 = 0, unsigned pos2 = -1u):
datatype(s.datatype), taxaNum(s.taxaNum), ambig_char(s.ambig_char),
originalPosNumbers_supplied(false), posNum(0)
{
unsigned i, n=taxaNum;
CSequence_Mol *seq;
for (i=0; i<n; ++i)
{
seq = new CSequence_Mol ( *(s.seqData[i]), pos1, pos2);
add_seq(seq);
}
if (i != n)
{
std::cerr << "Critical error in CSequences2 constructor: taxaNum and number of sequences found disagree." << std::endl;
}
if (n > 0)
posNum = seq->length();
}
CSequence_Mol* get_seq_by_name(faststring 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:
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();
}
}
unsigned GetTaxaNum() { return taxaNum;}
unsigned GetPosNum() { return posNum;}
CSequence_Mol::DataTypesEnum get_datatype()
{
return datatype;
}
chartype GetChar(unsigned TaxaIndex,
unsigned PosIndex) const
{
assert(TaxaIndex < taxaNum);
assert(PosIndex < posNum);
return seqData[TaxaIndex]->get_pos(PosIndex);
}
void print_DEBUG(std::ostream &os, unsigned flag=0)
{
if (flag == 0) // scalars:
{
os << "Debug output CSequence object, flag==0" << std::endl;
os << "taxaNum: " << taxaNum << std::endl;
os << "posNum: " << posNum << std::endl;
os << "ambig_char: " << ambig_char << std::endl;
os << "originalPosNumbers_supplied " << (int)originalPosNumbers_supplied << std::endl;
os << "size of originalPosNumbers vector: " << originalPosNumbers.size() << std::endl;
os << "size of seqData : " << seqData.size() << std::endl;
os << "size of sn_map : " << sn_map.size() << std::endl;
}
}
/* void SetChar(unsigned TaxaIndex, unsigned PosIndex, chartype mychar) */
/* { */
/* assert(TaxaIndex < taxaNum); */
/* assert(PosIndex < posNum); */
/* seqData[TaxaIndex]->set_pos(PosIndex, mychar); */
/* } */
void SetOriginalPosNumber(unsigned index, unsigned theOriginalPosNumber)
{
originalPosNumbers_supplied = true;
assert(index < posNum);
originalPosNumbers[index] = theOriginalPosNumber;
}
unsigned GetOriginalPosNumber(unsigned index) const
{
assert(index < posNum);
if (originalPosNumbers_supplied)
return originalPosNumbers[index];
else
return -1u;
}
// Moves taxon with index index to top, preseving 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)
{
unsigned i;
for (i=0; i< taxaNum; ++i)
{
faststring iname = seqData[i]->getFullName();
if (seqData[i]->getFullName() == taxon_name)
{
std::cerr << "Move to top: " << i << std::endl;
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)
{
int i,n=names.size();
bool success = true;
for (i=n-1; i>=0; --i)
{
success = success & reorder_move_seq_to_top(names[i]);
}
return success;
}
bool get_Originalposnumbers_Supplied()
{
return originalPosNumbers_supplied;
}
char get_ambiguity_character()
{
return ambig_char;
}
void get_sequence_names(std::vector<faststring> &snames)
{
snames.clear();
unsigned i;
for (i=0; i < taxaNum; ++i)
{
snames.push_back(seqData[i]->getFullName());
}
}
void unique_phylip_names(std::vector<faststring> &snames)
{
snames.clear();
std::map<faststring, unsigned> m_snames;
std::map<faststring, unsigned>::iterator f_it;
unsigned digits = (unsigned)log10(taxaNum) + 1;
unsigned i;
for (i=0; i < taxaNum; ++i)
{
// push_back first sequence phylip sequence name. This is already trimmed to 10 characters.
snames.push_back(seqData[i]->getPhylipName());
// Search for this name in m_snames map.
f_it = m_snames.find(snames[i]);
// If we find it it is not unique
if (f_it != m_snames.end() ) // This name is not unique
{
++f_it->second; // We count this occurence
}
else // If we do not find it, we insert it and set the counter to 1
{
m_snames.insert(std::make_pair(snames[i], 1));
}
}
// We have build the map that count the number of occurences - now we need to create unique names:
f_it = m_snames.begin();
while (f_it != m_snames.end() )
{
if (f_it->second > 1) // If the 10 character sequence name occurs more than one, we have to number them:
{
unsigned internal_counter = 1;
unsigned j;
for (j=0; j<taxaNum; ++j)
{
if (snames[j] == f_it->first)
{
snames[j] = snames[j].substr(0,10-digits);
faststring nn = faststring(internal_counter, '0', digits);
nn.replace_char(' ', '0');
snames[j].append(nn);
++internal_counter;
}
}
}
++f_it;
}
}
unsigned PairwiseSequenceSymbolMatches(unsigned taxon1, unsigned taxon2,
char numDistCharacters,
const signed char* pos_vec,
signed char* match_vec) const
{
unsigned count = 0;
unsigned pos;
for (pos = 0; pos < posNum; ++pos)
{
if (pos_vec[pos] &&
seqData[taxon1]->get_pos(pos) == seqData[taxon2]->get_pos(pos) &&
seqData[taxon1]->get_pos(pos) < numDistCharacters)
{
++count;
match_vec[pos] = 1;
}
else
match_vec[pos] = 0;
}
return count;
}
unsigned PairwiseSequenceSymbolMatches(
unsigned taxon1,
const faststring & ref_seq,
char numDistCharacters,
const signed char* pos_vec,
signed char* match_vec) const
// Ist hier alles OK?????????????????????????????????????????
{
unsigned count = 0;
unsigned pos;
for (pos = 0; pos < posNum; ++pos)
{
if (pos_vec[pos] && seqData[taxon1]->get_pos(pos) == ref_seq[pos]
&& ref_seq[pos] < numDistCharacters)
{
++count;
match_vec[pos] = 1;
}
else
match_vec[pos] = 0;
}
return count;
}
void ConsensusSequence(faststring& conSeq,
const CSplit& setOfTaxa,
char numDistCharacters,
unsigned numSymbols,
double consensusThreshold )
{
unsigned pos;
unsigned taxon, maxindex, equalindex;
unsigned taxaCount = 0;
unsigned consensusSymMinimum;
char i;
std::vector<unsigned> counterSymbolsVec(numSymbols,0);
for (pos=0; pos < posNum; ++pos)
{
// Initialise variable
taxaCount = 0;
for (i=0; i < numDistCharacters; ++i)
counterSymbolsVec[i] = 0;
// Count number of occuring symbols for this position over all taxa
for (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 (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;
}
}
void GetSymbolFrequenciesAtPosition(unsigned pos, const CSplit &taxaSet,
unsigned numSymbols,
std::vector<unsigned>& frequencies)
{
unsigned i;
// chartype sym;
// assert(frequencies.size() <= numDistCharacters);
for (i=0; i<numSymbols; ++i)
frequencies[i]=0;
for (i=0; i<taxaNum; ++i)
{
if (taxaSet.test(i))
{
++frequencies[seqData[i]->get_pos(pos)];
}
}
}
int read_from_Fasta_File(CFile& infile,
CSequence_Mol::processing_flag pflag,
unsigned first_seq,
unsigned last_seq,
bool report_status_to_cerr=true
)
{
CSequence_Mol *seq;
unsigned count_seq = 0;
unsigned count_seqs_stored = 0;
// TODO
(void) report_status_to_cerr;
// Remove all sequences from this object - we want to read a new data set.
clear(datatype);
while (!infile.eof())
{
seq = new CSequence_Mol (datatype);
++count_seq;
seq->readFastaSequence_generic(infile, pflag);
// PrintMessage_cerr(seq.getName());PrintMessage_cerr("-\n");PrintMessage_cerr(seq.getFullName());PrintMessage_cerr("-\n");PrintMessage_cerr(seq.getDescription());PrintMessage_cerr("-\n");
if ( infile.fail() && !infile.eof() )
{
PrintMessage_cerr("\n\n");
faststring errormsg;
errormsg = "An error occurred while reading the input file. It might not be a valid fasta file.\n";
errormsg += "File position: line ";
errormsg += faststring(infile.line());
ErrorMessage(errormsg.c_str());
PrintMessage_cerr("\n");
flush_cerr();
return -25;
}
if ( count_seq < first_seq || count_seq > last_seq )
{
if (report_status_to_cerr)
{
PrintMessage_cerr("Skipping sequence ");
PrintMessage_cerr(faststring(count_seq).c_str());
PrintMessage_cerr(": ");
PrintMessage_cerr(seq->getName());
PrintMessage_cerr("\n");
flush_cerr();
}
continue;
}
if (report_status_to_cerr)
{
PrintMessage_cerr("Processing sequence ");
PrintMessage_cerr(faststring(count_seq).c_str());
PrintMessage_cerr(": ");
PrintMessage_cerr(seq->getName());
PrintMessage_cerr("\n");
flush_cerr();
}
add_seq(seq);
++count_seqs_stored;
} // End while
// Check that all sequences have the same length - we require that they have the same length
if (!equal_length_of_all_sequences() )
return -1;
// Check equal data type and ambig character:
taxaNum = count_seqs_stored;
if (taxaNum > 0)
{
posNum = seqData[0]->length();
ambig_char = seqData[0]->get_ambiguity_character();
}
return 0;
} // End this element function.
// Can read sequential and interleaved phylip files
// Cannot read multi phylip files.
// format_flag: 0 strict phylip standard. Sequence names are exactly 10 characters long.
// 1 relaxed sequence name length. Sequence names end with first space and can have anly length.
// Spaces are not allowed in sequence names.
int read_from_Phylip_File(CFile& infile, unsigned format_flag = 1)
{
CSequence_Mol *seq;
// unsigned count_seq;
// unsigned global_sequence_from=0, global_sequence_to=-1u;
// bool global_gaps_to_Ns=false;
unsigned all_lines_N;
unsigned curr_taxon;
char read_mode;
// The allowed symbols from the phylip manual:
char ch;
faststring line;
std::vector<faststring> fsvec;
faststring *p;
// Clear the oject and initialize it with the supplied data type
clear(datatype); // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ch = infile.peek();
// If the first char is a white space or a digit, we expect this
// is the line with the number of taxa and seq. positions.
if ( isspace(ch) || isdigit(ch) )
{
infile.getline(line);
split(fsvec, line);
if (fsvec.size()==2 && fsvec[0].isAnUnsigned() && fsvec[1].isAnUnsigned() )
{
taxaNum = fsvec[0].ToUnsigned();
posNum = fsvec[1].ToUnsigned();
/* std::cout << "Number of taxa " << taxaNum << std::endl; */
/* std::cout << "Number of residues " << posNum << std::endl; */
}
}
// std::vector<faststring*> sqs;
std::vector<faststring*> all_lines;
/* if (taxaNum == 0 && posNum == 0) */
/* { */
/* faststring *pp = new faststring; */
/* *pp = line; */
/* all_lines.push_back(pp); */
/* } */
// We read the complete file into a vector of strings.
p = new faststring();
infile.getline(*p);
p->removeSpacesFront();
p->removeSpacesBack();
while (!infile.fail() )
{
all_lines.push_back(p);
p = new faststring();
infile.getline(*p);
p->removeSpacesFront();
p->removeSpacesBack();
}
// The problem is: The phylip format is very difficult
// to parse. Main problem is to distinguish between
// sequential and interleaved format.
// The interleaved format is distinguished as follows:
// After each block there must be a blank line.
// So if we find blank lines which are not the last line
// the format is interleaved. Otherwise it is sequential.
// Another problem is relaxed versus strict format.
// In the related format the sequence name and the sequence are separated by white spaces.
// In the strict format the sequence name is less or sequal to 10 character.
// Example: Name123456A MILLV
// Can be interpreted as sequence AMILLV or as sequence MILLV with the two different names.
// In the strit format the following would be legal:
// NAME123456MILLVWSAL LADDPKHIMV
// The sequence name would be NAME123456 the rest is the sequence.
// Note that the format allows spaces in the sequence.
// The two versions cannot be distinguished unambiguously!!
// Pragmatic approach: In the presence of one white space island, we assume the relaxed format.
// Otherwise the strict format.
// Since empty lines are allowed at the end of the file in all formats we remove them.
// They cannot be indicative of the interleaved format.
unsigned i;
all_lines_N = all_lines.size();
// std::cerr << all_lines[all_lines_N-1]->length() << std::endl;
while (all_lines[all_lines_N-1]->length() == 0)
{
--all_lines_N;
delete all_lines[all_lines_N];
std::vector<faststring*>::iterator it = all_lines.end();
--it;
all_lines.erase(it);
}
unsigned number_blank_lines=0;
for (i=0; i<all_lines_N; ++i)
{
if (all_lines[i]->length() == 0)
{
++number_blank_lines;
}
}
if (all_lines_N == 0 || number_blank_lines == all_lines_N) // Nothing to do???
return 0;
if (number_blank_lines == 0) // sequential format
{
read_mode = 's';
// Example:
//a ATGATTCAAC CTCAGACCCT TTTAAATGTA GCAGATAACA GTGGAGCTCG
// AAAATTGATG
//b ATGATTCAAC CTCAGACCCA TTTAAATGTA GCGGATAACA GCGGGGCTCG
// AGAATTGATG
// This can only be interpreted, if the number
// of taxa and positions has been specified in
// the first line.
// What makes it more complicated
// is the fact, that the phylip format tolerates
// numbers and other stuff at the beginning of pure sequence lines.
faststring seq_taxon_name;
faststring seq_in_one_line;
// unsigned current_length = 0;
unsigned curr_line_num=0;
faststring *currLine;
if (taxaNum == 0 || posNum == 0)
{
// delete all faststrings in all_lines
for (unsigned ind=0; ind < all_lines.size(); ++ind)
delete all_lines[ind];
return -3;
}
// For all taxa
//
for (curr_taxon = 0; curr_taxon < taxaNum; ++curr_taxon)
{
if (curr_line_num >= all_lines_N)
{
std::cerr << "Parse error while reading the input file:\nUnexpected end of file in line: " << curr_line_num << std::endl;
std::cerr << "Trying to read " << taxaNum << " taxa but found only " << curr_taxon << "!" << std::endl;
exit(-45);
}
currLine = all_lines[curr_line_num];
const char* pos = currLine->c_str();
// currLineLen = currLine->length();
seq_taxon_name.clear();
seq_in_one_line.clear();
// Copy the sequence name
if (format_flag == 0)
{
for (i=0; i<10 && *pos != '\0'; ++i, ++pos)
{
seq_taxon_name.push_back(*pos);
}
if (i<10) // Fill name with spaces.
seq_taxon_name.append(10-i, ' ');
}
else
{
for (;*pos != '\0' && *pos != ' '; ++pos)
{
seq_taxon_name.push_back(*pos);
}
}
// Skip all spaces:
while (*pos == ' ' && *pos != '\0')
++pos;
// Read data after sequence name:
if (*pos)
{
// Copy the sequence data:
{
// Find first character that shall be copied.
// pos should point to the first char of the sequence.
char c;
// Skip all non-allowed symbols - since we skiped spaces, there should be none.
c = *pos;
while (!is_phylip_aa_dna_symbol(c) && !is_allowed_non_ABC(c) )
{
++pos;
c = *pos;
}
}
// Now pos points to the first char that should be copied:
while (*pos)
{
if (*pos != ' ')
{
seq_in_one_line.push_back(*pos);
}
++pos;
}
} // END if (*pos) AND read data after sequence name.
// Read lines until we have the required number of residues:
// TODO: More error checking could be done here:
// We could check that only allowed symbols are added.
// By this we also might be able to detect an error earlier
while (seq_in_one_line.length() < posNum)
{
++curr_line_num;
if (curr_line_num >= all_lines_N)
{
std::cerr << "Parse error while reading the input file. The file has been interpreted as being in sequential phylip format." << std::endl;
std::cerr << "Several problems can trigger this error: (i) Wrong number of residues in sequences compared to the number specified " << std::endl;
std::cerr << "in the file header. (ii) Wrong number of taxa (sequences) compared to the number specified in the file header." << std::endl;
std::cerr << "(iii) Missing blank line between blocks of data if this file should be in interleaved format." << std::endl;
exit(-44);
}
currLine = all_lines[curr_line_num];
// const char* pos = currLine->c_str();
{
// Find first character that shall be copied.
char c;
pos = currLine->c_str();
c = *pos;
while (!is_phylip_aa_dna_symbol(c) && !is_allowed_non_ABC(c) )
{
++pos;
c = *pos;
}
}
// Now pos points to the first char that should be copied:
// Here we are in the sequential section, reading all residues until
// we have filled our sequence.
while (*pos)
{
if (*pos != ' ')
{
seq_in_one_line.push_back(*pos);
}
++pos;
}
}
// If we are here, the sequence should have been copied to
// seq_in_one_line
seq = new CSequence_Mol (datatype);
seq->set_taxon_and_sequence(seq_taxon_name, seq_in_one_line, datatype);
add_seq(seq);
// The next line should start with a new sequence:
++curr_line_num;
} // End for loop - for all taxa
if (curr_line_num != all_lines_N)
{
std::cerr << "Parse error while reading the input file: This can have several reasons:\n"
"(i) The number of taxa found in the first block does not match the number specified in the file header.\n"
"(ii) Since only one data block was found, this file is interpreted as sequential format. If this should be a file\n"
"in interleaved format, blank line must be added between blocks of data.\n"
"(iii) It could also be that the number of residues in the sequences is larger than specified in the header, so that addtional\n"
"lines of data are interpreted as additional taxa in the sequential format." << std::endl;
exit(-67);
}
} // End sequential format
else // Interleaved format
{
read_mode = 'i';
// In the first block, the first 10 characters are
// the sequence name. Then the first base starts
// the sequence.
// After the first block, the sequence beginns/continues at
// the first base symbol in each line. Thus, numbers and spaces are ignored.
// Sequence names are not allowed in interleaved blocks.
// With format_flag == 1 we may have a different number of sequence name characters.
// But then, no spaces are allowed in the sequnce name.
unsigned curr_line_num=0;
faststring *currLine;
// unsigned current_length = 0;
unsigned curr_taxon = 0;
faststring *pseq_taxon_name = NULL;
faststring *pseq_in_one_line = NULL;
std::vector<faststring*> taxonnames;
std::vector<faststring*> sequences;
currLine = all_lines[curr_line_num];
const char* pos;
// read first block (interleaved) - until we find a blank line:
while ( currLine->length() != 0 ) // We read all lines of the first block. Counter: curr_line_num
{
pos = currLine->c_str();
// We will store all pointer to sequences in the vectors defined above,
// so we do not delete sequences here. We keep on creating new ones.
pseq_taxon_name = new faststring;
pseq_in_one_line = new faststring;
// Copy the sequence name
if (format_flag == 0)
{
for (i=0; i<10 && *pos != '\0'; ++i, ++pos)
{
pseq_taxon_name->push_back(*pos);
}