forked from sheneman/clearcut
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfasta.c
755 lines (592 loc) · 16 KB
/
fasta.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
/*
* fasta.c
*
* $Id: fasta.c,v 1.4 2007/11/27 18:33:59 sheneman Exp $
*
*****************************************************************************
*
* Copyright (c) 2004, Luke Sheneman
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* + Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* + The names of its contributors may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*****************************************************************************
*
* Functions for parsing FASTA formatted alignment files
*
*****************************************************************************
*
* AUTHOR:
*
* Luke Sheneman
* sheneman@cs.uidaho.edu
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "clearcut.h"
#include "common.h"
#include "fasta.h"
#define NJ_NUM_DNA_AMBIGUITY_SYMS 14
static const char NJ_dna_ambiguity_syms[NJ_NUM_DNA_AMBIGUITY_SYMS] =
{
'M', 'R', 'W', 'S', 'Y', 'K',
'V', 'H', 'D', 'B', 'X', 'N',
'-', '.'
};
#define NJ_NUM_PROTEIN_AMBIGUITY_SYMS 6
static const char NJ_protein_ambiguity_syms[NJ_NUM_PROTEIN_AMBIGUITY_SYMS] =
{
'X', 'B', 'Z', '*', '-', '.'
};
#define NJ_NUM_DNA_SYMS 5
static const char NJ_dna_syms[NJ_NUM_DNA_SYMS] =
{
'A', 'G', 'C', 'T', 'U'
};
#define NJ_NUM_PROTEIN_SYMS 20
static const char NJ_protein_syms[NJ_NUM_PROTEIN_SYMS] =
{
'A', 'R', 'N', 'D', 'C', 'Q', 'E', 'G', 'H', 'I',
'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V'
};
/*
* NJ_is_whitespace() - Check to see if character is whitespace
*
* INPUTS:
* -------
* c -- character to check
*
* RETURNS:
* --------
* int -- 0 if not whitespace
* 1 if whitespace
*/
static inline
int
NJ_is_whitespace(char c) {
if( c == ' ' || /* space */
c == '\n' || /* newline */
c == '\r' || /* carriage-return */
c == '\v' || /* vertical tab */
c == '\f' || /* form feed */
c == '\t' ) { /* horizontal tab */
return(1);
} else {
return(0);
}
}
/*
* NJ_is_dna() -
*
* Determines if the given symbol is DNA
*
* RETURNS: 1 if DNA
* 0 if not DNA
*
*/
static inline
int
NJ_is_dna(char c) {
int i;
char up_c;
up_c = toupper(c);
for(i=0;i<NJ_NUM_DNA_SYMS;i++) {
if(up_c == NJ_dna_syms[i]) {
return(1);
}
}
return(0);
}
/*
* NJ_is_dna_ambiguity() -
*
* Determines if the given symbol is a
* DNA ambiguity code
*
* RETURNS: 1 if DNA Ambiguity Code
* 0 if not DNA Ambiguity Code
*
*/
static inline
int
NJ_is_dna_ambiguity(char c) {
int i;
char up_c;
up_c = toupper(c);
for(i=0;i<NJ_NUM_DNA_AMBIGUITY_SYMS;i++) {
if(up_c == NJ_dna_ambiguity_syms[i]) {
return(1);
}
}
return(0);
}
/*
* NJ_is_protein() -
*
* Determines if supplied symbol is amino acid symbol
*
* RETURNS: 1 if amino acid
* 0 if not amino acid
*
*/
static inline
int
NJ_is_protein(char c) {
int i;
char up_c;
up_c = toupper(c);
for(i=0;i<NJ_NUM_PROTEIN_SYMS;i++) {
if(up_c == NJ_protein_syms[i]) {
return(1);
}
}
return(0);
}
/*
* NJ_is_protein_ambiguity() -
*
* Determines if supplied symbol is amino acid ambiguity symbol
*
* RETURNS: 1 if amino acid ambiguity symbol
* 0 if not amino acid ambiguity symbol
*
*/
static inline
int
NJ_is_protein_ambiguity(char c) {
int i;
char up_c;
up_c = toupper(c);
for(i=0;i<NJ_NUM_PROTEIN_AMBIGUITY_SYMS;i++) {
if(up_c == NJ_protein_ambiguity_syms[i]) {
return(1);
}
}
return(0);
}
/*
* NJ_read_fasta() - A function for inputing FASTA sequences into an alignment
* data structure
*
*
* INPUTS:
* -------
* nj_args -- A pointer to a data structure containing command-line args
*
* RETURNS:
* --------
* NJ_alignment * -- A pointer to a multiple sequence alignment
*
* DESCRIPTION:
* ------------
*
*
* This function implements a state machine parser for parsing FASTA-formatted
* multiple sequence alignment files.
*
* Example Input:
*
* > sequence1
* ATAGATATAGATTAGAATAT----TATAGATAT----ATATAT-TTT-
* > sequence2
* --ATAGATA---ATATATATATTTT--GTCTCATAGT---ATATGCTT
* > sequence3
* TTATAGATA---ATATATATATTTTAAGTCTCATAGT-A-ATATGC--
*
* This function will parse alignments for DNA or protein, and will do
* so mindful of ambiguity codes for these kinds of sequences. All
* ambiguity codes are ignored by this program for the purposes of
* computing a distance matrix from a multiple alignment. By design,
* this program does not auto-detect DNA vs. Protein, and requires that
* the user explictly specify that on the command-line.
*
* Gaps can be represented either with the '-' or '.' characters.
*
* Newlines and other whitespace are allowed to be interspersed
* throughout the sequences.
*
* Taxon labels are required to be unique, and they must start with
* an alphabetic character (not a number, etc.). The parser will read
* the first token after the > character in the description line up until the
* first whitespace and use that for the taxon label.
*
* For example, in the line "> taxon1 is homo sapien", the taxon label will be
* "taxon1"
*
*/
NJ_alignment *
NJ_read_fasta(NJ_ARGS *nj_args) {
FILE *fp = NULL;
char *buf = NULL;
char *ptr = NULL;
NJ_alignment *alignment = NULL;
char c;
int state;
long int index, x, seq;
long int i;
long int bufsize, nseqs = NJ_INITIAL_NSEQS;
int first_sequence_flag;
/*
* In this function, we implement a FASTA alignment parser which
* reads in an alignment character-by-character, maintaining state
* information which guides the parser.
*
* The program reads either DNA or Protein alignments. All title lines
* and sequences can be arbitrarily long. Gaps can be represented by
* "-" or "." characters.
*
* Ambiguity codes are also handled.
*
*/
/*
* We can't handle reading fasta input unless the user explicity
* specifies the input type...just to be sure.
*/
if( (!nj_args->dna_flag && !nj_args->protein_flag) ||
(nj_args->dna_flag && nj_args->protein_flag) ) {
fprintf(stderr, "Clearcut: Explicitly specify protein or DNA\n");
goto XIT_BAD;
}
/* open specified fasta file here */
if(nj_args->stdin_flag) {
fp = stdin;
} else {
fp = fopen(nj_args->infilename, "r");
if(!fp) {
fprintf(stderr, "Clearcut: Failed to open input FASTA file: %s\n", nj_args->infilename);
perror("Clearcut");
goto XIT_BAD;
}
}
/* allocate the initial buffer */
bufsize = NJ_INITIAL_BUFFER_SIZE;
buf = (char *)calloc(bufsize, sizeof(char));
/* allocate the alignment container here */
alignment = (NJ_alignment *)calloc(1, sizeof(NJ_alignment));
/* allocate initial title array */
// printf("allocating initial title array\n");
alignment->titles = (char **)calloc(NJ_INITIAL_NSEQS, sizeof(char *));
/* make sure that we successfully allocated memory */
if(!buf || !alignment || !alignment->titles) {
fprintf(stderr, "Clearcut: Memory allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
/* a flag */
first_sequence_flag = 1;
index = 0; /* tracks the position in buffer */
x = 0; /* tracks the position on sequence */
seq = 0; /* tracks the active sequence */
/* intitial state of state machine */
state = NJ_FASTA_MODE_UNKNOWN;
while(1) {
/* get the next character */
c = fgetc(fp);
if(feof(fp)) {
if(state == NJ_FASTA_MODE_SEQUENCE) {
buf[index+1] = '\0';
/* copy buf to alignment */
for(i=1;i<=alignment->length;i++) {
alignment->data[seq*alignment->length+i-1] = buf[i];
}
}
break;
}
/* make sure our dynamic buffer is big enough */
if(index >= bufsize) {
bufsize *= 2;
buf = (char *)realloc(buf, bufsize);
if(!buf) {
fprintf(stderr, "Clearcut: Memory allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
}
switch(state) {
case NJ_FASTA_MODE_UNKNOWN:
if(!NJ_is_whitespace(c)) {
if(c == '>') {
state = NJ_FASTA_MODE_TITLE;
buf[0] = '>';
} else {
goto XIT_BAD;
}
}
break;
case NJ_FASTA_MODE_TITLE:
if( c == '\n' ||
c == '\r' ) {
buf[index] = '\0';
state = NJ_FASTA_MODE_SEQUENCE;
index = 0;
x = -1;
/* make sure we've allocated enough space for titles and sequences */
if(seq == nseqs) {
// printf("realloc(). seq = %d, nseqs = %d\n", seq, nseqs);
nseqs *= 2;
alignment->titles = (char **)realloc(alignment->titles, nseqs*sizeof(char *));
if(!alignment->titles) {
fprintf(stderr, "Clearcut: Memory allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
alignment->data = (char *)realloc(alignment->data, alignment->length*nseqs*sizeof(char));
if(!alignment->data) {
fprintf(stderr, "Clearcut: Allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
}
// printf("Allocating %d bytes for title %d: %s\n", (int)strlen(buf), (int)seq, buf);
alignment->titles[seq] = (char *)calloc(strlen(buf), sizeof(char));
if(!alignment->titles[seq]) {
fprintf(stderr, "Clearcut: Memory allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
/* lets forward to the first non-space (space/tab) character after the '>' */
if(first_sequence_flag) {
ptr = buf;
} else {
ptr = &buf[1];
}
while(*ptr == '\t' || *ptr == ' ') {
ptr++;
}
sscanf(ptr, "%s", alignment->titles[seq]); /* get the first word and use as the title */
alignment->nseq++;
}
buf[index++] = c;
break;
case NJ_FASTA_MODE_SEQUENCE:
if(c == '>') {
if(first_sequence_flag) {
first_sequence_flag = 0;
/* allocate our alignment data section here */
alignment->length = index-1;
nseqs = NJ_INITIAL_NSEQS;
alignment->data = (char *)calloc(alignment->length*nseqs, sizeof(char));
if(!alignment->data) {
fprintf(stderr, "Clearcut: Allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
}
if(!first_sequence_flag) {
if(index-1 < alignment->length) {
fprintf(stderr, "Clearcut: Sequences must be of uniform length in alignment at sequence %ld\n", seq);
goto XIT_BAD;
}
}
/* re-allocate if necessary */
/*
if(seq >= nseqs) {
nseqs *= 2;
alignment->data = (char *)realloc(alignment->data, alignment->length*nseqs*sizeof(char));
if(!alignment->data) {
fprintf(stderr, "Clearcut: Allocation error in NJ_read_fasta()\n");
goto XIT_BAD;
}
}
*/
/* copy buf to alignment */
for(i=1;i<=alignment->length;i++) {
alignment->data[seq*alignment->length+i-1] = buf[i];
}
state = NJ_FASTA_MODE_TITLE;
index = 1;
x = 1;
buf[0] = c;
seq++;
} else {
if(NJ_is_whitespace(c)) {
break;
}
if(!first_sequence_flag) {
if(index-1 >= alignment->length) {
fprintf(stderr, "Clearcut: Sequences must be of uniform length in alignment at sequence %ld\n", seq);
goto XIT_BAD;
}
}
/*
* Here we check to make sure that the symbol read is appropriate
* for the type of data the user specified. (dna or protein).
* We also handle ambiguity codes by converting them to a specific
* assigned ambiguity code character. Ambiguity codes are ignored
* when computing distances
*/
if(nj_args->dna_flag) {
if(NJ_is_dna(c)) {
buf[index++] = toupper(c);
} else {
if(NJ_is_dna_ambiguity(c)) {
buf[index++] = NJ_AMBIGUITY_CHAR;
} else {
fprintf(stderr, "Clearcut: Unknown symbol '%c' in nucleotide sequence %ld.\n", c, seq);
goto XIT_BAD;
}
}
} else if(nj_args->protein_flag) {
if(NJ_is_protein(c)) {
buf[index++] = toupper(c);
} else {
if(NJ_is_protein_ambiguity(c)) {
buf[index++] = NJ_AMBIGUITY_CHAR;
} else {
fprintf(stderr, "Clearcut: Unknown symbol '%c' in protein sequence %ld.\n", c, seq);
goto XIT_BAD;
}
}
}
}
break;
default:
goto XIT_BAD;
break;
}
}
if(index-1 != alignment->length) {
fprintf(stderr, "Clearcut: Sequences must be of uniform length in alignment at sequence %ld\n", seq);
goto XIT_BAD;
}
/* check for duplicate taxon labels */
if(!NJ_taxaname_unique(alignment)) {
goto XIT_BAD;
}
return(alignment);
XIT_BAD:
if(fp) {
fprintf(stderr, "Clearcut: Fatal error parsing FASTA file at file offset %ld.\n", ftell(fp));
}
if(buf) {
free(buf);
}
NJ_free_alignment(alignment);
return(NULL);
}
/*
* NJ_print_alignment() - Print multiple sequence alignment (for debugging)
*
* INPUTS:
* -------
* alignment -- A pointer to the alignment
*
* RETURNS:
* --------
* NONE
*
*/
void
NJ_print_alignment(NJ_alignment *alignment) {
long int i, j;
printf("nseq = %ld, length = %ld\n", alignment->nseq, alignment->length);
for(i=0;i<alignment->nseq;i++) {
printf("> %s\n", alignment->titles[i]);
for(j=0;j<alignment->length;j++) {
printf("%c", alignment->data[i*alignment->length+j]);
}
printf("\n");
}
return;
}
/*
*
* NJ_free_alignment() - Free all of the memory allocated for the
* multiple sequence alignment
*
* INPUTS:
* -------
* alignment -- A pointer to the multiple sequence alignment
*
* RETURNS:
* --------
* NONE
*
*/
void
NJ_free_alignment(NJ_alignment *alignment) {
long int i;
if(alignment) {
/* free the allocated titles */
if(alignment->titles) {
for(i=0;i<alignment->nseq;i++) {
if(alignment->titles[i]) {
free(alignment->titles[i]);
}
}
free(alignment->titles);
}
/* free the alignment data */
if(alignment->data) {
free(alignment->data);
}
/* free the alignment itself */
free(alignment);
}
return;
}
/*
* NJ_taxaname_unique() - Check to see if taxanames are unique in alignment
*
* INPUTS:
* -------
* alignment -- a pointer to a multiple sequence alignment
*
* OUTPUTS:
* --------
* int -- 0 if all taxanames in alignment are unique
* 1 if all taxanames in alignment are NOT unique
*
*
* DESCRIPTION:
* ------------
*
* Check to see if the taxanames in the alignment are unique. It
* will be impossible to make sense of the final tree if the taxon
* labels are not unqiue.
*
*/
int
NJ_taxaname_unique(NJ_alignment *alignment) {
long int i, j;
for(i=0;i<alignment->nseq;i++) {
for(j=i+1;j<alignment->nseq;j++) {
if(!strcmp(alignment->titles[i],
alignment->titles[j])) {
fprintf(stderr, "Clearcut: Taxa %ld and %ld (%s) do not have unique taxon labels.\n",
i, j, alignment->titles[i]);
return(0);
}
}
}
return(1);
}
void
NJ_print_titles(NJ_alignment *alignment) {
int i;
for(i=0;i<alignment->nseq;i++) {
printf("%d: %s\n", i, alignment->titles[i]);
}
return;
}