-
Notifications
You must be signed in to change notification settings - Fork 0
/
treesub.c
10032 lines (8772 loc) · 359 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
/* TREESUB.c
subroutines that operates on trees, inserted into other programs
such as baseml, basemlg, codeml, and pamp.
*/
extern char BASEs[], *EquateBASE[], AAs[], BINs[], CODONs[][4], nChara[], CharaMap[][64];
extern int noisy;
#ifdef BASEML
#define REALSEQUENCE
#define NODESTRUCTURE
#define TREESEARCH
#define LSDISTANCE
#define LFUNCTIONS
#define RECONSTRUCTION
#define MINIMIZATION
#endif
#ifdef CODEML
#define REALSEQUENCE
#define NODESTRUCTURE
#define TREESEARCH
#define LSDISTANCE
#define LFUNCTIONS
#define RECONSTRUCTION
#define MINIMIZATION
#endif
#ifdef BASEMLG
#define REALSEQUENCE
#define NODESTRUCTURE
#define LSDISTANCE
#endif
#ifdef RECONSTRUCTION
#define PARSIMONY
#endif
#ifdef MCMCTREE
#define REALSEQUENCE
#define NODESTRUCTURE
#define LFUNCTIONS
#endif
#if(defined CODEML || defined YN00)
double SS, NN, Sd, Nd; /* kostas, # of syn. sites,# of non syn. sites,# of syn. subst.,# of non syn. subst. */
#endif
#if(defined BASEML || defined BASEMLG || defined CODEML || defined BPP || defined EVOLVER || defined MCMCTREE)
int PatternWeightSimple(void)
{
/* This is modified from PatternWeight(), and does not deal with multiple genes in
the same alignment (com.ngene, com.lgene[], com.posG[], etc.)
Binary search is used to sort site patterns, with patterns represented using 0-ended strings.
The routine works with nucleotide, amino acid, or codon sequences.
This should work with both encoded and un-encoded sequences.
If com.pose is not NULL, this generates the site-to-pattern map in com.pose[].
com.fpatt holds site-pattern counts.
Sequences z[ns][ls] are copied into patterns zt[ls*lpatt], and bsearch is used
twice to avoid excessive copying, first to count npatt and identify the site patterns and
second to generate fpatt[], pose[] etc.
*/
int maxnpatt = com.ls, h, l, u, ip, j, k, same;
int n31 = (com.seqtype==CODONseq ? 3 : 1);
int lpatt = com.ns*n31 + 1;
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.
Move sequences com.z[ns][ls] into sites zt[ls*lpatt].
Use p2s to map patterns to sites in zt to avoid copying.
*/
if ((com.seqtype == 1 && com.ns<5) || (com.seqtype != 1 && com.ns<7))
maxnpatt = (int)(pow(nc, (double)com.ns) + 0.5);
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);
com.npatt = l = u = ip = 0;
for (h = 0; h<com.ls; h++) {
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 (h != 0) { /* not 1st pattern? */
for (l = 0, 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?'S':'D'), ip, l, u);
for (j = 0; j<com.npatt; j++)
printf(" %s", zt + p2s[j] * lpatt);
}
if(noisy>2 && ((h+1)%10000==0 || h+1==com.ls))
printf("\r%12d patterns at %8d / %8d sites (%.1f%%), %s",
com.npatt, h+1, com.ls, (h+1.)*100/com.ls, printtime(timestr));
} /* for (h) */
if(noisy>2) printf("\n%d patterns\n", com.npatt);
/* (B) count pattern frequencies */
com.fpatt = (double*)realloc(com.fpatt, com.npatt*sizeof(double));
if (com.fpatt == NULL) error2("oom fpatt");
memset(com.fpatt, 0, com.npatt*sizeof(double));
for (h = 0; h<com.ls; h++) {
for (same = 0, l = 0, 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)
error2("ghost pattern?");
com.fpatt[ip]++;
if(com.pose) com.pose[h] = ip;
} /* for (h) */
for (j = 0; j<com.ns; j++) {
com.z[j] = p = (unsigned char*)realloc(com.z[j], com.npatt * sizeof(unsigned char));
for (ip = 0; ip<com.npatt; ip++)
for (k = 0; k<n31; k++)
*p++ = (unsigned char)(zt[p2s[ip] * lpatt + j*n31 + k] - 1);
}
free(p2s); free(zt);
return (0);
}
int ConvertSiteJC69like(unsigned char *z[], int ns, int h, unsigned char zh[])
{
/* This converts a site (or pattern) of nucleotides or amino acids for JC69-like models.
Sequence alignments in com.z[] are already encoded into 0, 1, ...
If the data have no ambiguities (com.cleandata=1), the routine converts,
for example, a site 1120 (CCAT) into 0012 (TTCA) before checking against old
patterns already found. If a site contain non-gap ambiguities, it is not
converted. For every site, the routine changes ? or N into - first, and then
convert the site iff there are no non-gap ambiguities. Thus CC?T will be
converted into CC-T first and then into TT-C. A site with CCRT will not be
convertd. In theory such sites may be compressed as well, but the effort is
perhaps not worthwhile.
*/
char b, gap;
char *pch = (com.seqtype == 0 ? BASEs : (com.seqtype == 2 ? AAs : BINs));
int npatt0 = com.npatt, j, k, same = 0, convert;
gap = (char)(strchr(pch, (int)'-') - pch);
if (com.cleandata) { /* clean data, always convert */
zh[0] = b = 0;
b++;
for (j = 1; j<com.ns; j++) {
for (k = 0; k<j; k++)
if (z[j][h] == z[k][h]) break;
zh[j] = (k<j ? zh[k] : b++);
}
}
else { /* convert only if there are no non-gap ambiguity characters */
for (j = 0; j<ns; j++)
zh[j] = z[j][h];
/* After this loop, convert = 0 or 1 decides whether to convert. */
for (j = 0, convert = 1; j<ns; j++) {
if (zh[j] < com.ncode)
continue;
if (nChara[(int)zh[j]] == com.ncode) {
zh[j] = gap;
continue;
}
convert = 0;
break;
}
if (convert) {
b = 0;
if (zh[0] != gap)
zh[0] = b++;
for (j = 1; j<ns; j++) {
if (zh[j] != gap) {
for (k = 0; k<j; k++)
if (zh[j] == z[k][h]) break;
if (k<j) zh[j] = zh[k];
else zh[j] = b++;
}
}
}
}
for (j = 0; j<ns; j++) zh[j] ++; /* change 0 to 1. */
return(0);
}
int PatternWeightJC69like (void)
{
/* This collaps site patterns further for JC69-like models, called after
PatternWeight(). This is used for JC and poisson amino acid models.
The routine could be merged into PatternWeight(), which should lead to
faster computation, but this is not done because right now
InitializeBaseAA() prints out base or amino acid frequencies after
PatternWeight() and before this routine.
If com.pose is not NULL, the routine also updates com.pose. This allows the program
to work if com.readpattern==1.
This works for nucleotide and amino acid models, but not codon models.
This routine is nearly identical to PatternWeight, which works for un-encoded sequences.
fpatt0 stores the old com.fpatt info, while com.fpatt is shrunk.
Think about merging them (encode sequences first and compress sites).
*/
int npatt0=com.npatt, lpatt = com.ns + 1, h, l, u, ip, j, k, same;
int *p2s; /* point patterns to sites in zt */
char timestr[36];
unsigned char *p, *zt;
double *fpatt0;
int debug = 0;
/* (A) Collect and sort patterns. Get com.npatt.
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>2) printf("Counting site patterns again, for JC69.. %s\n", printtime(timestr));
if (com.seqtype == 1) error2("PatternWeightJC69like does not work for codon seqs");
if (com.ngene>1) error2("PatternWeightJC69like does not work when ngene > 1");
p2s = (int*)malloc(npatt0 * sizeof(int));
zt = (char*)malloc(npatt0*lpatt * sizeof(char));
fpatt0 = (double*)malloc(npatt0* sizeof(double));
if (p2s == NULL || zt == NULL || fpatt0 == NULL) error2("oom p2s or zt or fpatt0");
memset(zt, 0, npatt0*lpatt * sizeof(char));
memmove(fpatt0, com.fpatt, npatt0*sizeof(double));
for (h = 0; h<npatt0; h++)
ConvertSiteJC69like(com.z, com.ns, h, zt + h*lpatt);
l = u = ip = com.npatt = 0;
for (h = 0; h<npatt0; h++) {
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 (h != 0) { /* not 1st pattern? */
for (l = 0, 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 (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 ? 'S' : 'D'), ip, l, u);
for (j = 0; j<com.npatt; j++)
printf(" %s", zt + p2s[j] * lpatt);
}
if (noisy>2 && ((h + 1) % 10000 == 0 || h + 1 == npatt0))
printf("\rCompressing, %6d patterns at %6d / %6d sites (%.1f%%), %s",
com.npatt, h + 1, npatt0, (h + 1.) * 100 / npatt0, printtime(timestr));
} /* for (h) */
if (noisy>2) printf("\n");
/* (B) count pattern frequencies and collect pose[] */
com.fpatt = (double*)realloc(com.fpatt, com.npatt * sizeof(double));
memset(com.fpatt, 0, com.npatt * sizeof(double));
for (h = 0; h<npatt0; h++) {
for (same = 0, l = 0, 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) error2("ghost pattern?");
com.fpatt[ip] += fpatt0[h];
if(com.pose) com.pose[h] = ip;
if (noisy>2 && ((h + 1) % 10000 == 0 || h + 1 == npatt0))
printf("\rCollecting patterns, %6d patterns at %6d / %6d sites (%.1f%%), %s",
com.npatt, h + 1, npatt0, (h + 1.) * 100 / npatt0, printtime(timestr));
} /* for (h) */
if (noisy>2) printf("\n");
for (j = 0; j<com.ns; j++) {
com.z[j] = (unsigned char*)realloc(com.z[j], com.npatt * sizeof(unsigned char));
for (ip = 0, p = com.z[j]; ip<com.npatt; ip++)
*p++ = (unsigned char)(zt[p2s[ip] * lpatt + j] - 1);
}
free(p2s); free(zt); free(fpatt0);
return (0);
}
#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 i,j, locus=data.nmorphloci;
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");
if((data.nmorphloci = locus+1) > NMORPHLOCI) error2("raise NMORPHLOCI and recompile.");
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]=" ";
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 ("\nns = %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;
#endif
}
#if(MCMCTREE)
if(data.datatype[locus] == MORPHC) { /* morhpological data */
ReadMorphology(fout, fseq);
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;
#if(defined(BASEML) || defined(BASEMLG))
com.coding=1;
if(com.readpattern)
error2("partterns for coding sequences (G C P) not implemented.");
else
for (i=0;i<com.ls;i++) com.pose[i]=(char)(i%3);
#endif
}
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" : "\r"));
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 \r",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
#ifdef CODEML
/* mask stop codons as ???. */
if(com.seqtype==1 && MarkStopCodons())
miss=1;
#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(); */
#ifdef CODEML
if(com.seqtype==1 && com.verbose) Get4foldSites();
if(com.seqtype==CODON2AAseq) {
if (noisy>2) puts("\nTranslating into AA sequences\n");
for(j=0; j<com.ns; j++) {
if (noisy>2) printf("Translating sequence %d\n",j+1);
DNA2protein(com.z[j], com.z[j], com.ls,com.icode);
}
com.seqtype=AAseq;
if(fout) {
fputs("\nTranslated AA Sequences\n",fout);
fprintf(fout,"%4d %6d",com.ns,com.ls);
printsma(fout,com.spname,com.z,com.ns,com.ls,com.ls,10,com.seqtype,0,0,NULL);
}
}
#endif
#if (defined CODEML || defined BASEML)
if(com.ngene==1 && com.Mgene==1) com.Mgene=0;
if(com.ngene>1 && com.Mgene==1 && com.verbose) printSeqsMgenes ();
if(com.bootstrap) { BootstrapSeq("boot.txt"); exit(0); }
#endif
#if (defined CODEML)
/* list sites with 2 types of serine codons: TC? and TCY. 19 March 2014, Ziheng. */
if(com.seqtype==1) {
char codon[4]="";
int nbox0, nbox1, present=0;
for(h=0; h<com.ls; h++) {
for(i=0,nbox0=nbox1=0; i<com.ns; i++) {
codon[0]=com.z[i][h*3+0];
codon[1]=com.z[i][h*3+1];
codon[2]=com.z[i][h*3+2];
if(codon[0]=='T' && codon[1]=='C') nbox0++;
else if(codon[0]=='A' && codon[1]=='G' && (codon[2]=='T' || codon[2]=='C')) nbox1++;
}
if(nbox0 && nbox1 && nbox0+nbox1==com.ns) {
present=1;
printf("\ncodon site %6d: ", h+1);
for(i=0; i<com.ns; i++)
printf("%c%c%c ", com.z[i][h*3+0], com.z[i][h*3+1], com.z[i][h*3+2]);
}
}
if(present) printf("\nAbove are 'synonymous' sites with 2 types of serine codons: TC? and TCY.\n");
}
#endif
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==0)
RemoveEmptySequences();
#endif
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);
}
return (0);
}
#if (defined CODEML)
int MarkStopCodons(void)
{
/* this converts the whole column into ??? if there is a stop codon in one sequence.
Data in com.z[] are just read in and not encoded yet.
*/
int i,j,h,k, NColumnEdited=0;
char codon[4]="", stops[6][4]={"","",""}, nstops=0;
if(com.seqtype!=1) error2("should not be here");
for(i=0; i<64; i++)
if(GeneticCode[com.icode][i]==-1)
getcodon(stops[nstops++], i);
for(h=0; h<com.ls/3; h++) {
for(i=0; i<com.ns; i++) {
codon[0] = com.z[i][h*3+0];
codon[1] = com.z[i][h*3+1];
codon[2] = com.z[i][h*3+2];
for(j=0; j<nstops; j++)
if(strcmp(codon, stops[j])==0) {
printf("stop codon %s in seq. # %3d (%s)\r", codon, i+1, com.spname[i]);
break;
}
if(j<nstops) break;
}
if(i<com.ns) {
for(i=0; i<com.ns; i++)
com.z[i][h*3+0] = com.z[i][h*3+1] = com.z[i][h*3+2] = '?';
NColumnEdited++;
}
}
if(NColumnEdited) {
printf("\n%2d columns are converted into ??? because of stop codons\nPress Enter to continue", NColumnEdited);
getchar();
}