-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimprot.cpp
3191 lines (2796 loc) · 109 KB
/
simprot.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
/* Simprot (c) Copyright 2005-2012 by the University Health Network written by Elisabeth Tillier.
Permission is granted to copy and use this program provided no fee is charged for it
and provided that this copyright notice is not removed. */
#include <fstream>
#include <string>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <string.h>
#include <popt.h>
#include <math.h>
#include <float.h>
#include <sys/types.h>
//#include <windows.h> //Windows only
#include <unistd.h> //Linux only
#include <time.h>
#include <stdlib.h> //needed on Linux and not Windows
#include <errno.h>
#include <stdint.h>
/** THIS HEADER CONTAINS THE EIGEN-DECOMPOSED MATRICES **/
#include "eigen.h"
#include "random.h"
using namespace std;
// Constants.
#define INSERTION 1
#define DELETION 0
#define ALPHABET_SIZE 27
#define MAX_TREE_SIZE 65536
#define BUFFER_SIZE 65536
#define MAX_TOKEN_SIZE 65536
#define MAX_SEQUENCE_NAME_LENGTH 128
#define MAX_PATH_NAME 1024
#define MAX_SEQUENCE_LENGTH 5000
#define INIT_MAX_GAMMA_RATE_ITERATIONS 10000
#define MAX_GAMMA_THRESHOLD 0.9999999999
/*
#define CR 13 /* Decimal code of Carriage Return char
#define LF 10 /* Decimal code of Line Feed char
#define EOF_MARKER 26 /* Decimal code of DOS end-of-file marker
#define MAX_REC_LEN 1024 /* Maximum size of input buffer
*/
// This constant represents the spaces making up gaps
#define SPACE '-'
// These constants are used to remember where we came
// from when recursively traversing the tree.
#define LEFT 'L'
#define RIGHT 'R'
/**************************** FILE NAMES **************************************/
// Input files File contains:
char *TreeFileName ; // evolutionary tree
char *RootSequenceFileName ; // user root sequence
char *GapDistFileName ; // user root sequence
char *CorrelFileName ;
// Output files File will contain:
/*@null@*/
static char *TrueAlignmentFileName = NULL; // The name of the output file
static char *IndelFileName=NULL; //to outout indel sizes as created;
/*@null@*/
static char *FastaFileName = NULL; // generated sequences in FASTA format
static char *PhylipFileName = NULL; // (PN Mar05), output in Phylip format
/******************************************************************************/
/**************************** FILES *******************************************/
static FILE *TrueAlignmentFile;
static FILE *FastaFile;
static FILE *PhylipFile;
static FILE *pFile;
/******************************************************************************/
/**************************** LOOKUP TABLES ***********************************/
static char itor[21]; // Convert an {i}nteger to a {r}esidue
static int rtoi[26]; // Convert a {r}esidue to an {i}nteger
static double SymbolCumulativeDensity[21];
static double matrix[20][20][4];
static double row_totals[20][4];
typedef struct correl {
int pos;
double value;
};
static correl Correlation[MAX_SEQUENCE_LENGTH];
static double *IndelCumulativeDensity;
static double *IndelLengthCumulativeDensity;
/******************************************************************************/
// Some values
static int max_indel_length = 2048;
static int root_sequence_length = 50;
static double IndelLengthFreq[2048];
static int debug_mode = 0;
static int internal_count = 0;
// Parameters for the Gamma distribution
static double alpha = 1.0;
static double beta = 1.0;
// Gap initiation and extension penatlties
static double GapExtensionPenalty = 1;
static double GapOpenProbability;
double INDEL_FREQ = 0.03;
int subModel = 2;
int interleave = 0; // (PN Aug05)
int benner = 0; // (PN Aug05)
int variablegamma = 0; // (PN Aug05)
int bennerk = -2; // (PN Sep05)
double indelWeight = 0; // (JA Aug06)
double extra_terminal_indels = 0; // (JA Sep06)
double *eigmat; /* eig matrix variable */
double **probmat; /* prob matrix variable */
double freqaa[20]; /* amino acid frequencies */
double TreeBranchScale = 1.0; /* Scaling the branch length of the tree file */
double EvolScale = 3.0; /* scale factor of distance when determining the length of Indel */
double previousGamma; /* (PN Sep05) debug test */
double VariableBranch = 0; /* flag that sets the branch length scale multiplier to random or not */
double BranchExtinction = 0; /*PN Dec 07, value of the probability of branch being "extinct", or have a negative
branch length*/
double InDelRatio = 0.5;
int IndelDistLength= 200;
/****************************************************************************
* STRUCT DEFINITIONS
****************************************************************************/
/**** THE STRUCT REPRESENTING THE TREE NODES ****/
typedef struct TreeNode_ {
// The {left,right}_profile_self contain exactly the same residue list as
// "sequence". the {left,right}_profile_self contain exactly the same
// residue list as "sequence" in the left or right child. However:
// left_profile_{child,self} are aligned such that the two sequences have
// their relative gaps marked with SPACE characters.
// right_profile_{child,self} are aligned in the same way.
char *left_profile_child, *left_profile_self;
char *right_profile_child, *right_profile_self;
/* The name, sequence and rate vector of the node */
char *name; // as defined in the tree input file
char *sequence; // the sequence at this node, with no gaps
double *rate;
char *extinct;
/* The left and right children of the node */
struct TreeNode_ *left, *right;
/* The distance on the edge above the node */
double distance; // branch length to the parent node
} TreeNode;
/*************** THE STRUCTS REPRESENTING ALIGNMENTS ***************
* These were originally structs of pointers, but no provision was
* made for dynamic memory management. As a consequence, memory
* usage was out of control for large trees, as the maximum possible
* memory allocation was used to guard against buffer overflow.
* The recursive nature of the algorithm meant exponential growth
* of memory usage. String's memory management obviates this problem.
*
* Further optimizations in speed and memory usage might be made
* elsewhere in the program as well, but this is not urgent.
*******************************************************************/
struct Row {
std::string name;
std::string sequence;
Row() { }
Row(const char* theName, const char* theSequence) : name(theName), sequence(theSequence) { }
};
struct Alignment {
std::vector<Row> r;
explicit Alignment(TreeNode* currentNode); // was GetAlignment()
Alignment(const Alignment& child_aln, TreeNode* current_node, char child_type_flag); // was AlignProfile()
Alignment(const Alignment& a, const Alignment& b); // was AlignAlignments()
};
/*********************************************************************
* Modified by RLC from:
* static Alignment *GetAlignment(TreeNode *current_node);
*
* RECURSIVE CONSTRUCTOR TO OBTAIN A TRUE ALIGNMENT OF SEQUENCES AT THE
* LEAVES OF THE TREE.
*
* ARGUMENTS:
* current_node (TreeNode *) The root of the (sub) tree for which an
* alignment of the sequences is to be constructed
**********************************************************************/
Alignment::Alignment(TreeNode* current_node)
{
// If the present node is a leaf, then we just make an alignment
// of a single sequence (i.e. no indels).
// Remember: if there is no left child, there will be no right
// child, and the node is a leaf.
if (!current_node->left && current_node->sequence != NULL) { // if the node is a leaf
// printf("%s\n%s\n", current_node->name, current_node->sequence);
r.resize(1, Row(current_node->name, current_node->sequence)); // This obviates the need for MakeAlignment()
} else {
// Here we are getting the alignment for a non-leaf node.
// Recurse left, then align the present sequence to the alignment from the left subtree:
const Alignment left_profile(Alignment(current_node->left), current_node, LEFT);
// Recurse right, then align the present sequence to the alignment from the right subtree:
const Alignment right_profile(Alignment(current_node->right), current_node, RIGHT);
// Align the left+present and right+present alignments, and assign it to this object:
Alignment lr(left_profile, right_profile);
r.swap(lr.r);
}
}
/***********************************************************************
* Modified by RLC from:
* static Alignment *AlignProfile(Alignment *child_aln, TreeNode *current_node, char child_type_flag);
*
* FUNCTION TO ALIGN A SINGLE SEQUENCE TO AN EXISTING ALIGNMENT, USING
* A PROFILE THAT CONTAINS THE POSITIONS WHERE THE SINGLE ALIGNS WITH
* THE FIRST SEQUENCE OF THE EXISTING ALIGNMENT.
*
* ARGUMENTS:
* child_aln : Alignment of sequences in the left or right subtree
* current_node: (TreeNode *) Node whose sequence is to be added to
* the 'child_aln'
* child_type_flag: (char *) Flag indicating whether it is the left or right
* child alignment with which the current_node's sequence
* is to be aligned
*
* RESULTS:
* Constructs a 'true' alignment of all sequences in the
* (left/right) subtree and the sequence at the 'current_node'
**********************************************************************/
Alignment::Alignment(const Alignment& child_aln, TreeNode* current_node, char child_type_flag) :
r(child_aln.r.size() + 1) // Make a new alignment
{
// Copy the name of the sequence to be added:
r[0].name = current_node->name;
// Copy the names of the sequences already there:
const std::size_t m = child_aln.r.size();
std::size_t z;
for (z = 0; z < m; ++z) {
r[z + 1].name = child_aln.r[z].name;
}
// Point the profile pointers at the appropriate child sequences:
char* profile[2];
if (child_type_flag == LEFT) {
profile[0] = current_node->left_profile_child;
profile[1] = current_node->left_profile_self;
} else {
profile[0] = current_node->right_profile_child;
profile[1] = current_node->right_profile_self;
}
// Iterate over positions of the new alignment, filling in each column:
const std::size_t n = std::strlen(profile[0]);
const std::size_t child_aln_n = child_aln.r[0].sequence.length();
std::size_t j = 0, k = 0;
while (j < child_aln_n && k < n) {
// If the j-th symbol in the first row in the child alignment is equal to
// the k-th symbol in the present node's profile
if (child_aln.r[0].sequence[j] == profile[0][k]) {
r[0].sequence += profile[1][k];
for (z = 0; z < m; ++z) {
r[z + 1].sequence += child_aln.r[z].sequence[j];
}
++j;
++k;
} else if (child_aln.r[0].sequence[j] == SPACE) {
r[0].sequence += SPACE;
for (z = 0; z < m; ++z) {
r[z + 1].sequence += child_aln.r[z].sequence[j];
}
++j;
} else {
r[0].sequence += profile[1][k];
for (z = 0; z < m; ++z) {
r[z + 1].sequence += SPACE;
}
++k;
}
}
}
/********************************************************************
* Modified by RLC from:
* static Alignment *AlignAlignments(Alignment *a, Alignment *b);
*
* CONSTRUCTOR BUILDS AN ALIGNMENT FROM TWO ALIGNMENTS.
* THE FIRST ROW OF EACH ALIGNMENT
* IS CONSIDERED TO BE A PROFILE, AND MUST CONTAIN IDENTICAL
* CHARACTERS, WITH SPACES AT POSITIONS THAT ARE NOT NECESSARILY
* IDENTICAL.
*
* ARGUMENTS:
* a One of the alignments to align
* b The other alignment to align
**********************************************************************/
Alignment::Alignment(const Alignment& a, const Alignment& b) :
r(a.r.size() + b.r.size() - 1) // Make a new alignment
{
// Copy 'a' into the new alignment:
const std::size_t a_m = a.r.size();
std::size_t z;
for (z = 0; z < a_m; ++z) {
r[z].name = a.r[z].name;
}
// Copy 'b' into the new alignment:
const std::size_t aln_m = r.size();
for (; z < aln_m; ++z) {
r[z].name = b.r[z - a_m + 1].name;
}
// Iterate over the positions of the new alignment, filling in each column:
const std::size_t a_n = a.r[0].sequence.length();
const std::size_t b_n = b.r[0].sequence.length();
std::size_t j = 0, k = 0;
while (j < a_n && k < b_n) {
if ((a.r[0].sequence[j] != SPACE) && (a.r[0].sequence[j] == b.r[0].sequence[k])) {
// present position in 'a' and 'b' is same and not a blank
for (z = 0; z < a_m; ++z) {
r[z].sequence += a.r[z].sequence[j];
}
for (; z < aln_m; ++z) {
r[z].sequence += b.r[z - a_m + 1].sequence[k];
}
++j;
++k;
} else if (a.r[0].sequence[j] == SPACE) {
// 'a' has a space in the profile row, so we must insert spaces
// for the rows of 'b'.
for (z = 0; z < a_m; ++z) {
r[z].sequence += a.r[z].sequence[j];
}
for (; z < aln_m; ++z) {
r[z].sequence += SPACE;
}
++j;
} else {
// 'a' and 'b' differ in the profile row,
// we must select one to make the present
// column in the new alignment, and we select 'b'.
for (z = 0; z < a_m; ++z) {
r[z].sequence += SPACE;
}
for (; z < aln_m; ++z) {
r[z].sequence += b.r[z - a_m + 1].sequence[k];
}
++k;
}
}
}
/**** THE STRUCTS REPRESENTING SEQUENCES IN LIST FORM. USED BECAUSE IT
IS EASIER TO DO INDELS IN A LIST THAN AN ARRAY ****/
typedef struct SequenceNode_ {
char c; // Residue at this site
double rate; // Evolutionary rate at this site
int mark; // Marker indicating the site beside an indel
struct SequenceNode_ *prev; // Backward link
struct SequenceNode_ *next; // Forward link
} SequenceNode;
typedef struct SequenceList_ {
SequenceNode *head;
SequenceNode *tail;
int size;
} SequenceList;
void MemoryRequestFailure(char *function_name) {
fprintf(stderr, "ERROR %s: memory request failure\n", function_name);
exit(EXIT_FAILURE);
}
////////////////////////////////////////////////////////////////////
/// FUNCTIONS FOR READING AND CONSTRUCTING THE TREE
/******************************************************************
* FUNCTION TO GET THE NEXT TOKEN FROM THE STRING REPRESENTING THE
* TREE.
*
* ARGUMENTS:
* tree_string: (char **) the string (being parsed) representing the tree
* delimiters : (char *) the string representing the set of delimiters
*
* RETURN VALUE: * (char *) a character array containing the token,
* which may be a delimiter or a delimited string (e.g. a name)
******************************************************************/
static char *GetNextToken(char **tree_string, const char *delimiters) {
int i, j, delimiters_length;
char buffer[MAX_TOKEN_SIZE];
char *token;
/* Get the size of the set of delimiters */
delimiters_length = (int)strlen(delimiters);
/* Check to see if the token is a delimiter (a single character) */
for (j = 0; j < delimiters_length; j++)
if (**tree_string == delimiters[j]) {
token = (char *)malloc(sizeof(char));
if (token != NULL) { // This is for "splint"
*token = **tree_string;
(*tree_string)++; // Eat the input
return token;
}
else MemoryRequestFailure("GetNextToken()");
}
/* Since the token is not a delimiter, fill the buffer with all characters
up to, but not including, the next delimiter. */
memset(buffer, 0, MAX_TOKEN_SIZE * sizeof(char));
for (i = 0; **tree_string != '\0'; (*tree_string)++) {
for (j = 0; j < delimiters_length && (**tree_string != delimiters[j]); j++);
if (j != delimiters_length) break;
else buffer[i++] = **tree_string;
}
/* Allocte some memory to return, and copy the contents of
the buffer into it */
token = (char *)malloc((strlen(buffer) + 1) * sizeof(char));
if (token != NULL) {
strcpy(token, buffer);
}
else MemoryRequestFailure("GetNextToken()");
// Pass back the token
return token;
}
/****************************************************************
* FUNCTION TO ALLOCATE AND INITIALIZE TREE NODES.
*
* RETURN VALUE:
*(TreeNode *) this function returns a pointer to a newly allocated
* and Null-initialized tree node.
****************************************************************/
static TreeNode *MakeTreeNode() {
TreeNode *temp;
// Allocate the space
temp = (TreeNode *)malloc(sizeof(TreeNode));
if (temp != NULL) {
// Zero or NULL everything
temp->distance = 0.0;
temp->extinct = "N";
temp->name = NULL;
temp->sequence = NULL;
temp->rate = NULL;
temp->left = NULL;
temp->right = NULL;
temp->left_profile_child = NULL;
temp->left_profile_self = NULL;
temp->right_profile_child = NULL;
temp->right_profile_self = NULL;
}
else MemoryRequestFailure("MakeTreeNode()");
return temp;
}
/****************************************************************
* RECURSIVE FUNCTION TO FREE A TREE.
*
* ARGUMENTS:
* current_node (TreeNode *) this is a pointer to the root of the
* (sub)tree being freed
****************************************************************/
static void FreeTree(TreeNode *current_node) {
// Can't free it if it ain't been got...
if (current_node != NULL) {
// Recursively free the left subtree
if (current_node->left) {
FreeTree(current_node->left);
}
// Recursively free the right subtree
if (current_node->right) {
FreeTree(current_node->right);
}
// Free all the allocated fields
if (current_node->name != NULL)
free(current_node->name);
if (current_node->sequence != NULL)
free(current_node->sequence);
if (current_node->left_profile_child != NULL)
free(current_node->left_profile_child);
if (current_node->left_profile_self != NULL)
free(current_node->left_profile_self);
if (current_node->right_profile_child != NULL)
free(current_node->right_profile_child);
if (current_node->right_profile_self != NULL)
free(current_node->right_profile_self);
free(current_node);
}
}
/***********************************************************************
* RECURSIVE function that flags the nodes that are extinct in the case of
* internal node extinction
*
* ARGUMENTS
* tree_node
PN Dec 2007
***********************************************************************/
void FlagTree(TreeNode *current_node){
if(current_node->left) {
FlagTree(current_node->left);
FlagTree(current_node->right);
}
if (current_node->left && strstr(current_node->name, "Neg") != NULL){
sprintf(current_node->left->name, "%s %s", current_node->left->name, "Neg");
sprintf(current_node->left->name, "%s %s", current_node->left->name, "Neg");
}
}
/***********************************************************************
* RECURSIVE PARSING FUNCTION TO BUILD THE EVOLUTIONARY TREE FROM ITS
* STRING REPRESENTATION.
*
* ARGUMENTS
* tree_string (char **) a pointer to the character array holding
* the string representation of the tree
***********************************************************************/
static TreeNode *RecursiveParse(char **tree_string, char *ext) {
int label_flag = 1, distance_flag = 0;
double randomGamma, x; //PN Dec 2007
TreeNode * temp;
char * buffer;
// This will be returned as the root
temp = MakeTreeNode();
while ( ( buffer=GetNextToken(tree_string, "(),:;") ) ) {
if (*buffer == '(') {
// Parsing a descendant_list, push onto the stack
temp->left = RecursiveParse(tree_string, temp->extinct);
temp->right = RecursiveParse(tree_string, temp->extinct);
// label_flag = 1;
} else if ( (*buffer == ',') || (*buffer == ';') || (*buffer == ')') ) {
// If it was a ',' then we just finished a subtree, if it was a
// ';' then we just finished a tree. In both cases, we must return.
// Popping off the stack, finished parsing a descendant_list, subtree,
// or tree
// ZHUOZHI
{
// Special case, not covered in ":", the right node of the root,
// the right node of the right node of the root......
if ( temp->name == NULL ) {
temp->name = (char *)malloc(MAX_SEQUENCE_NAME_LENGTH * sizeof(char));
if (temp->name != NULL) {
sprintf(temp->name, "%s_%2.2d", "Internal", internal_count);
internal_count++;
} else {
MemoryRequestFailure ( "RecursiveParse()" );
}
}
}
// !!!!!!!!!!!!!!!!!!!!! WHAT DOES THIS ACTUALLY DO
free(buffer);
return temp;
} else if (*buffer == ':') {
// This token indicates that the next token will be a branch length.
// So we must have already processed a leaf label, a subtree, or an
// internal node label.
if (label_flag != 0) {
// We haven't just processed a label, so we must be at an internal
// node, and there must not be a label. So we make one up.
temp->name = (char *)malloc(MAX_SEQUENCE_NAME_LENGTH * sizeof(char));
if (temp->name != NULL) {
sprintf(temp->name, "%s_%2.2d", "Internal", internal_count);
// Increment the count of internal nodes
internal_count++;
label_flag = 0;
}
else MemoryRequestFailure("RecursiveParse()");
} else {
;
}
// Set the flag to indicate that we expect a number as the next token
distance_flag = 1;
}
else {
// If we are here, the token should be a label or distance
if (label_flag == 1) {
// This should be a label
temp->name = (char *)malloc(MAX_SEQUENCE_NAME_LENGTH * sizeof(char));
if (temp->name != NULL) {
strcpy(temp->name,buffer);
label_flag = 0;
} else MemoryRequestFailure("RecursiveParse()");
} else {
//PN Dec 2007
x = rndu();
if(VariableBranch == 0){
// This should be a distance
if(x <= BranchExtinction){
/* read in the branch length multiplied by a scale factor (program parameter)*/
temp->distance = 0;
temp->extinct = "Y";
sprintf(temp->name, "%s %s", temp->name, "Neg");
} else {
temp->distance = strtod(buffer, NULL) * TreeBranchScale;
}
} else {
randomGamma = rndgamma(VariableBranch);
// printf("%f\n",randomGamma);
if(x <= BranchExtinction){
temp->distance = 0;
temp->extinct = "Y"; //not fully implemented
sprintf(temp->name, "%s %s", temp->name, "Neg");
} else {
temp->distance = strtod(buffer, NULL) * TreeBranchScale * randomGamma;
}
}
distance_flag = 0;
}
}
}
// If we get here, something's wrong
fprintf(stderr, "ERROR RecursiveParse(): tree format problem\n");
exit(EXIT_FAILURE);
}
////////////////////////////////////////////////////////////////////////
/// INITIALIZATION ROUTINES
/************************************************************
* FUNCTION TO INITIALIZE THE PROTEIN MATRICES FROM PHYLIP
************************************************************/
void InitProtMats() {
int i, j, temp;
eigmat = (double *)malloc(20 * sizeof(double));
for (i = 0; i < 20; i++)
if (subModel == 0) eigmat[i] = pameigmat[i];
else if (subModel == 1) eigmat[i] = jtteigmat[i];
else eigmat[i] = pmbeigmat[i];
probmat = (double **)malloc(20 * sizeof(double *));
for (i = 0; i < 20; i++)
probmat[i] = (double *)malloc(20 * sizeof(double));
for (i = 0; i < 20; i++)
for (j= 0; j < 20; j++)
if (subModel == 0) probmat[i][j] = pamprobmat[i][j];
else if (subModel == 1) probmat[i][j] = jttprobmat[i][j];
else probmat[i][j] = pmbprobmat[i][j];
for(i = 0; i < 20; i++) {
temp = (int)(aaSequence[i]-'A');
rtoi[temp] = i;
itor[i] = aaSequence[i];
}
}
/*********************************************************************
* FUNCTION TO CALCULATE AMINO ACID FREQUENCIES BASED ON EIGMAT
*********************************************************************/
void MakeProtFreqs() {
int i, maxeig = 0;
for (i = 0; i < 20; i++)
if (eigmat[i] > eigmat[maxeig])
maxeig = i;
memcpy(freqaa, probmat[maxeig], 20 * sizeof(double));
for (i = 0; i < 20; i++)
freqaa[i] = fabs(freqaa[i]);
}
/*********************************************************************
* FUNCTION TO INITIALIZE THE TREE. OPENS THE TREE FILE, READS IN THE
* STRING REPRESENTATION, PARSES IT AND CONSTRUCTS THE TREE.
*
* RETURN VALUE:
* (TreeNode *) a pointer to the root of the initialized tree
*********************************************************************/
static TreeNode *InitTree() {
char *TreeString, *buffer, *temp;
int i, offset = 0, buffer_len;
FILE *TreeFile;
TreeNode *t;
if (!(TreeFile = fopen(TreeFileName, "r"))) {
fprintf ( stderr,
"ERROR InitTree(): cannot open tree file \"%s\"\n",
TreeFileName);
exit(EXIT_FAILURE);
}
// Allocate the buffer, which is temporary storage for individual lines
// in the tree file.
buffer = (char *)malloc(BUFFER_SIZE * sizeof(char));
// Allocate the tree string, which will contain the contents of the tree file
// without newlines or the EOF
TreeString = (char *)malloc(MAX_TREE_SIZE * sizeof(char));
if (buffer != NULL && TreeString != NULL) {
/* Grab input until the end of the file */
while ( fscanf(TreeFile, "%s\n", buffer ) != EOF) {
buffer_len = (int)strlen(buffer);
for (i = 0; i < buffer_len; i++)
TreeString[offset + i] = buffer[i];
offset += i;
}
// Free the buffer
free(buffer);
// Parse the tree
temp = TreeString; /* Need to do this because the RecursiveParse()
modifies the location where "tree" points */
// This is the recursive descent parser
t = RecursiveParse(&TreeString, NULL);
// Free the tree string before returning
free(temp);
{
// Set name for the root of the Tree, by ZHUOZHI
char * pe;
pe = (char *) malloc ( sizeof(char) * MAX_SEQUENCE_NAME_LENGTH );
if ( pe == NULL ) {
MemoryRequestFailure ( "InitTree()" );
} else {
strcpy ( pe, "InternalRoot" );
t->name = pe;
}
}
return t;
}
else MemoryRequestFailure("InitTree()");
}
/******************************************
*
*
******************************************/
static void InitTrueAlignmentFile() {
if (TrueAlignmentFileName) TrueAlignmentFile = fopen(TrueAlignmentFileName, "w");
else TrueAlignmentFile = stdout;
}
/**********************************************************************
* THIS FUNCTION INITIALIZES THE FASTA OUTPUT FILE. THE INITIALIZATION
* IS DONE HERE, AND NOT IN THE ONE FUNCTION THAT USES THAT FILE,
* BECAUSE THAT ONE FUNCTION IS RECURSIVE
*
* ARGUMENTS:
* temp_fasta_file_name (char *) The name of the file for output of the
* sequences in fasta format
**********************************************************************/
static void InitFastaFile(char *temp_fasta_file_name) {
if (FastaFileName != NULL) {
if ((FastaFile = fopen(temp_fasta_file_name, "w")) == NULL) {
fprintf(stderr, "ERROR InitFastaFile(): cannot open file \"%s\"\n", temp_fasta_file_name);
exit(EXIT_FAILURE);
}
}
else FastaFile = stdout;
}
//PN March 2005
/**********************************************************************
* THIS FUNCTION INITIALIZES THE Phylip OUTPUT FILE. THE INITIALIZATION
* IS DONE HERE, AND NOT IN THE ONE FUNCTION THAT USES THAT FILE,
* BECAUSE THAT ONE FUNCTION IS RECURSIVE
*
* ARGUMENTS:
* temp_phylip_file_name (char *) The name of the file for output of the
* sequences in fasta format
**********************************************************************/
static void InitPhylipFile(char *temp_phylip_file_name) {
if (PhylipFileName != NULL) {
if ((PhylipFile = fopen(temp_phylip_file_name, "w")) == NULL) {
fprintf(stderr, "ERROR InitFastaFile(): cannot open file \"%s\"\n", temp_phylip_file_name);
exit(EXIT_FAILURE);
}
}
//else PhylipFile = stdout;
}
/*****************************************************************
* INITIALIZES A VECTOR CONTAINING THE CUMULATIVE DENSITY FOR THE
* ALPHABET. THIS VECTOR IS USED TO CONVERT A UNIFORMLY RANDOM
* VALUE IN [0,1] INTO A SYMBOL THAT IS RANDOM ACCORDING TO THE
* BACKGROUND FREQUENCY
***************************************************************/
static void InitSymbolCumulativeDensity() {
int i;
SymbolCumulativeDensity[0] = 0.0;
for (i = 1; i <= 19; i++) {
SymbolCumulativeDensity[i] =
SymbolCumulativeDensity[i-1] + freqaa[i-1];
}
SymbolCumulativeDensity[20] = 1.0;
}
/////////////////////////////
/////////////////////////////
/// ///
/// MUTATION ROUTINES ///
/// ///
/////////////////////////////
/////////////////////////////
/********************************************************************
* WRAPPER FUNCTION TO GET A RANDOM GAMMA RATE.
*
* ARGUMENTS:
* a (double) The alpha parameter to the Gamma distribution
* b (double) The beta parameter to the Gamma distribution
* a controls more
*
* RETURN VALUE:
* (double) A value chosen at random from the Gamma distribution with
* parameters 'a' and 'b'.
********************************************************************/
static double RandomGammaRate(double a, double b) {
if (a<0) {
return 1.0;
}
return rndgamma(a);
}
/*********************************************************************
* FUNCTION TO OBTAIN A RANDOM SYMBOL ACCORDING TO THE BACKGROUND
* DISTRIBUTION. THE FUNCTION DOES A BINARY SEARCH ON THE VECTOR OF
* CUMULATIVE DENSITIES FOR EACH SYMBOL
*
* RETURN VALUE:
* (char) A symbol chosen at random from the background distribution
*********************************************************************/
static char RandomSymbol() {
int mid, low = 0, high = 20;
double x;
int y;
// Get a uniformly random number in [0,1]
x = rndu();
// Do a binary search in the cumulative density vector
// to find the symbol corresponding to the random number
while (1) {
mid = (low+high)/2;
if (SymbolCumulativeDensity[mid] <= x)
if (SymbolCumulativeDensity[mid+1] > x)
return itor[mid];
else low = mid;
else high = mid;
}
return '\0'; /* This will also never happen */
}
/// ET May 2007
static char *ReadRootSequence() {
char *RootString, *buffer, *temp;
int i, offset = 0, buffer_len;
FILE *RootSequenceFile;
int size = 0;
if (!(RootSequenceFile = fopen(RootSequenceFileName, "r"))) {
fprintf ( stderr,
"ERROR ReadRoot(): cannot open root sequence file \"%s\"\n",
RootSequenceFileName);
exit(EXIT_FAILURE);
}
// Allocate the buffer, which is temporary storage for individual lines
buffer = (char *)malloc(BUFFER_SIZE * sizeof(char));
// Allocate the root string, which will contain the contents of the tree file
// without newlines or the EOF
RootString = (char *)malloc(MAX_TREE_SIZE * sizeof(char));
if (buffer != NULL && RootString != NULL) {
/* Grab input until the end of the file */
while ( fscanf(RootSequenceFile, "%s\n", buffer ) != EOF) {
buffer_len = (int)strlen(buffer);
for (i = 0; i < buffer_len; i++)
RootString[offset + i] = buffer[i];
offset += i;
}
size=(int)strlen(buffer);
RootString[size] = '\0';
return RootString;
}
else MemoryRequestFailure("RootSequence()");
}
// RLC's implementation of ReadGapDist(const char* distfile):
void ReadGapDist(const char* distfile)
{
for (int i = 0; i < max_indel_length; ++i) {
IndelLengthFreq[i] = 0.0;
}
std::ifstream inputFile(distfile);
if (inputFile.is_open()) {
double val;
int count = 0;
inputFile >> val;
while (inputFile && count < max_indel_length) {
IndelLengthFreq[count++] = val;
inputFile >> val;
}
inputFile.close();
} else {
printf("Error opening %s\n", distfile);
std::exit(1);
}
}
void ReadCorrelatedPairs(const char* CorrelFile)
{
std::ifstream inputFile(CorrelFile);
string tempLine;
if (inputFile.is_open()) {
while (getline(inputFile,tempLine,'\n')) {
stringstream ss(tempLine);
string temp;
int l=0;
int i=0;
int j=0;
double c=0;
while (getline(ss, temp, '\t')){
stringstream tmpstring(temp);
if (l==0) { tmpstring >> i ;}
else if (l==1){ tmpstring >> j ;}
else if (l==2) { tmpstring >> c ; }
l++;
}
Correlation[i-1].pos=j-1;
Correlation[j-1].pos=i-1;
Correlation[i-1].value=c;
Correlation[j-1].value=c;
}
inputFile.close();
} else {
printf("Error opening %s\n", CorrelFileName);
std::exit(1);
}
}
/****************************************************************
* GET A RANDOM SEQUENCE ACCORDING TO THE BACKGROUND DISTRIBUTION.
* THIS FUNCTION ALLOCATES MEMORY, SO REMEMBER TO FREE IT.
*
* ARGUMENTS:
* size (int) The size of the desired sequence
*
* RETURN VALUE:
* (char *) A pointer to the newly allocated character array
* containing the sequence.
****************************************************************/
static char *RandomSequence(int size) {
char *s;
int i;