-
Notifications
You must be signed in to change notification settings - Fork 1
/
treesub.c
3288 lines (2875 loc) · 113 KB
/
treesub.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2022 Anna Nagel
Originally modified from PAML version 4.9 by Ziheng Yang
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 3 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 <https://www.gnu.org/licenses/>.
*/
/* treesub.c
subroutines that operates on trees, inserted into other programs
such as baseml, basemlg, codeml, and pamp.
*/
#include "mcmctree.h"
#include "tools.h"
#include "treesub.h"
#define MCMCTREE 1
extern char BASEs[], *EquateBASE[], AAs[], BINs[], CODONs[][4], nChara[], CharaMap[][64];
extern int NFunCall;
extern char BASEs[];
extern double PjumpOptimum;
extern int noisy;
extern int LASTROUND;
extern double _rateSite;
extern char *fossils[];
extern int npfossils[];
#ifdef MCMCTREE
#define REALSEQUENCE
#define NODESTRUCTURE
#define LFUNCTIONS
#endif
#ifdef REALSEQUENCE
int hasbase(char *str)
{
char *p = str, *eqdel = ".-?";
while (*p)
if (*p == eqdel[0] || *p == eqdel[1] || *p == eqdel[2] || isalpha(*p++))
return(1);
return(0);
}
int GetSeqFileType(FILE *fseq, int *NEXUSseq);
int IdenticalSeqs(void);
void RemoveEmptySequences(void);
int GetSeqFileType(FILE *fseq, int *format)
{
/* NEXUSstart="begin data" and NEXUSdata="matrix" identify nexus file format.
Modify if necessary.
format: 0: alignment; 1: fasta; 2: nexus.
*/
int lline = 1000, ch, aligned;
char fastastarter = '>';
char line[1000], *NEXUSstart = "begin data", *NEXUSdata = "matrix", *p;
char *ntax = "ntax", *nchar = "nchar";
while (isspace(ch = fgetc(fseq)))
;
ungetc(ch, fseq);
if (ch == fastastarter) {
*format = 1;
ScanFastaFile(fseq, &com.ns, &com.ls, &aligned);
if (aligned)
return(0);
else
error2("The seq file appears to be in fasta format, but not aligned?");
}
if (fscanf(fseq, "%d%d", &com.ns, &com.ls) == 2) {
*format = 0; return(0);
}
*format = 2;
printf("\nseq file is not paml/phylip format. Trying nexus format.");
for (; ; ) {
if (fgets(line, lline, fseq) == NULL) error2("seq err1: EOF");
strcase(line, 0);
if (strstr(line, NEXUSstart)) break;
}
for (; ; ) {
if (fgets(line, lline, fseq) == NULL) error2("seq err2: EOF");
strcase(line, 0);
if ((p = strstr(line, ntax)) != NULL) {
while (*p != '=') { if (*p == 0) error2("seq err"); p++; }
sscanf(p + 1, "%d", &com.ns);
if ((p = strstr(line, nchar)) == NULL) error2("expect nchar");
while (*p != '=') { if (*p == 0) error2("expect ="); p++; }
sscanf(p + 1, "%d", &com.ls);
break;
}
}
/* printf("\nns: %d\tls: %d\n", com.ns, com.ls); */
for (; ; ) {
if (fgets(line, lline, fseq) == NULL) error2("seq err1: EOF");
strcase(line, 0);
if (strstr(line, NEXUSdata)) break;
}
return(0);
}
int PopupNEXUSComment(FILE *fseq)
{
int ch, comment1 = ']';
for (; ; ) {
ch = fgetc(fseq);
if (ch == EOF) error2("expecting ]");
if (ch == comment1) break;
if (noisy) putchar(ch);
}
return(0);
}
#if(MCMCTREE)
int ReadMorphology(FILE *fout, FILE *fin, int locus)
{
int i, j;
char line[1024], str[64];
if ((data.zmorph[locus][0] = (double*)malloc((com.ns * 2 - 1)*com.ls * sizeof(double))) == NULL)
error2("oom zmorph");
if ((data.Rmorph[locus] = (double*)malloc(com.ls*com.ls * sizeof(double))) == NULL)
error2("oom Rmorph");
printf("Locus %d has morphological alignment\n", locus + 1);
for (i = 1; i < com.ns * 2 - 1; i++) {
data.zmorph[locus][i] = data.zmorph[locus][0] + i*com.ls;
}
for (i = 0; i < com.ns; i++) {
fscanf(fin, "%s", com.spname[i]);
printf("Reading data for species #%2d: %s \r", i + 1, com.spname[i]);
for (j = 0; j < com.ls; j++)
fscanf(fin, "%lf", &data.zmorph[locus][i][j]);
}
for (i = 0; i < com.ns; i++) {
fprintf(fout, "%-10s ", com.spname[i]);
for (j = 0; j < com.ls; j++)
fprintf(fout, " %8.5f", data.zmorph[locus][i][j]);
FPN(fout);
}
#if(0)
fscanf(fin, "%s", str);
fgets(line, 1024, fin);
i = j = -1;
if (strstr("Correlation", str)) {
for (i = 0; i < com.ls; i++) {
for (j = 0; j < com.ls; j++)
if (fscanf(fin, "%lf", &data.Rmorph[locus][i*com.ls + j]) != 1) break;
if (j < com.ls) break;
}
}
if (i != com.ls || j != com.ls) {
printf("\ndid not find a good R matrix. Setting it to identity matrix I.\n");
for (i = 0; i < com.ls; i++)
for (j = 0; j < com.ls; j++)
data.Rmorph[locus][i*com.ls + j] = (i == j);
}
#endif
return(0);
}
#endif
int ReadSeq(FILE *fout, FILE *fseq, int cleandata, int locus)
{
/* read in sequence, translate into protein (CODON2AAseq), and
This counts ngene but does not initialize lgene[].
It also codes (transforms) the sequences.
com.seqtype: 0=nucleotides; 1=codons; 2:AAs; 3:CODON2AAs; 4:BINs
com.pose[] is used to store gene or site-partition labels.
ls/3 gene marks for codon sequences.
char opt_c[]="GIPM";
G:many genes; I:interlaved format; P:patterns; M:morphological characters
Use cleandata=1 to clean up ambiguities. In return, com.cleandata=1 if the
data are clean or are cleaned, and com.cleandata=0 is the data are unclean.
*/
char *p, *p1, eq = '.', comment0 = '[', *line;
int format = 0; /* 0: paml/phylip, 1: fasta; 2: NEXUS/nexus */
int i, j, k, ch, noptline = 0, lspname = LSPNAME, miss = 0, nb;
int lline = 10000, lt[NS], igroup, Sequential = 1, basecoding = 0;
int n31 = (com.seqtype == CODONseq || com.seqtype == CODON2AAseq ? 3 : 1);
int gap = (n31 == 3 ? 3 : 10), nchar = (com.seqtype == AAseq ? 20 : 4);
int h, b[3] = { 0 };
char *pch = ((com.seqtype <= 1 || com.seqtype == CODON2AAseq) ? BASEs : (com.seqtype == 2 ? AAs : BINs));
char str[4] = " ", tmp[32];
char *NEXUSend = "end;";
double lst;
#if(MCMCTREE)
data.datatype[locus] = com.seqtype;
#endif
str[0] = 0; h = -1; b[0] = -1; /* avoid warning */
com.readpattern = 0;
if (com.seqtype == 4) error2("seqtype==BINs, check with author");
if (noisy >= 9 && (com.seqtype <= CODONseq || com.seqtype == CODON2AAseq)) {
puts("\n\nAmbiguity character definition table:\n");
for (i = 0; i < (int)strlen(BASEs); i++) {
nb = (int)strlen(EquateBASE[i]);
printf("%c (%d): ", BASEs[i], nb);
for (j = 0; j < nb; j++) printf("%c ", EquateBASE[i][j]);
FPN(F0);
}
}
GetSeqFileType(fseq, &format);
if (com.ns > NS) error2("too many sequences.. raise NS?");
if (com.ls%n31 != 0) {
printf("\n%d nucleotides, not a multiple of 3!", com.ls); exit(-1);
}
if (noisy) printf("ns = %d \tls = %d\n", com.ns, com.ls);
for (j = 0; j < com.ns; j++) {
if (com.spname[j]) free(com.spname[j]);
com.spname[j] = (char*)malloc((lspname + 1) * sizeof(char));
for (i = 0; i < lspname + 1; i++) com.spname[j][i] = 0;
if ((com.z[j] = (unsigned char*)realloc(com.z[j], com.ls * sizeof(unsigned char))) == NULL)
error2("oom z");
}
com.rgene[0] = 1; com.ngene = 1;
lline = max2(lline, com.ls / n31*(n31 + 1) + lspname + 50);
if ((line = (char*)malloc(lline * sizeof(char))) == NULL) error2("oom line");
/* first line */
if (format == 0) {
if (!fgets(line, lline, fseq)) error2("ReadSeq: first line");
com.readpattern = (strchr(line, 'P') || strchr(line, 'p'));
#if(MCMCTREE)
if (strchr(line, 'M') || strchr(line, 'm')) {
data.datatype[locus] = MORPHC;
data.zpopvar[locus] = 0; data.ldetRm[locus] = 0; /* MdR */
sscanf(line, "%s %lf %lf", tmp, &data.zpopvar[locus], &data.ldetRm[locus]); /* MdR */
printf("MdR: got %f %f, locus: %d\n", data.zpopvar[locus], data.ldetRm[locus], locus);
/* TODO: Do some error checking. MdR. */
}
#endif
}
#if(MCMCTREE)
if (data.datatype[locus] == MORPHC) { /* morhpological data */
ReadMorphology(fout, fseq, locus);
return(0);
}
else
#endif
if (!com.readpattern) {
if (com.pose) free(com.pose);
if ((com.pose = (int*)malloc(com.ls / n31 * sizeof(int))) == NULL)
error2("oom pose");
for (j = 0; j < com.ls / n31; j++) com.pose[j] = 0; /* gene #1, default */
}
else {
if (com.pose) free(com.pose);
com.pose = NULL;
}
if (format) goto readseq;
for (j = 0; j < lline && line[j] && line[j] != '\n'; j++) {
if (!isalnum(line[j])) continue;
line[j] = (char)toupper(line[j]);
switch (line[j]) {
case 'G': noptline++; break;
case 'C': basecoding = 1; break;
case 'S': Sequential = 1; break;
case 'I': Sequential = 0; break;
case 'P': break; /* already dealt with. */
default:
printf("\nBad option '%c' in first line of seqfile\n", line[j]);
exit(-1);
}
}
if (strchr(line, 'C')) { /* protein-coding DNA sequences */
if (com.seqtype == 2) error2("option C?");
if (com.seqtype == 0) {
if (com.ls % 3 != 0 || noptline < 1) error2("option C?");
com.ngene = 3;
for (i = 0; i < 3; i++) com.lgene[i] = com.ls / 3;
}
noptline--;
}
/* option lines */
for (j = 0; j < noptline; j++) {
for (ch = 0; ; ) {
ch = (char)fgetc(fseq);
if (ch == comment0)
PopupNEXUSComment(fseq);
if (isalnum(ch)) break;
}
ch = (char)toupper(ch);
switch (ch) {
case ('G'):
if (basecoding) error2("sequence data file: incorrect option format, use GC?\n");
#if(defined MCMCTREE || defined BPP)
error2("sequence data file: option G should not be used.");
#endif
if (fscanf(fseq, "%d", &com.ngene) != 1) error2("expecting #gene here..");
if (com.ngene > NGENE) error2("raise NGENE?");
fgets(line, lline, fseq);
if (!blankline(line)) { /* #sites in genes on the 2nd line */
for (i = 0, p = line; i < com.ngene; i++) {
while (*p && !isalnum(*p)) p++;
if (sscanf(p, "%d", &com.lgene[i]) != 1) break;
while (*p && isalnum(*p)) p++;
}
/* if ngene is large and some lgene is on the next line */
for (; i < com.ngene; i++)
if (fscanf(fseq, "%d", &com.lgene[i]) != 1) error2("EOF at lgene");
for (i = 0, k = 0; i < com.ngene; i++)
k += com.lgene[i];
if (k != com.ls / n31) {
matIout(F0, com.lgene, 1, com.ngene);
printf("\n%6d != %d", com.ls / n31, k);
puts("\nOption G: total length over genes is not correct");
if (com.seqtype == 1) {
puts("Note: gene length is in number of codons.");
}
puts("Sequence length in number of nucleotides.");
exit(-1);
}
if (!com.readpattern)
for (i = 0, k = 0; i < com.ngene; k += com.lgene[i], i++)
for (j = 0; j < com.lgene[i]; j++)
com.pose[k + j] = i;
}
else { /* site marks on later line(s) */
if (com.readpattern)
error2("option PG: use number of patterns in each gene and not site marks");
for (k = 0; k < com.ls / n31; ) {
if (com.ngene > 9) fscanf(fseq, "%d", &ch);
else {
do ch = fgetc(fseq); while (!isdigit(ch));
ch = ch - (int)'1' + 1; /* assumes 1,2,...,9 are consecutive */
}
if (ch<1 || ch>com.ngene)
{
printf("\ngene mark %d at %d?\n", ch, k + 1); exit(-1);
}
com.pose[k++] = ch - 1;
}
if (!fgets(line, lline, fseq)) error2("sequence file, gene marks");
}
break;
default:
printf("Bad option '%c' in option lines in seqfile\n", line[0]);
exit(-1);
}
}
readseq:
/* read sequence */
if (Sequential) { /* sequential */
if (noisy) printf("Reading sequences, sequential format..\n");
for (j = 0; j < com.ns; j++) {
lspname = LSPNAME;
for (i = 0; i < 2 * lspname; i++) line[i] = '\0';
if (!fgets(line, lline, fseq)) error2("EOF?");
if (blankline(line)) {
if (PopEmptyLines(fseq, lline, line))
{
printf("error in sequence data file: empty line (seq %d)\n", j + 1); exit(-1);
}
}
p = line + (line[0] == '=' || line[0] == '>');
while (isspace(*p)) p++;
if ((ch = (int)(strstr(p, " ") - p)) < lspname && ch > 0) lspname = ch;
strncpy(com.spname[j], p, lspname);
k = (int)strlen(com.spname[j]);
p += (k < lspname ? k : lspname);
for (; k > 0; k--) /* trim spaces */
if (!isgraph(com.spname[j][k])) com.spname[j][k] = 0;
else break;
if (noisy >= 2) printf("Reading seq #%2d: %s %s", j + 1, com.spname[j], (noisy > 3 ? "\n" : "\n"));
for (k = 0; k < com.ls; p++) {
while (*p == '\n' || *p == '\0') {
p = fgets(line, lline, fseq);
if (p == NULL)
{
printf("\nEOF at site %d, seq %d\n", k + 1, j + 1); exit(-1);
}
}
*p = (char)toupper(*p);
if ((com.seqtype == BASEseq || com.seqtype == CODONseq) && *p == 'U')
*p = 'T';
p1 = strchr(pch, *p);
if (p1 && p1 - pch >= nchar)
miss = 1;
if (*p == eq) {
if (j == 0) error2("Error in sequence data file: . in 1st seq.?");
com.z[j][k] = com.z[0][k]; k++;
}
else if (p1)
com.z[j][k++] = *p;
else if (isalpha(*p)) {
printf("\nError in sequence data file: %c at %d seq %d.\n", *p, k + 1, j + 1);
puts("Make sure to separate the sequence from its name by 2 or more spaces.");
exit(0);
}
else if (*p == (char)EOF) error2("EOF?");
} /* for(k) */
if (strchr(p, '\n') == NULL) /* pop up line return */
while ((ch = fgetc(fseq)) != '\n' && ch != EOF);
} /* for (j,com.ns) */
}
else { /* interlaved */
if (noisy) printf("Reading sequences, interlaved format..\n");
FOR(j, com.ns) lt[j] = 0; /* temporary seq length */
for (igroup = 0; ; igroup++) {
/*
printf ("\nreading block %d ", igroup+1); matIout(F0,lt,1,com.ns);*/
FOR(j, com.ns) if (lt[j] < com.ls) break;
if (j == com.ns) break;
FOR(j, com.ns) {
if (!fgets(line, lline, fseq)) {
printf("\nerr reading site %d, seq %d group %d\nsites read in each seq:",
lt[j] + 1, j + 1, igroup + 1);
error2("EOF?");
}
if (!hasbase(line)) {
if (j) {
printf("\n%d, seq %d group %d", lt[j] + 1, j + 1, igroup + 1);
error2("empty line.");
}
else
if (PopEmptyLines(fseq, lline, line) == -1) {
printf("\n%d, seq %d group %d", lt[j] + 1, j + 1, igroup + 1);
error2("EOF?");
}
}
p = line;
if (igroup == 0) {
lspname = LSPNAME;
while (isspace(*p)) p++;
if ((ch = (int)(strstr(p, " ") - p)) < lspname && ch > 0)
lspname = ch;
strncpy(com.spname[j], p, lspname);
k = (int)strlen(com.spname[j]);
p += (k < lspname ? k : lspname);
for (; k > 0; k--) /* trim spaces */
if (!isgraph(com.spname[j][k]))
com.spname[j][k] = 0;
else
break;
if (noisy >= 2) printf("Reading seq #%2d: %s \n", j + 1, com.spname[j]);
}
for (; *p && *p != '\n'; p++) {
if (lt[j] == com.ls) break;
*p = (char)toupper(*p);
if ((com.seqtype == BASEseq || com.seqtype == CODONseq) && *p == 'U')
*p = 'T';
p1 = strchr(pch, *p);
if (p1 && p1 - pch >= nchar)
miss = 1;
if (*p == eq) {
if (j == 0) {
printf("err: . in 1st seq, group %d.\n", igroup);
exit(-1);
}
com.z[j][lt[j]] = com.z[0][lt[j]];
lt[j]++;
}
else if (p1)
com.z[j][lt[j]++] = *p;
else if (isalpha(*p)) {
printf("\nerr: unrecognised character %c at %d seq %d block %d.",
*p, lt[j] + 1, j + 1, igroup + 1);
exit(-1);
}
else if (*p == (char)EOF) error2("EOF");
} /* for (*p) */
} /* for (j,com.ns) */
if (noisy > 2) {
printf("\nblock %3d:", igroup + 1);
for (j = 0; j < com.ns; j++) printf(" %6d", lt[j]);
}
} /* for (igroup) */
}
if (format == 2) { /* NEXUS format: pop up extra lines until "end;" */
for (; ; ) {
if (fgets(line, lline, fseq) == NULL) error2("seq err1: EOF");
strcase(line, 0);
if (strstr(line, NEXUSend)) break;
}
}
free(line);
/*** delete empty sequences ******************/
#if(0)
{ int ns1 = com.ns, del[100] = { 0 };
for (i = 0; i < com.ns; i++) {
for (h = 0; h < com.ls; h++) if (com.z[i][h] != '?') break;
if (h == com.ls) {
del[i] = 1;
ns1--;
}
}
fprintf(fnew, "\n\n%4d %6d\n", ns1, com.ls);
for (i = 0; i < com.ns; i++) {
if (!del[i]) {
fprintf(fnew, "\n%-40s ", com.spname[i]);
for (h = 0; h < com.ls; h++) fprintf(fnew, "%c", com.z[i][h]);
}
}
fflush(fnew);
}
#endif
if (!miss)
com.cleandata = 1;
else if (cleandata) { /* forced removal of ambiguity characters */
if (noisy > 2) puts("\nSites with gaps or missing data are removed.");
if (fout) {
fprintf(fout, "\nBefore deleting alignment gaps\n");
fprintf(fout, " %6d %6d\n", com.ns, com.ls);
printsma(fout, com.spname, com.z, com.ns, com.ls, com.ls, gap, com.seqtype, 0, 0, NULL);
}
RemoveIndel();
if (fout) fprintf(fout, "\nAfter deleting gaps. %d sites\n", com.ls);
}
if (fout && !com.readpattern) {/* verbose=1, listing sequences again */
fprintf(fout, " %6d %6d\n", com.ns, com.ls);
printsma(fout, com.spname, com.z, com.ns, com.ls, com.ls, gap, com.seqtype, 0, 0, NULL);
}
if (n31 == 3) com.ls /= n31;
/* IdenticalSeqs(); */
if (noisy >= 2) printf("\nSequences read..\n");
if (com.ls == 0) {
puts("no sites. Got nothing to do");
return(1);
}
#if (defined MCMCTREE)
/* Check and remove empty sequences. */
if (com.cleandata == 1)
RemoveEmptySequences();
#endif
/***** GIBBON, 2017.10.8 **/
/* return(0); */
if (!com.readpattern) {
PatternWeight();
}
else { /* read pattern counts */
com.npatt = com.ls;
if ((com.fpatt = (double*)realloc(com.fpatt, com.npatt * sizeof(double))) == NULL)
error2("oom fpatt");
for (h = 0, lst = 0; h < com.npatt; h++) {
fscanf(fseq, "%lf", &com.fpatt[h]);
lst += com.fpatt[h];
if (com.fpatt[h]<0 || com.fpatt[h]>1e66)
printf("fpatth[%d] = %.6g\n", h + 1, com.fpatt[h]);
}
if (lst > 1.00001) {
com.ls = (int)lst;
if (noisy) printf("\n%d site patterns read, %d sites\n", com.npatt, com.ls);
}
if (com.ngene == 1) {
com.lgene[0] = com.ls;
com.posG[0] = 0;
com.posG[1] = com.npatt;
}
else {
for (j = 0, com.posG[0] = 0; j < com.ngene; j++)
com.posG[j + 1] = com.posG[j] + com.lgene[j];
for (j = 0; j < com.ngene; j++) {
com.lgene[j] = (j == 0 ? 0 : com.lgene[j - 1]);
for (h = com.posG[j]; h < com.posG[j + 1]; h++)
com.lgene[j] += (int)com.fpatt[h];
}
}
}
EncodeSeqs();
if (fout) {
fprintf(fout, "\nPrinting out site pattern counts\n\n");
printPatterns(fout);
if (com.verbose >= 2) {
fprintf(fout, "\nSite-to-pattern map: ");
for (i = 0; i < com.ls; i++)
fprintf(fout, " %2d", com.pose[i] + 1);
fprintf(fout, "\n");
}
}
return (0);
}
void RemoveEmptySequences(void)
{
/* this removes empty sequences (? or - only) and adjust com.ns
*/
int j, h, nsnew;
char emptyseq[NS];
for (j = 0; j < com.ns; j++) {
emptyseq[j] = 1;
for (h = 0; h < com.ls*(com.seqtype == 1 ? 3 : 1); h++)
if (com.z[j][h] != '?' && com.z[j][h] != '-') {
emptyseq[j] = 0;
break;
}
}
for (j = 0, nsnew = 0; j < com.ns; j++) {
if (emptyseq[j]) {
printf("seq #%3d: %-30s is removed\n", j + 1, com.spname[j]);
free(com.z[j]);
free(com.spname[j]);
continue;
}
com.z[nsnew] = com.z[j];
com.spname[nsnew] = com.spname[j];
nsnew++;
}
for (j = nsnew; j < com.ns; j++) {
com.z[j] = NULL;
com.spname[j] = NULL;
}
com.ns = nsnew;
if (com.ns <= 0)
error2("\nThis locus has nothing left after empty sequences are removed. Use cleandata = 0.\n");
}
int printPatterns(FILE *fout)
{
int j, h, n31 = (com.seqtype == CODONseq || com.seqtype == CODON2AAseq ? 3 : 1);
int gap = (n31 == 3 ? 3 : 10); //, n=(com.seqtype==AAseq?20:4);
fprintf(fout, "\n%10d %10d P", com.ns, com.npatt*n31);
if (com.ngene > 1) {
fprintf(fout, " G\nG %d ", com.ngene);
for (j = 0; j < com.ngene; j++)
fprintf(fout, "%7d", com.posG[j + 1] - com.posG[j]);
}
FPN(fout);
if (com.seqtype == 1 && com.cleandata) {
; /* nothing is printed out for yn00, as the coding is different. */
}
else
printsma(fout, com.spname, com.z, com.ns, com.npatt, com.npatt, gap, com.seqtype, 1, 0, NULL);
if (com.ls > 1.0001) {
fprintf(fout, "\n");
for (h = 0; h < com.npatt; h++) {
fprintf(fout, " %4.0f", com.fpatt[h]);
if ((h + 1) % 15 == 0) FPN(fout);
}
fprintf(fout, "\n\n");
}
return(0);
}
void EncodeSeqs(void)
{
/* This encodes sequences and set up com.TipMap[][], called after sites are collapsed
into patterns.
*/
int n = com.ncode, nA, is, h, i, j, k, ic, indel = 0, ch, b[3];
char *pch = ((com.seqtype == 0 || com.seqtype == 1) ? BASEs : (com.seqtype == 2 ? AAs : BINs));
unsigned char c[4] = "", str[4] = " ";
if (com.seqtype != 1) {
for (is = 0; is < com.ns; is++) {
for (h = 0; h < com.npatt; h++) {
ch = com.z[is][h];
com.z[is][h] = (char)(k = (int)(strchr(pch, ch) - pch));
if (k < 0) {
printf("strange character %c in seq %d site %d\n", ch, is + 1, h + 1);
exit(-1);
}
}
}
}
}
int print1site(FILE*fout, int h)
{
/* This print out one site in the sequence data, com.z[]. It may be the h-th
site in the original data file or the h-th pattern. The data are coded.
naa > 1 if the codon codes for more than one amino acid.
*/
char *pch = (com.seqtype == 0 ? BASEs : (com.seqtype == 2 ? AAs : BINs));
char compatibleAAs[20] = "";
int n = com.ncode, i, b, aa = 0;
for (i = 0; i < com.ns; i++) {
b = com.z[i][h];
if (com.seqtype == 0 || com.seqtype == 2)
fprintf(fout, "%c", pch[b]);
}
return(0);
}
void SetMapAmbiguity(int seqtype, int ModelAA2Codon)
{
/* This sets up CharaMap, the map from the ambiguity characters to resolved characters.
*/
int n = com.ncode, nc, i, j, i0, i1, i2, nb[3], ib[3][4], iaa, ic;
char *pch = (seqtype == 0 ? BASEs : (seqtype == 2 ? AAs : BINs));
char *pbases = (seqtype == 0 ? BASEs : NULL);
char **pEquateBASE = (seqtype == 0 ? EquateBASE : NULL);
char debug = 0;
for (j = 0; j < n; j++) { /* basic characters, coded according to the definition in pch. */
nChara[j] = (char)1;
CharaMap[j][0] = (char)j;
}
if (seqtype != 1 && ModelAA2Codon == 0) { /* nucleotides or amino acids */
for (j = n, pch += n; *pch; j++, pch++) {
if (com.seqtype == 0 || com.seqtype == 5) { /* ambiguities are allowed for those 2 types */
nChara[j] = (char)strlen(pEquateBASE[j]);
for (i = 0; i < nChara[j]; i++)
CharaMap[j][i] = (char)(strchr(pbases, pEquateBASE[j][i]) - pbases);
}
else { /* for non-nucleotide characters, ambiguity characters must be ? or -. */
nChara[j] = (char)n;
for (i = 0; i < n; i++)
CharaMap[j][i] = (char)i;
}
if (debug) {
printf("character %c (%d): ", pbases[j], nChara[j]);
for (i = 0; i < nChara[j]; i++)
printf("%c", pbases[(int)CharaMap[j][i]]);
printf("\n");
}
}
}
}
int PatternWeight(void)
{
/* This collaps sites into patterns, for nucleotide, amino acid, or codon sequences.
Site patterns are represented by 0-ended character strings. The code adds 1 to the character
during transposing so that it works for both unoded and coded data.
com.pose[i] has labels for genes as input and maps sites to patterns in return.
com.fpatt has site-pattern counts.
This deals with multiple genes/partitions, and uses com.ngene, com.lgene[], com.posG[] etc.
Sequences z[ns][ls] are copied into patterns zt[ls*lpatt], and bsearch is used
twice to avoid excessive copying of com.fpatt[] and com.pose[], the first round to count
npatt and generate the site patterns and the second round to generate fpatt[] & com.pose[].
*/
int maxnpatt = com.ls, h, ip, l, u, j, k, same, ig, *poset;
// int gap = (com.seqtype==CODONseq ? 3 : 10);
int n31 = (com.seqtype == CODONseq ? 3 : 1);
int lpatt = com.ns*n31 + 1; /* extra 0 used for easy debugging, can be voided */
int *p2s; /* point patterns to sites in zt */
char timestr[36];
unsigned char *p, *zt;
double nc = (com.seqtype == 1 ? 64 : com.ncode) + !com.cleandata + 1;
int debug = 0;
/* (A) Collect and sort patterns. Get com.npatt, com.lgene, com.posG.
Move sequences com.z[ns][ls] into sites zt[ls*lpatt].
Use p2s to map patterns to sites in zt to avoid copying.
*/
if (noisy) printf("Counting site patterns.. %s\n", printtime(timestr));
if ((com.seqtype == 1 && com.ns < 5) || (com.seqtype != 1 && com.ns < 7))
maxnpatt = (int)(pow(nc, (double)com.ns) + 0.5) * com.ngene;
if (maxnpatt > com.ls) maxnpatt = com.ls;
p2s = (int*)malloc(maxnpatt * sizeof(int));
zt = (char*)malloc(com.ls*lpatt * sizeof(char));
if (p2s == NULL || zt == NULL) error2("oom p2s or zt");
memset(zt, 0, com.ls*lpatt * sizeof(char));
for (j = 0; j < com.ns; j++)
for (h = 0; h < com.ls; h++)
for (k = 0; k < n31; k++)
zt[h*lpatt + j*n31 + k] = (unsigned char)(com.z[j][h*n31 + k] + 1);
for (ig = 0; ig < com.ngene; ig++) com.lgene[ig] = 0;
for (ig = 0, com.npatt = 0; ig < com.ngene; ig++) {
com.posG[ig] = l = u = ip = com.npatt;
for (h = 0; h < com.ls; h++) {
if (com.pose[h] != ig) continue;
if (debug) printf("\nh %3d %s", h, zt + h*lpatt);
/* bsearch in existing patterns. Knuth 1998 Vol3 Ed2 p.410
ip is the loc for match or insertion. [l,u] is the search interval.
*/
same = 0;
if (com.lgene[ig]++ != 0) { /* not 1st pattern? */
for (l = com.posG[ig], u = com.npatt - 1; ; ) {
if (u < l) break;
ip = (l + u) / 2;
k = strcmp(zt + h*lpatt, zt + p2s[ip] * lpatt);
if (k < 0) u = ip - 1;
else if (k > 0) l = ip + 1;
else { same = 1; break; }
}
}
if (!same) {
if (com.npatt > maxnpatt)
error2("npatt > maxnpatt");
if (l > ip) ip++; /* last comparison in bsearch had k > 0. */
/* Insert new pattern at ip. This is the expensive step. */
if (ip < com.npatt)
memmove(p2s + ip + 1, p2s + ip, (com.npatt - ip) * sizeof(int));
p2s[ip] = h;
com.npatt++;
}
if (debug) {
printf(": %3d (%c ilu %3d%3d%3d) ", com.npatt, (same ? '.' : '+'), ip, l, u);
for (j = 0; j < com.npatt; j++)
printf(" %s", zt + p2s[j] * lpatt);
}
if (noisy && ((h + 1) % 10000 == 0 || h + 1 == com.ls))
printf("\rCompressing, %6d patterns at %6d / %6d sites (%.1f%%), %s",
com.npatt, h + 1, com.ls, (h + 1.) * 100 / com.ls, printtime(timestr));
} /* for (h) */
if (noisy) FPN(F0);
} /* for (ig) */
/* (B) count pattern frequencies and collect pose[] */
com.posG[com.ngene] = com.npatt;
for (j = 0; j < com.ngene; j++)
if (com.lgene[j] == 0)
error2("some genes do not have any sites?");
for (j = 1; j < com.ngene; j++)
com.lgene[j] += com.lgene[j - 1];
com.fpatt = (double*)realloc(com.fpatt, com.npatt * sizeof(double));
poset = (int*)malloc(com.ls * sizeof(int));
if (com.fpatt == NULL || poset == NULL) error2("oom poset");
memset(com.fpatt, 0, com.npatt * sizeof(double));
for (ig = 0; ig < com.ngene; ig++) {
for (h = 0; h < com.ls; h++) {
if (com.pose[h] != ig) continue;
for (same = 0, l = com.posG[ig], u = com.posG[ig + 1] - 1; ; ) {
if (u < l) break;
ip = (l + u) / 2;
k = strcmp(zt + h*lpatt, zt + p2s[ip] * lpatt);
if (k < 0) u = ip - 1;
else if (k > 0) l = ip + 1;
else { same = 1; break; }
}
com.fpatt[ip]++;
poset[h] = ip;
if (noisy && ((h + 1) % 10000 == 0 || h + 1 == com.ls))
printf("\rCollecting fpatt[] & pose[], %6d patterns at %6d / %6d sites (%.1f%%), %s",
com.npatt, h + 1, com.ls, (h + 1.) * 100 / com.ls, printtime(timestr));
} /* for (h) */
if (noisy) FPN(F0);
} /* for (ig) */
if (com.seqtype == CODONseq && com.ngene == 3 && com.lgene[0] == com.ls / 3)
puts("\nCheck option G in data file?\n");
for (j = 0; j < com.ns; j++) {
com.z[j] = (unsigned char*)realloc(com.z[j], com.npatt*n31 * sizeof(unsigned char));
for (ip = 0, p = com.z[j]; ip < com.npatt; ip++)
for (k = 0; k < n31; k++)
*p++ = (unsigned char)(zt[p2s[ip] * lpatt + j*n31 + k] - 1);
}
memcpy(com.pose, poset, com.ls * sizeof(int));
free(poset); free(p2s); free(zt);
return (0);
}
void AddFreqSeqGene(int js, int ig, double pi0[], double pi[]);
void Chi2FreqHomo(double f[], int ns, int nc, double X2G[2])
{
/* This calculates a chi-square like statistic for testing that the base
or amino acid frequencies are identical among sequences.
f[ns*nc] where ns is #sequences (rows) and nc is #states (columns).
*/
int i, j;
double mf[64] = { 0 }, smallv = 1e-50;
X2G[0] = X2G[1] = 0;
for (i = 0; i < ns; i++)
for (j = 0; j < nc; j++)
mf[j] += f[i*nc + j] / ns;
for (i = 0; i < ns; i++) {
for (j = 0; j < nc; j++) {
if (mf[j] > smallv) {
X2G[0] += square(f[i*nc + j] - mf[j]) / mf[j];
if (f[i*nc + j])
X2G[1] += 2 * f[i*nc + j] * log(f[i*nc + j] / mf[j]);
}
}
}
}
int InitializeBaseAA(FILE *fout)
{
/* Count site patterns (com.fpatt) and calculate base or amino acid frequencies
in genes and species. This works on raw (uncoded) data.
Ambiguity characters in sequences are resolved by iteration.
For frequencies in each species, they are resolved within that sequence.
For average base frequencies among species, they are resolved over all
species.
This routine is called by baseml and aaml. codonml uses another
routine InitializeCodon()
*/
char *pch = (com.seqtype == 0 ? BASEs : (com.seqtype == 2 ? AAs : BINs));
char indel[] = "-?";
int wname = 30, h, js, k, ig, nconstp, n = com.ncode;
int irf, nrf = 20;
double pi0[20], t, lmax = 0, X2G[2], *pisg; /* freq for species & gene, for X2 & G */
if (noisy) printf("Counting frequencies..");
if (fout) fprintf(fout, "\nFrequencies..");
if ((pisg = (double*)malloc(com.ns*n * sizeof(double))) == NULL)
error2("oom pisg");
for (h = 0, nconstp = 0; h < com.npatt; h++) {
for (js = 1; js < com.ns; js++)
if (com.z[js][h] != com.z[0][h]) break;
if (js == com.ns && com.z[0][h] != indel[0] && com.z[0][h] != indel[1])
nconstp += (int)com.fpatt[h];
}
for (ig = 0, zero(com.pi, n); ig < com.ngene; ig++) {
if (com.ngene > 1)
fprintf(fout, "\n\nGene %2d (len %4d)", ig + 1, com.lgene[ig] - (ig == 0 ? 0 : com.lgene[ig - 1]));
fprintf(fout, "\n%*s", wname, "");
for (k = 0; k < n; k++) fprintf(fout, "%7c", pch[k]);
/* The following block calculates freqs in each species for each gene.
Ambiguities are resolved in each species. com.pi and com.piG are
used for output only, and are not be used later with missing data.
*/
zero(com.piG[ig], n);
zero(pisg, com.ns*n);
for (js = 0; js < com.ns; js++) {
fillxc(pi0, 1.0 / n, n);
for (irf = 0; irf < nrf; irf++) {
zero(com.pi, n);
AddFreqSeqGene(js, ig, pi0, com.pi);
t = sum(com.pi, n);
if (t < 1e-10) {
printf("Some sequences are empty.\n");
fillxc(com.pi, 1.0 / n, n);
}
else
abyx(1 / t, com.pi, n);
if (com.cleandata || com.cleandata || (t = distance(com.pi, pi0, n)) < 1e-8)
break;
xtoy(com.pi, pi0, n);
} /* for(irf) */