1 /*****************************************************************
2 * SQUID - a library of functions for biological sequence analysis
3 * Copyright (C) 1992-2002 Washington University School of Medicine
5 * This source code is freely distributed under the terms of the
6 * GNU General Public License. See the files COPYRIGHT and LICENSE
8 *****************************************************************/
11 * From: ureadseq.c in Don Gilbert's sequence i/o package
13 * Reads and writes nucleic/protein sequence in various
14 * formats. Data files may have multiple sequences.
16 * Heavily modified from READSEQ package
17 * Copyright (C) 1990 by D.G. Gilbert
18 * Biology Dept., Indiana University, Bloomington, IN 47405
19 * email: gilbertd@bio.indiana.edu
22 * SRE: Modifications as noted. Fri Jul 3 09:44:54 1992
23 * Packaged for squid, Thu Oct 1 10:07:11 1992
24 * ANSI conversion in full swing, Mon Jul 12 12:22:21 1993
26 * CVS $Id: sqio.c,v 1.29 2002/08/26 23:10:52 eddy Exp)
28 *****************************************************************
29 * Basic API for single sequence reading:
33 * int format; - see squid.h for formats; example: SQFILE_FASTA
37 * if ((sqfp = SeqfileOpen(seqfile, format, "BLASTDB")) == NULL)
38 * Die("Failed to open sequence database file %s\n%s\n", seqfile, usage);
39 * while (ReadSeq(sqfp, sqfp->format, &seq, &sqinfo)) {
41 * FreeSequence(seq, &sqinfo);
45 *****************************************************************
61 static void SeqfileGetLine(SQFILE *V);
63 #define kStartLength 500
65 static char *aminos = "ABCDEFGHIKLMNPQRSTVWXYZ*";
66 static char *primenuc = "ACGTUN";
67 static char *protonly = "EFIPQZ";
69 static SQFILE *seqfile_open(char *filename, int format, char *env, int ssimode);
71 /* Function: SeqfileOpen()
73 * Purpose : Open a sequence database file and prepare for reading
76 * Args: filename - name of file to open
77 * format - format of file
78 * env - environment variable for path (e.g. BLASTDB)
79 * ssimode - -1, SSI_OFFSET_I32, or SSI_OFFSET_I64
81 * Returns opened SQFILE ptr, or NULL on failure.
84 SeqfileOpen(char *filename, int format, char *env)
86 return seqfile_open(filename, format, env, -1);
89 SeqfileOpenForIndexing(char *filename, int format, char *env, int ssimode)
91 return seqfile_open(filename, format, env, ssimode);
94 seqfile_open(char *filename, int format, char *env, int ssimode)
98 dbfp = (SQFILE *) MallocOrDie (sizeof(SQFILE));
100 dbfp->ssimode = ssimode;
101 dbfp->rpl = -1; /* flag meaning "unset" */
104 dbfp->bpl = -1; /* flag meaning "unset" */
108 /* Open our file handle.
109 * Three possibilities:
110 * 1. normal file open
111 * 2. filename = "-"; read from stdin
112 * 3. filename = "*.gz"; read thru pipe from gzip
113 * If we're reading from stdin or a pipe, we can't reliably
114 * back up, so we can't do two-pass parsers like the interleaved alignment
117 if (strcmp(filename, "-") == 0)
120 dbfp->do_stdin = TRUE;
121 dbfp->do_gzip = FALSE;
122 dbfp->fname = sre_strdup("[STDIN]", -1);
124 #ifndef SRE_STRICT_ANSI
125 /* popen(), pclose() aren't portable to non-POSIX systems; disable */
126 else if (Strparse("^.*\\.gz$", filename, 0))
130 /* Note that popen() will return "successfully"
131 * if file doesn't exist, because gzip works fine
132 * and prints an error! So we have to check for
133 * existence of file ourself.
135 if (! FileExists(filename))
136 Die("%s: file does not exist", filename);
138 if (strlen(filename) + strlen("gzip -dc ") >= 256)
139 Die("filename > 255 char in SeqfileOpen()");
140 sprintf(cmd, "gzip -dc %s", filename);
141 if ((dbfp->f = popen(cmd, "r")) == NULL)
144 dbfp->do_stdin = FALSE;
145 dbfp->do_gzip = TRUE;
146 dbfp->fname = sre_strdup(filename, -1);
148 #endif /*SRE_STRICT_ANSI*/
151 if ((dbfp->f = fopen(filename, "r")) == NULL &&
152 (dbfp->f = EnvFileOpen(filename, env, NULL)) == NULL)
155 dbfp->do_stdin = FALSE;
156 dbfp->do_gzip = FALSE;
157 dbfp->fname = sre_strdup(filename, -1);
161 /* Invoke autodetection if we haven't already been told what
164 if (format == SQFILE_UNKNOWN)
166 if (dbfp->do_stdin == TRUE || dbfp->do_gzip)
167 Die("Can't autodetect sequence file format from a stdin or gzip pipe");
168 format = SeqfileFormat(dbfp->f);
169 if (format == SQFILE_UNKNOWN)
170 Die("Can't determine format of sequence file %s", dbfp->fname);
173 /* The hack for sequential access of an interleaved alignment file:
174 * read the alignment in, we'll copy sequences out one at a time.
178 dbfp->format = format;
179 dbfp->linenumber = 0;
182 if (IsAlignmentFormat(format))
184 /* We'll be reading from the MSA interface. Copy our data
185 * to the MSA afp's structure.
187 dbfp->afp = MallocOrDie(sizeof(MSAFILE));
188 dbfp->afp->f = dbfp->f; /* just a ptr, don't close */
189 dbfp->afp->do_stdin = dbfp->do_stdin;
190 dbfp->afp->do_gzip = dbfp->do_gzip;
191 dbfp->afp->fname = dbfp->fname; /* just a ptr, don't free */
192 dbfp->afp->format = dbfp->format; /* e.g. format */
193 dbfp->afp->linenumber = dbfp->linenumber; /* e.g. 0 */
194 dbfp->afp->buf = NULL;
195 dbfp->afp->buflen = 0;
197 if ((dbfp->msa = MSAFileRead(dbfp->afp)) == NULL)
198 Die("Failed to read any alignment data from file %s", dbfp->fname);
199 /* hack: overload/reuse msa->lastidx; indicates
200 next seq to return upon a ReadSeq() call */
201 dbfp->msa->lastidx = 0;
206 /* Load the first line.
208 SeqfileGetLine(dbfp);
212 /* Function: SeqfilePosition()
214 * Purpose: Move to a particular offset in a seqfile.
215 * Will not work on alignment files.
218 SeqfilePosition(SQFILE *sqfp, SSIOFFSET *offset)
220 if (sqfp->do_stdin || sqfp->do_gzip || IsAlignmentFormat(sqfp->format))
221 Die("SeqfilePosition() failed: in a nonrewindable data file or stream");
223 if (SSISetFilePosition(sqfp->f, offset) != 0)
224 Die("SSISetFilePosition failed, but that shouldn't happen.");
225 SeqfileGetLine(sqfp);
229 /* Function: SeqfileRewind()
231 * Purpose: Set a sequence file back to the first sequence.
233 * Won't work on alignment files. Although it would
234 * seem that it could (just set msa->lastidx back to 0),
235 * that'll fail on "multiple multiple" alignment file formats
239 SeqfileRewind(SQFILE *sqfp)
241 if (sqfp->do_stdin || sqfp->do_gzip)
242 Die("SeqfileRewind() failed: in a nonrewindable data file or stream");
245 SeqfileGetLine(sqfp);
248 /* Function: SeqfileLineParameters()
249 * Date: SRE, Thu Feb 15 17:00:41 2001 [St. Louis]
251 * Purpose: After all the sequences have been read from the file,
252 * but before closing it, retrieve overall bytes-per-line and
253 * residues-per-line info. If non-zero, these mean that
254 * the file contains homogeneous sequence line lengths (except
255 * the last line in each record).
257 * If either of bpl or rpl is determined to be inhomogeneous,
258 * both are returned as 0.
260 * Args: *sqfp - an open but fully read sequence file
261 * ret_bpl - RETURN: bytes per line, or 0 if inhomogeneous
262 * ret_rpl - RETURN: residues per line, or 0 if inhomogenous.
267 SeqfileLineParameters(SQFILE *V, int *ret_bpl, int *ret_rpl)
269 if (V->rpl > 0 && V->maxrpl == V->rpl &&
270 V->bpl > 0 && V->maxbpl == V->bpl) {
281 SeqfileClose(SQFILE *sqfp)
283 /* note: don't test for sqfp->msa being NULL. Now that
284 * we're holding afp open and allowing access to multi-MSA
285 * databases (e.g. Stockholm format, Pfam), msa ends
286 * up being NULL when we run out of alignments.
288 if (sqfp->afp != NULL) {
289 if (sqfp->msa != NULL) MSAFree(sqfp->msa);
290 if (sqfp->afp->buf != NULL) free(sqfp->afp->buf);
293 #ifndef SRE_STRICT_ANSI /* gunzip functionality only on POSIX systems */
294 if (sqfp->do_gzip) pclose(sqfp->f);
296 else if (! sqfp->do_stdin) fclose(sqfp->f);
297 if (sqfp->buf != NULL) free(sqfp->buf);
298 if (sqfp->fname != NULL) free(sqfp->fname);
303 /* Function: SeqfileGetLine()
304 * Date: SRE, Tue Jun 22 09:15:49 1999 [Sanger Centre]
306 * Purpose: read a line from a sequence file into V->buf
307 * If the fgets() is NULL, sets V->buf[0] to '\0'.
314 SeqfileGetLine(SQFILE *V)
317 if (0 != SSIGetFilePosition(V->f, V->ssimode, &(V->ssioffset)))
318 Die("SSIGetFilePosition() failed");
319 if (sre_fgets(&(V->buf), &(V->buflen), V->f) == NULL)
326 FreeSequence(char *seq, SQINFO *sqinfo)
328 if (seq != NULL) free(seq); /* FS, r244, here is potential problem in profile/profile */
329 if (sqinfo->flags & SQINFO_SS){
330 if (NULL != sqinfo->ss){ /* FS, r244 -> r245 */
334 if (sqinfo->flags & SQINFO_SA){
335 if (NULL != sqinfo->sa){ /* FS, r244 -> r245 */
339 if (sqinfo->flags & SQINFO_CO){
340 if (NULL != sqinfo->co){ /* FS, r296 -> */
344 } /* this is the end of FreeSequence() */
347 SetSeqinfoString(SQINFO *sqinfo, char *sptr, int flag)
352 /* silently ignore NULL. */
353 if (sptr == NULL) return 1;
355 while (*sptr == ' ') sptr++; /* ignore leading whitespace */
356 for (pos = strlen(sptr)-1; pos >= 0; pos--)
357 if (! isspace((int) sptr[pos])) break;
358 sptr[pos+1] = '\0'; /* ignore trailing whitespace */
364 strncpy(sqinfo->name, sptr, SQINFO_NAMELEN-1);
365 sqinfo->name[SQINFO_NAMELEN-1] = '\0';
366 sqinfo->flags |= SQINFO_NAME;
373 strncpy(sqinfo->id, sptr, SQINFO_NAMELEN-1);
374 sqinfo->id[SQINFO_NAMELEN-1] = '\0';
375 sqinfo->flags |= SQINFO_ID;
382 strncpy(sqinfo->acc, sptr, SQINFO_NAMELEN-1);
383 sqinfo->acc[SQINFO_NAMELEN-1] = '\0';
384 sqinfo->flags |= SQINFO_ACC;
391 if (sqinfo->flags & SQINFO_DESC) /* append? */
393 len = strlen(sqinfo->desc);
394 if (len < SQINFO_DESCLEN-2) /* is there room? */
396 strncat(sqinfo->desc, " ", SQINFO_DESCLEN-1-len); len++;
397 strncat(sqinfo->desc, sptr, SQINFO_DESCLEN-1-len);
401 strncpy(sqinfo->desc, sptr, SQINFO_DESCLEN-1);
402 sqinfo->desc[SQINFO_DESCLEN-1] = '\0';
403 sqinfo->flags |= SQINFO_DESC;
408 if (!IsInt(sptr)) { squid_errno = SQERR_FORMAT; return 0; }
409 sqinfo->start = atoi(sptr);
410 if (sqinfo->start != 0) sqinfo->flags |= SQINFO_START;
414 if (!IsInt(sptr)) { squid_errno = SQERR_FORMAT; return 0; }
415 sqinfo->stop = atoi(sptr);
416 if (sqinfo->stop != 0) sqinfo->flags |= SQINFO_STOP;
420 if (!IsInt(sptr)) { squid_errno = SQERR_FORMAT; return 0; }
421 sqinfo->olen = atoi(sptr);
422 if (sqinfo->olen != 0) sqinfo->flags |= SQINFO_OLEN;
426 Die("Invalid flag %d to SetSeqinfoString()", flag);
432 SeqinfoCopy(SQINFO *sq1, SQINFO *sq2)
434 sq1->flags = sq2->flags;
435 if (sq2->flags & SQINFO_NAME) strcpy(sq1->name, sq2->name);
436 if (sq2->flags & SQINFO_ID) strcpy(sq1->id, sq2->id);
437 if (sq2->flags & SQINFO_ACC) strcpy(sq1->acc, sq2->acc);
438 if (sq2->flags & SQINFO_DESC) strcpy(sq1->desc, sq2->desc);
439 if (sq2->flags & SQINFO_LEN) sq1->len = sq2->len;
440 if (sq2->flags & SQINFO_START) sq1->start = sq2->start;
441 if (sq2->flags & SQINFO_STOP) sq1->stop = sq2->stop;
442 if (sq2->flags & SQINFO_OLEN) sq1->olen = sq2->olen;
443 if (sq2->flags & SQINFO_TYPE) sq1->type = sq2->type;
444 if (sq2->flags & SQINFO_SS) sq1->ss = Strdup(sq2->ss);
445 if (sq2->flags & SQINFO_SA) sq1->sa = Strdup(sq2->sa);
446 if (sq2->flags & SQINFO_CO) sq1->co = Strdup(sq2->co);
451 * Purpose: Convert a sequence to DNA.
457 for (; *seq != '\0'; seq++)
459 if (*seq == 'U') *seq = 'T';
460 else if (*seq == 'u') *seq = 't';
466 * Purpose: Convert a sequence to RNA.
472 for (; *seq != '\0'; seq++)
474 if (*seq == 'T') *seq = 'U';
475 else if (*seq == 't') *seq = 'u';
480 /* Function: ToIUPAC()
482 * Purpose: Convert X's, o's, other junk in a nucleic acid sequence to N's,
483 * to comply with IUPAC code. If is_aseq is TRUE, will allow gap
484 * characters though, so we can call ToIUPAC() on aligned seqs.
486 * NUCLEOTIDES is defined in squid.h as:
487 * "ACGTUNRYMKSWHBVDacgtunrymkswhbvd"
488 * gap chars allowed by isgap() are defined in squid.h as:
491 * WU-BLAST's pressdb will
492 * choke on X's, for instance, necessitating conversion
493 * of certain genome centers' data.
496 ToIUPAC(char *seq, int is_aseq)
499 for (; *seq != '\0'; seq++)
500 if (strchr(NUCLEOTIDES, *seq) == NULL && ! isgap(*seq)) *seq = 'N';
502 for (; *seq != '\0'; seq++)
503 if (strchr(NUCLEOTIDES, *seq) == NULL) *seq = 'N';
508 /* Function: addseq()
510 * Purpose: Add a line of sequence to the growing string in V.
512 * In the seven supported unaligned formats, all sequence
513 * lines may contain whitespace that must be filtered out;
514 * four formats (PIR, EMBL, Genbank, GCG) include coordinates
515 * that must be filtered out. Thus an (!isdigit && !isspace)
516 * test on each character before we accept it.
519 addseq(char *s, struct ReadSeqVars *V)
523 int rpl; /* valid residues per line */
524 int bpl; /* characters per line */
526 if (V->ssimode == -1)
527 { /* Normal mode: keeping the seq */
528 /* Make sure we have enough room. We know that s is <= buflen,
529 * so just make sure we've got room for a whole new buflen worth
532 if (V->seqlen + V->buflen > V->maxseq) {
533 V->maxseq += MAX(V->buflen, kStartLength);
534 V->seq = ReallocOrDie (V->seq, V->maxseq+1);
537 sq = V->seq + V->seqlen;
540 if (! isdigit((int) *s) && ! isspace((int) *s) && isprint((int) *s)) {
542 if (! isdigit((int) *s) && ! isspace((int) *s)) {
549 V->seqlen = sq - V->seq;
551 else /* else: indexing mode, discard the seq */
556 if (! isdigit((int) *s) && ! isspace((int) *s)) {
564 /* Keep track of the global rpl, bpl for the file.
565 * This is overly complicated because we have to
566 * allow the last line of each record (e.g. the last addseq() call
567 * on each sequence) to have a different length - and sometimes
568 * we'll have one-line sequence records, too. Thus we only
569 * do something with the global V->rpl when we have *passed over*
570 * a line - we keep the last line's rpl in last_rpl. And because
571 * a file might consist entirely of single-line records, we keep
572 * a third guy, maxrpl, that tells us the maximum rpl of any line
573 * in the file. If we reach the end of file and rpl is still unset,
574 * we'll set it to maxrpl. If we reach eof and rpl is set, but is
575 * less than maxrpl, that's a weird case where a last line in some
576 * record is longer than every other line.
578 if (V->rpl != 0) { /* 0 means we already know rpl is invalid */
579 if (V->lastrpl > 0) { /* we're on something that's not the first line */
580 if (V->rpl > 0 && V->lastrpl != V->rpl) V->rpl = 0;
581 else if (V->rpl == -1) V->rpl = V->lastrpl;
584 if (rpl > V->maxrpl) V->maxrpl = rpl; /* make sure we check max length of final lines */
586 if (V->bpl != 0) { /* 0 means we already know bpl is invalid */
587 if (V->lastbpl > 0) { /* we're on something that's not the first line */
588 if (V->bpl > 0 && V->lastbpl != V->bpl) V->bpl = 0;
589 else if (V->bpl == -1) V->bpl = V->lastbpl;
592 if (bpl > V->maxbpl) V->maxbpl = bpl; /* make sure we check max length of final lines */
594 } /* end of indexing mode of addseq(). */
599 readLoop(int addfirst, int (*endTest)(char *,int *), struct ReadSeqVars *V)
605 V->lastrpl = V->lastbpl = 0;
607 if (V->ssimode >= 0) V->d_off = V->ssioffset;
609 } else if (V->ssimode >= 0)
610 if (0 != SSIGetFilePosition(V->f, V->ssimode, &(V->d_off)))
611 Die("SSIGetFilePosition() failed");
615 /* feof() alone is a bug; files not necessarily \n terminated */
616 if (*(V->buf) == '\0' && feof(V->f))
618 done |= (*endTest)(V->buf, &addend);
626 endPIR(char *s, int *addend)
629 if ((strncmp(s, "///", 3) == 0) ||
630 (strncmp(s, "ENTRY", 5) == 0))
637 readPIR(struct ReadSeqVars *V)
640 /* load first line of entry */
641 while (!feof(V->f) && strncmp(V->buf, "ENTRY", 5) != 0) {
644 if (feof(V->f)) return;
645 if (V->ssimode >= 0) V->r_off = V->ssioffset;
647 if ((sptr = strtok(V->buf + 15, "\n\t ")) != NULL)
649 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
650 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ID);
654 if (!feof(V->f) && strncmp(V->buf, "TITLE", 5) == 0)
655 SetSeqinfoString(V->sqinfo, V->buf+15, SQINFO_DESC);
656 else if (!feof(V->f) && strncmp(V->buf, "ACCESSION", 9) == 0)
658 if ((sptr = strtok(V->buf+15, " \t\n")) != NULL)
659 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ACC);
661 } while (! feof(V->f) && (strncmp(V->buf,"SEQUENCE", 8) != 0));
662 SeqfileGetLine(V); /* skip next line, coords */
664 readLoop(0, endPIR, V);
666 /* reading a real PIR-CODATA database file, we keep the source coords
668 V->sqinfo->start = 1;
669 V->sqinfo->stop = V->seqlen;
670 V->sqinfo->olen = V->seqlen;
671 V->sqinfo->flags |= SQINFO_START | SQINFO_STOP | SQINFO_OLEN;
675 while (!feof(V->f) && strncmp(V->buf, "ENTRY", 5) != 0) {
683 endIG(char *s, int *addend)
685 *addend = 1; /* 1 or 2 occur in line w/ bases */
686 return((strchr(s,'1')!=NULL) || (strchr(s,'2')!=NULL));
690 readIG(struct ReadSeqVars *V)
693 /* position past ';' comments */
696 } while (! (feof(V->f) || ((*V->buf != 0) && (*V->buf != ';')) ));
700 if ((nm = strtok(V->buf, "\n\t ")) != NULL)
701 SetSeqinfoString(V->sqinfo, nm, SQINFO_NAME);
703 readLoop(0, endIG, V);
706 while (!(feof(V->f) || ((*V->buf != '\0') && (*V->buf == ';'))))
711 endStrider(char *s, int *addend)
714 return (strstr( s, "//") != NULL);
718 readStrider(struct ReadSeqVars *V)
722 while ((!feof(V->f)) && (*V->buf == ';'))
724 if (strncmp(V->buf,"; DNA sequence", 14) == 0)
726 if ((nm = strtok(V->buf+16, ",\n\t ")) != NULL)
727 SetSeqinfoString(V->sqinfo, nm, SQINFO_NAME);
733 readLoop(1, endStrider, V);
737 while ((!feof(V->f)) && (*V->buf != ';'))
743 endGB(char *s, int *addend)
746 return ((strstr(s,"//") != NULL) || (strstr(s,"LOCUS") == s));
750 readGenBank(struct ReadSeqVars *V)
755 /* We'll map three genbank identifiers onto names:
756 * LOCUS -> sqinfo.name
757 * ACCESSION -> sqinfo.acc [primary accession only]
758 * VERSION -> sqinfo.id
759 * We don't currently store the GI number, or secondary accessions.
761 while (strncmp(V->buf, "LOCUS", 5) != 0) {
764 if (V->ssimode >= 0) V->r_off = V->ssioffset;
766 if ((sptr = strtok(V->buf+12, "\n\t ")) != NULL)
767 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
769 in_definition = FALSE;
773 if (! feof(V->f) && strstr(V->buf, "DEFINITION") == V->buf)
775 if ((sptr = strtok(V->buf+12, "\n")) != NULL)
776 SetSeqinfoString(V->sqinfo, sptr, SQINFO_DESC);
777 in_definition = TRUE;
779 else if (! feof(V->f) && strstr(V->buf, "ACCESSION") == V->buf)
781 if ((sptr = strtok(V->buf+12, "\n\t ")) != NULL)
782 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ACC);
783 in_definition = FALSE;
785 else if (! feof(V->f) && strstr(V->buf, "VERSION") == V->buf)
787 if ((sptr = strtok(V->buf+12, "\n\t ")) != NULL)
788 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ID);
789 in_definition = FALSE;
791 else if (strncmp(V->buf,"ORIGIN", 6) != 0)
794 SetSeqinfoString(V->sqinfo, V->buf, SQINFO_DESC);
800 readLoop(0, endGB, V);
802 /* reading a real GenBank database file, we keep the source coords
804 V->sqinfo->start = 1;
805 V->sqinfo->stop = V->seqlen;
806 V->sqinfo->olen = V->seqlen;
807 V->sqinfo->flags |= SQINFO_START | SQINFO_STOP | SQINFO_OLEN;
810 while (!(feof(V->f) || ((*V->buf!=0) && (strstr(V->buf,"LOCUS") == V->buf))))
812 /* SRE: V->s now holds "//", so sequential
813 reads are wedged: fixed Tue Jul 13 1993 */
814 while (!feof(V->f) && strstr(V->buf, "LOCUS ") != V->buf)
819 endGCGdata(char *s, int *addend)
826 readGCGdata(struct ReadSeqVars *V)
828 int binary = FALSE; /* whether data are binary or not */
829 int blen = 0; /* length of binary sequence */
831 /* first line contains ">>>>" followed by name */
832 if (Strparse(">>>>([^ ]+) .+2BIT +Len: ([0-9]+)", V->buf, 2))
835 SetSeqinfoString(V->sqinfo, sqd_parse[1], SQINFO_NAME);
836 blen = atoi(sqd_parse[2]);
838 else if (Strparse(">>>>([^ ]+) .+ASCII +Len: [0-9]+", V->buf, 1))
839 SetSeqinfoString(V->sqinfo, sqd_parse[1], SQINFO_NAME);
841 Die("bogus GCGdata format? %s", V->buf);
843 /* second line contains free text description */
845 SetSeqinfoString(V->sqinfo, V->buf, SQINFO_DESC);
848 /* allocate for blen characters +3... (allow for 3 bytes of slop) */
849 if (blen >= V->maxseq) {
851 if ((V->seq = (char *) realloc (V->seq, sizeof(char)*(V->maxseq+4)))==NULL)
852 Die("malloc failed");
854 /* read (blen+3)/4 bytes from file */
855 if (fread(V->seq, sizeof(char), (blen+3)/4, V->f) < (size_t) ((blen+3)/4))
858 /* convert binary code to seq */
859 GCGBinaryToSequence(V->seq, blen);
861 else readLoop(0, endGCGdata, V);
863 while (!(feof(V->f) || ((*V->buf != 0) && (*V->buf == '>'))))
868 endPearson(char *s, int *addend)
876 only_whitespace(const char *s) {
878 if (!isspace((unsigned char)*s))
887 readPearson(struct ReadSeqVars *V)
891 if (V->ssimode >= 0) V->r_off = V->ssioffset;
894 while (only_whitespace(V->buf)) {
898 if (feof(V->f) || *V->buf != '>')
904 File %s does not appear to be in FASTA format at line %d.\n\
905 You may want to specify the file format on the command line.\n\
906 Usually this is done with an option --infmt <fmt>.\n",
907 V->fname, V->linenumber);
910 File %s does not appear to be in FASTA format at line %d.\n\
911 You may want to specify the file format on the command line.\n\
912 Usually this is done with an option --informat <fmt>.\n",
913 V->fname, V->linenumber);
915 if ((sptr = strtok(V->buf+1, "\n\t ")) != NULL)
916 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
917 if ((sptr = strtok(NULL, "\n")) != NULL)
918 SetSeqinfoString(V->sqinfo, sptr, SQINFO_DESC);
920 readLoop(0, endPearson, V);
922 while (!(feof(V->f) || ((*V->buf != 0) && (*V->buf == '>')))) {
929 endEMBL(char *s, int *addend)
932 /* Some people (Berlin 5S rRNA database, f'r instance) use
933 * an extended EMBL format that attaches extra data after
934 * the sequence -- watch out for that. We use the fact that
935 * real EMBL sequence lines begin with five spaces.
937 * We can use this as the sole end test because readEMBL() will
938 * advance to the next ID line before starting to read again.
940 return (strncmp(s," ",5) != 0);
941 /* return ((strstr(s,"//") != NULL) || (strstr(s,"ID ") == s)); */
945 readEMBL(struct ReadSeqVars *V)
949 /* make sure we have first line */
950 while (!feof(V->f) && strncmp(V->buf, "ID ", 4) != 0) {
953 if (V->ssimode >= 0) V->r_off = V->ssioffset;
955 if ((sptr = strtok(V->buf+5, "\n\t ")) != NULL)
957 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
958 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ID);
963 if (!feof(V->f) && strstr(V->buf, "AC ") == V->buf)
965 if ((sptr = strtok(V->buf+5, "; \t\n")) != NULL)
966 SetSeqinfoString(V->sqinfo, sptr, SQINFO_ACC);
968 else if (!feof(V->f) && strstr(V->buf, "DE ") == V->buf)
970 if ((sptr = strtok(V->buf+5, "\n")) != NULL)
971 SetSeqinfoString(V->sqinfo, sptr, SQINFO_DESC);
973 } while (! feof(V->f) && strncmp(V->buf,"SQ",2) != 0);
975 readLoop(0, endEMBL, V);
977 /* Hack for Staden experiment files: convert - to N
979 if (V->ssimode == -1) /* if we're in ssi mode, we're not keeping the seq */
980 for (sptr = V->seq; *sptr != '\0'; sptr++)
981 if (*sptr == '-') *sptr = 'N';
983 /* reading a real EMBL database file, we keep the source coords
985 V->sqinfo->start = 1;
986 V->sqinfo->stop = V->seqlen;
987 V->sqinfo->olen = V->seqlen;
988 V->sqinfo->flags |= SQINFO_START | SQINFO_STOP | SQINFO_OLEN;
990 /* load next record's ID line */
991 while (!feof(V->f) && strncmp(V->buf, "ID ", 4) != 0) {
999 endZuker(char *s, int *addend)
1002 return( *s == '(' );
1006 readZuker(struct ReadSeqVars *V)
1010 SeqfileGetLine(V); /*s == "seqLen seqid string..."*/
1012 if ((sptr = strtok(V->buf+6, " \t\n")) != NULL)
1013 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
1015 if ((sptr = strtok(NULL, "\n")) != NULL)
1016 SetSeqinfoString(V->sqinfo, sptr, SQINFO_DESC);
1018 readLoop(0, endZuker, V);
1020 while (!(feof(V->f) | ((*V->buf != '\0') & (*V->buf == '('))))
1025 readUWGCG(struct ReadSeqVars *V)
1033 /*writeseq: " %s Length: %d (today) Check: %d ..\n" */
1034 /*drop above or ".." from id*/
1035 if ((si = strstr(V->buf," Length: ")) != NULL) *si = 0;
1036 else if ((si = strstr(V->buf,"..")) != NULL) *si = 0;
1038 if ((sptr = strtok(V->buf, "\n\t ")) != NULL)
1039 SetSeqinfoString(V->sqinfo, sptr, SQINFO_NAME);
1044 if (! done) addseq(V->buf, V);
1049 /* Function: ReadSeq()
1051 * Purpose: Read next sequence from an open database file.
1052 * Return the sequence and associated info.
1054 * Args: fp - open sequence database file pointer
1055 * format - format of the file (previously determined
1056 * by call to SeqfileFormat()).
1057 * Currently unused, since we carry it in V.
1058 * ret_seq - RETURN: sequence
1059 * sqinfo - RETURN: filled in w/ other information
1061 * Limitations: uses squid_errno, so it's not threadsafe.
1063 * Return: 1 on success, 0 on failure.
1064 * ret_seq and some field of sqinfo are allocated here,
1065 * The preferred call mechanism to properly free the memory is:
1070 * ReadSeq(fp, format, &seq, &sqinfo);
1071 * ... do something...
1072 * FreeSequence(seq, &sqinfo);
1075 ReadSeq(SQFILE *V, int format, char **ret_seq, SQINFO *sqinfo)
1079 squid_errno = SQERR_OK;
1081 /* Here's the hack for sequential access of sequences from
1082 * the multiple sequence alignment formats
1084 if (IsAlignmentFormat(V->format))
1086 if (V->msa->lastidx >= V->msa->nseq)
1087 { /* out of data. try to read another alignment */
1089 if ((V->msa = MSAFileRead(V->afp)) == NULL)
1091 V->msa->lastidx = 0;
1093 /* copy and dealign the appropriate aligned seq */
1094 /* AW: stopping squid from dealigning sequences and corresponding info */
1096 V->seq = sre_strdup(V->msa->aseq[V->msa->lastidx], V->msa->alen);
1098 MakeDealignedString(V->msa->aseq[V->msa->lastidx], V->msa->alen,
1099 V->msa->aseq[V->msa->lastidx], &(V->seq));
1101 V->seqlen = strlen(V->seq);
1103 /* Extract sqinfo stuff for this sequence from the msa.
1104 * Tedious; code that should be cleaned.
1107 if (V->msa->sqname[V->msa->lastidx] != NULL)
1108 SetSeqinfoString(sqinfo, V->msa->sqname[V->msa->lastidx], SQINFO_NAME);
1109 if (V->msa->sqacc != NULL && V->msa->sqacc[V->msa->lastidx] != NULL)
1110 SetSeqinfoString(sqinfo, V->msa->sqacc[V->msa->lastidx], SQINFO_ACC);
1111 if (V->msa->sqdesc != NULL && V->msa->sqdesc[V->msa->lastidx] != NULL)
1112 SetSeqinfoString(sqinfo, V->msa->sqdesc[V->msa->lastidx], SQINFO_DESC);
1113 if (V->msa->ss != NULL && V->msa->ss[V->msa->lastidx] != NULL) {
1114 /* AW: stopping squid from dealigning sequences and corresponding info */
1116 sqinfo->ss = sre_strdup(V->msa->ss[V->msa->lastidx], V->msa->alen);
1118 MakeDealignedString(V->msa->aseq[V->msa->lastidx], V->msa->alen,
1119 V->msa->ss[V->msa->lastidx], &(sqinfo->ss));
1121 sqinfo->flags |= SQINFO_SS;
1123 if (V->msa->sa != NULL && V->msa->sa[V->msa->lastidx] != NULL) {
1124 /* AW: stopping squid from dealigning sequences and corresponding info */
1126 sqinfo->sa = sre_strdup(V->msa->sa[V->msa->lastidx], V->msa->alen);
1128 MakeDealignedString(V->msa->aseq[V->msa->lastidx], V->msa->alen,
1129 V->msa->sa[V->msa->lastidx], &(sqinfo->sa));
1131 sqinfo->flags |= SQINFO_SA;
1133 if (V->msa->co != NULL && V->msa->co[V->msa->lastidx] != NULL) {
1134 /* AW: stopping squid from dealigning sequences and corresponding info */
1136 sqinfo->co = sre_strdup(V->msa->co[V->msa->lastidx], V->msa->alen);
1138 MakeDealignedString(V->msa->aseq[V->msa->lastidx], V->msa->alen,
1139 V->msa->co[V->msa->lastidx], &(sqinfo->co));
1141 sqinfo->flags |= SQINFO_CO;
1146 if (feof(V->f)) return 0;
1148 if (V->ssimode == -1) { /* normal mode */
1149 V->seq = (char*) calloc (kStartLength+1, sizeof(char));
1150 V->maxseq = kStartLength;
1151 } else { /* index mode: discarding seq */
1157 V->sqinfo->flags = 0;
1159 switch (V->format) {
1160 case SQFILE_IG : readIG(V); break;
1161 case SQFILE_STRIDER : readStrider(V); break;
1162 case SQFILE_GENBANK : readGenBank(V); break;
1163 case SQFILE_FASTA : readPearson(V); break;
1164 case SQFILE_EMBL : readEMBL(V); break;
1165 case SQFILE_ZUKER : readZuker(V); break;
1166 case SQFILE_PIR : readPIR(V); break;
1167 case SQFILE_GCGDATA : readGCGdata(V); break;
1170 do { /* skip leading comments on GCG file */
1171 gotuw = (strstr(V->buf,"..") != NULL);
1172 if (gotuw) readUWGCG(V);
1174 } while (! feof(V->f));
1177 case SQFILE_IDRAW: /* SRE: no attempt to read idraw postscript */
1179 squid_errno = SQERR_FORMAT;
1183 if (V->seq != NULL) /* (it can be NULL in indexing mode) */
1184 V->seq[V->seqlen] = 0; /* stick a string terminator on it */
1189 sqinfo->len = V->seqlen;
1190 sqinfo->flags |= SQINFO_LEN;
1192 if (squid_errno == SQERR_OK) return 1; else return 0;
1195 /* Function: SeqfileFormat()
1196 * Date: SRE, Tue Jun 22 10:58:58 1999 [Sanger Centre]
1198 * Purpose: Determine format of an open file.
1199 * Returns format code.
1202 * Autodetects the following unaligned formats:
1209 * Also autodetects the following alignment formats:
1216 * Can't autodetect MSAFILE_A2M, calls it SQFILE_FASTA.
1217 * MSAFileFormat() does the opposite.
1219 * Args: sfp - open SQFILE
1221 * Return: format code, or SQFILE_UNKNOWN if unrecognized
1224 SeqfileFormat(FILE *fp)
1228 int fmt = SQFILE_UNKNOWN;
1230 char *bufcpy, *s, *s1, *s2;
1237 while (sre_fgets(&buf, &len, fp) != NULL)
1239 if (IsBlankline(buf)) continue;
1241 /* Well-behaved formats identify themselves in first nonblank line.
1245 if (strncmp(buf, ">>>>", 4) == 0 && strstr(buf, "Len: "))
1246 { fmt = SQFILE_GCGDATA; goto DONE; }
1249 { fmt = SQFILE_FASTA; goto DONE; }
1251 if (strncmp(buf, "!!AA_SEQUENCE", 13) == 0 ||
1252 strncmp(buf, "!!NA_SEQUENCE", 13) == 0)
1253 { fmt = SQFILE_GCG; goto DONE; }
1255 if (strncmp(buf, "# DUBLIN 1.", 11) == 0) /* -> r296, FS */
1256 { fmt = MSAFILE_DUBLIN; goto DONE; }
1258 if (strncmp(buf, "# STOCKHOLM 1.", 14) == 0)
1259 { fmt = MSAFILE_STOCKHOLM; goto DONE; }
1261 if (strncmp(buf, "CLUSTAL", 7) == 0 &&
1262 strstr(buf, "multiple sequence alignment") != NULL)
1263 { fmt = MSAFILE_CLUSTAL; goto DONE; }
1265 if (strncmp(buf, "!!AA_MULTIPLE_ALIGNMENT", 23) == 0 ||
1266 strncmp(buf, "!!NA_MULTIPLE_ALIGNMENT", 23) == 0)
1267 { fmt = MSAFILE_MSF; goto DONE; }
1269 /* PHYLIP id: also just a good bet */
1270 bufcpy = sre_strdup(buf, -1);
1272 if ((s1 = sre_strtok(&s, WHITESPACE, NULL)) != NULL &&
1273 (s2 = sre_strtok(&s, WHITESPACE, NULL)) != NULL &&
1276 { free(bufcpy); fmt = MSAFILE_PHYLIP; goto DONE; }
1280 /* We trust that other formats identify themselves soon.
1282 /* dead giveaways for extended SELEX */
1283 if (strncmp(buf, "#=AU", 4) == 0 ||
1284 strncmp(buf, "#=ID", 4) == 0 ||
1285 strncmp(buf, "#=AC", 4) == 0 ||
1286 strncmp(buf, "#=DE", 4) == 0 ||
1287 strncmp(buf, "#=GA", 4) == 0 ||
1288 strncmp(buf, "#=TC", 4) == 0 ||
1289 strncmp(buf, "#=NC", 4) == 0 ||
1290 strncmp(buf, "#=SQ", 4) == 0 ||
1291 strncmp(buf, "#=SS", 4) == 0 ||
1292 strncmp(buf, "#=CS", 4) == 0 ||
1293 strncmp(buf, "#=RF", 4) == 0)
1294 { fmt = MSAFILE_SELEX; goto DONE; }
1296 if (strncmp(buf, "///", 3) == 0 || strncmp(buf, "ENTRY ", 6) == 0)
1297 { fmt = SQFILE_PIR; goto DONE; }
1299 /* a ha, diagnostic of an (old) MSF file */
1300 if ((strstr(buf, "..") != NULL) &&
1301 (strstr(buf, "MSF:") != NULL) &&
1302 (strstr(buf, "Check:")!= NULL))
1303 { fmt = MSAFILE_MSF; goto DONE; }
1305 /* unaligned GCG (must follow MSF test!) */
1306 if (strstr(buf, " Check: ") != NULL && strstr(buf, "..") != NULL)
1307 { fmt = SQFILE_GCG; goto DONE; }
1309 if (strncmp(buf,"LOCUS ",6) == 0 || strncmp(buf,"ORIGIN ",6) == 0)
1310 { fmt = SQFILE_GENBANK; goto DONE; }
1312 if (strncmp(buf,"ID ",5) == 0 || strncmp(buf,"SQ ",5) == 0)
1313 { fmt = SQFILE_EMBL; goto DONE; }
1315 /* But past here, we're being desperate. A simple SELEX file is
1316 * very difficult to detect; we can only try to disprove it.
1319 if ((s1 = sre_strtok(&s, WHITESPACE, NULL)) == NULL) continue; /* skip blank lines */
1320 if (strchr("#%", *s1) != NULL) continue; /* skip comment lines */
1322 /* Disproof 1. Noncomment, nonblank lines in a SELEX file
1323 * must have at least two space-delimited fields (name/seq)
1325 if ((s2 = sre_strtok(&s, WHITESPACE, NULL)) == NULL)
1329 * The sequence field should look like a sequence.
1331 if (s2 != NULL && Seqtype(s2) == kOtherSeq)
1335 if (ndataline == 300) break; /* only look at first 300 lines */
1339 Die("Sequence file contains no data");
1341 /* If we've made it this far, we've run out of data, but there
1342 * was at least one line of it; check if we've
1343 * disproven SELEX. If not, cross our fingers, pray, and guess SELEX.
1345 if (has_junk == TRUE) fmt = SQFILE_UNKNOWN;
1346 else fmt = MSAFILE_SELEX;
1349 if (buf != NULL) free(buf);
1354 /* Function: GCGBinaryToSequence()
1356 * Purpose: Convert a GCG 2BIT binary string to DNA sequence.
1357 * 0 = C 1 = T 2 = A 3 = G
1360 * Args: seq - binary sequence. Converted in place to DNA.
1361 * len - length of DNA. binary is (len+3)/4 bytes
1364 GCGBinaryToSequence(char *seq, int len)
1366 int bpos; /* position in binary */
1367 int spos; /* position in sequence */
1371 for (bpos = (len-1)/4; bpos >= 0; bpos--)
1376 for (i = 3; i >= 0; i--)
1378 switch (twobit & 0x3) {
1379 case 0: seq[spos+i] = 'C'; break;
1380 case 1: seq[spos+i] = 'T'; break;
1381 case 2: seq[spos+i] = 'A'; break;
1382 case 3: seq[spos+i] = 'G'; break;
1384 twobit = twobit >> 2;
1392 /* Function: GCGchecksum()
1393 * Date: SRE, Mon May 31 11:13:21 1999 [St. Louis]
1395 * Purpose: Calculate a GCG checksum for a sequence.
1396 * Code provided by Steve Smith of Genetics
1399 * Args: seq - sequence to calculate checksum for.
1400 * may contain gap symbols.
1401 * len - length of sequence (usually known,
1402 * so save a strlen() call)
1404 * Returns: GCG checksum.
1407 GCGchecksum(char *seq, int len)
1409 int i; /* position in sequence */
1410 int chk = 0; /* calculated checksum */
1412 for (i = 0; i < len; i++)
1413 chk = (chk + (i % 57 + 1) * (sre_toupper((int) seq[i]))) % 10000;
1418 /* Function: GCGMultchecksum()
1420 * Purpose: GCG checksum for a multiple alignment: sum of
1421 * individual sequence checksums (including their
1422 * gap characters) modulo 10000.
1424 * Implemented using spec provided by Steve Smith of
1425 * Genetics Computer Group.
1427 * Args: seqs - sequences to be checksummed; aligned or not
1428 * nseq - number of sequences
1430 * Return: the checksum, a number between 0 and 9999
1433 GCGMultchecksum(char **seqs, int nseq)
1438 for (idx = 0; idx < nseq; idx++)
1439 chk = (chk + GCGchecksum(seqs[idx], strlen(seqs[idx]))) % 10000;
1446 /* Function: Seqtype()
1448 * Purpose: Returns a (very good) guess about type of sequence:
1449 * kDNA, kRNA, kAmino, or kOtherSeq.
1451 * Modified from, and replaces, Gilbert getseqtype().
1456 int saw; /* how many non-gap characters I saw */
1458 int po = 0; /* count of protein-only */
1459 int nt = 0; /* count of t's */
1460 int nu = 0; /* count of u's */
1461 int na = 0; /* count of nucleotides */
1462 int aa = 0; /* count of amino acids */
1463 int no = 0; /* count of others */
1465 /* Look at the first 300 non-gap characters
1469 /* VGGNGDDYLSGGTGNDTL is recognized as unknown using squid's default
1471 * We change it to the following:
1473 * 1. counting: ignore gaps and not alpha characters. if protein-only then
1474 * count as such (po). otherwise decide if amino-acid (aa) or nucleic-acid
1475 * (na) or unknown (no)
1477 * 2. determine type: if we saw more unknown than aa or na, return unknown.
1478 * if encountered protein-only return protein-only. otherwise decide based
1479 * on majority. (if aa==na return na)
1481 for (saw = 0; *seq != '\0' && saw < 300; seq++) {
1482 c = sre_toupper((int) *seq);
1485 if (isgap(c) || ! isalpha((int) c)) {
1489 if (strchr(protonly, c)) {
1494 if (strchr(aminos,c)) {
1499 if (strchr(primenuc,c)) {
1516 if (no > aa && no > na)
1519 if (po > 0 || aa>na)
1533 for (saw = 0; *seq != '\0' && saw < 300; seq++)
1535 c = sre_toupper((int) *seq);
1538 if (strchr(protonly, c)) po++;
1539 else if (strchr(primenuc,c)) {
1542 else if (c == 'U') nu++;
1544 else if (strchr(aminos,c)) aa++;
1545 else if (isalpha((int) c)) no++;
1550 if (no > 0) return kOtherSeq;
1551 else if (po > 0) return kAmino;
1553 if (nu > nt) return kRNA;
1556 else return kAmino; /* ooooh. risky. */
1562 /* Function: GuessAlignmentSeqtype()
1563 * Date: SRE, Wed Jul 7 09:42:34 1999 [St. Louis]
1565 * Purpose: Try to guess whether an alignment is protein
1566 * or nucleic acid; return a code for the
1567 * type (kRNA, kDNA, or kAmino).
1569 * Args: aseq - array of aligned sequences. (Could also
1570 * be an rseq unaligned sequence array)
1571 * nseq - number of aseqs
1573 * Returns: kRNA, kDNA, kAmino;
1574 * kOtherSeq if inconsistency is detected.
1577 GuessAlignmentSeqtype(char **aseq, int nseq)
1585 for (idx = 0; idx < nseq; idx++)
1586 switch (Seqtype(aseq[idx])) {
1587 case kRNA: nrna++; break;
1588 case kDNA: ndna++; break;
1589 case kAmino: namino++; break;
1593 /* Unambiguous decisions:
1595 if (nother) return kOtherSeq;
1596 if (namino == nseq) return kAmino;
1597 if (ndna == nseq) return kDNA;
1598 if (nrna == nseq) return kRNA;
1600 /* Ambiguous decisions:
1602 if (namino == 0) return kRNA; /* it's nucleic acid, but seems mixed RNA/DNA */
1603 return kAmino; /* some amino acid seen; others probably short seqs, some
1604 of which may be entirely ACGT (ala,cys,gly,thr). We
1605 could be a little more sophisticated: U would be a giveaway
1606 that we're not in protein seqs */
1609 /* Function: WriteSimpleFASTA()
1610 * Date: SRE, Tue Nov 16 18:06:00 1999 [St. Louis]
1612 * Purpose: Just write a FASTA format sequence to a file;
1613 * minimal interface, mostly for quick and dirty programs.
1615 * Args: fp - open file handle (stdout, possibly)
1616 * seq - sequence to output
1617 * name - name for the sequence
1618 * desc - optional description line, or NULL.
1623 WriteSimpleFASTA(FILE *fp, char *seq, char *name, char *desc)
1631 fprintf(fp, ">%s %s\n", name, desc != NULL ? desc : "");
1632 for (pos = 0; pos < len; pos += 60)
1634 strncpy(buf, seq+pos, 60);
1635 fprintf(fp, "%s\n", buf);
1640 WriteSeq(FILE *outf, int outform, char *seq, SQINFO *sqinfo)
1643 int lines = 0, spacer = 0, width = 50, tab = 0;
1644 int i, j, l, l1, ibase;
1646 char s[100]; /* buffer for sequence */
1647 char ss[100]; /* buffer for structure */
1650 int which_case; /* 0 = do nothing. 1 = upper case. 2 = lower case */
1651 int dostruc; /* TRUE to print structure lines*/
1655 seqlen = (sqinfo->flags & SQINFO_LEN) ? sqinfo->len : strlen(seq);
1657 if (IsAlignmentFormat(outform))
1658 Die("Tried to write an aligned format with WriteSeq() -- bad, bad.");
1663 checksum = GCGchecksum(seq, seqlen);
1666 case SQFILE_UNKNOWN: /* no header, just sequence */
1667 strcpy(endstr,"\n"); /* end w/ extra blank line */
1670 case SQFILE_GENBANK:
1671 fprintf(outf,"LOCUS %s %d bp\n",
1672 sqinfo->name, seqlen);
1673 fprintf(outf,"ACCESSION %s\n",
1674 (sqinfo->flags & SQINFO_ACC) ? sqinfo->acc : ".");
1675 fprintf(outf,"DEFINITION %s\n",
1676 (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : ".");
1677 fprintf(outf,"VERSION %s\n",
1678 (sqinfo->flags & SQINFO_ID) ? sqinfo->id : ".");
1679 fprintf(outf,"ORIGIN \n");
1682 strcpy(endstr, "\n//");
1685 case SQFILE_GCGDATA:
1686 fprintf(outf, ">>>>%s 9/95 ASCII Len: %d\n", sqinfo->name, seqlen);
1687 fprintf(outf, "%s\n", (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : "-");
1691 fprintf(outf, "ENTRY %s\n",
1692 (sqinfo->flags & SQINFO_ID) ? sqinfo->id : sqinfo->name);
1693 fprintf(outf, "TITLE %s\n",
1694 (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : "-");
1695 fprintf(outf, "ACCESSION %s\n",
1696 (sqinfo->flags & SQINFO_ACC) ? sqinfo->acc : "-");
1697 fprintf(outf, "SUMMARY #Length %d #Checksum %d\n",
1698 sqinfo->len, checksum);
1699 fprintf(outf, "SEQUENCE\n");
1700 fprintf(outf, " 5 10 15 20 25 30\n");
1701 spacer = 2; /* spaces after every residue */
1702 numline = 1; /* number lines w/ coords */
1703 width = 30; /* 30 aa per line */
1704 strcpy(endstr, "\n///");
1708 fprintf(outf, "NAM %s\n", sqinfo->name);
1709 if (sqinfo->flags & (SQINFO_ID | SQINFO_ACC | SQINFO_START | SQINFO_STOP | SQINFO_OLEN))
1710 fprintf(outf, "SRC %s %s %d..%d::%d\n",
1711 (sqinfo->flags & SQINFO_ID) ? sqinfo->id : "-",
1712 (sqinfo->flags & SQINFO_ACC) ? sqinfo->acc : "-",
1713 (sqinfo->flags & SQINFO_START) ? sqinfo->start : 0,
1714 (sqinfo->flags & SQINFO_STOP) ? sqinfo->stop : 0,
1715 (sqinfo->flags & SQINFO_OLEN) ? sqinfo->olen : 0);
1716 if (sqinfo->flags & SQINFO_DESC)
1717 fprintf(outf, "DES %s\n", sqinfo->desc);
1718 if (sqinfo->flags & SQINFO_SS)
1720 fprintf(outf, "SEQ +SS\n");
1721 dostruc = TRUE; /* print structure lines too */
1724 fprintf(outf, "SEQ\n");
1725 numline = 1; /* number seq lines w/ coords */
1726 strcpy(endstr, "\n++");
1730 fprintf(outf,"ID %s\n",
1731 (sqinfo->flags & SQINFO_ID) ? sqinfo->id : sqinfo->name);
1732 fprintf(outf,"AC %s\n",
1733 (sqinfo->flags & SQINFO_ACC) ? sqinfo->acc : "-");
1734 fprintf(outf,"DE %s\n",
1735 (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : "-");
1736 fprintf(outf,"SQ %d BP\n", seqlen);
1737 strcpy(endstr, "\n//"); /* 11Oct90: bug fix*/
1738 tab = 5; /** added 31jan91 */
1739 spacer = 11; /** added 31jan91 */
1743 fprintf(outf,"%s\n", sqinfo->name);
1744 if (sqinfo->flags & SQINFO_ACC)
1745 fprintf(outf,"ACCESSION %s\n", sqinfo->acc);
1746 if (sqinfo->flags & SQINFO_DESC)
1747 fprintf(outf,"DEFINITION %s\n", sqinfo->desc);
1748 fprintf(outf," %s Length: %d (today) Check: %d ..\n",
1749 sqinfo->name, seqlen, checksum);
1752 strcpy(endstr, "\n"); /* this is insurance to help prevent misreads at eof */
1755 case SQFILE_STRIDER: /* ?? map ?*/
1756 fprintf(outf,"; ### from DNA Strider ;-)\n");
1757 fprintf(outf,"; DNA sequence %s, %d bases, %d checksum.\n;\n",
1758 sqinfo->name, seqlen, checksum);
1759 strcpy(endstr, "\n//");
1762 /* SRE: Don had Zuker default to Pearson, which is not
1763 intuitive or helpful, since Zuker's MFOLD can't read
1764 Pearson format. More useful to use kIG */
1766 which_case = 1; /* MFOLD requires upper case. */
1769 fprintf(outf,";%s %s\n",
1771 (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : "");
1772 fprintf(outf,"%s\n", sqinfo->name);
1773 strcpy(endstr,"1"); /* == linear dna */
1776 case SQFILE_RAW: /* Raw: no header at all. */
1781 fprintf(outf,">%s %s\n", sqinfo->name,
1782 (sqinfo->flags & SQINFO_DESC) ? sqinfo->desc : "");
1786 if (which_case == 1) s2upper(seq);
1787 if (which_case == 2) s2lower(seq);
1790 width = MIN(width,100);
1791 for (i=0, l=0, ibase = 1, lines = 0; i < seqlen; ) {
1794 if (numline) fprintf(outf,"%8d ",ibase);
1795 for (j=0; j<tab; j++) fputc(' ',outf);
1797 if ((spacer != 0) && ((l+1) % spacer == 1))
1798 { s[l] = ' '; ss[l] = ' '; l++; }
1800 ss[l] = (sqinfo->flags & SQINFO_SS) ? sqinfo->ss[i] : '.';
1802 l1++; /* don't count spaces for width*/
1803 if (l1 == width || i == seqlen) {
1804 s[l] = ss[l] = '\0';
1808 fprintf(outf, "%s\n", s);
1809 if (numline) fprintf(outf," ");
1810 for (j=0; j<tab; j++) fputc(' ',outf);
1811 if (i == seqlen) fprintf(outf,"%s%s\n",ss,endstr);
1812 else fprintf(outf,"%s\n",ss);
1816 if (i == seqlen) fprintf(outf,"%s%s\n",s,endstr);
1817 else fprintf(outf,"%s\n",s);
1827 /* Function: ReadMultipleRseqs()
1829 * Purpose: Open a data file and
1830 * parse it into an array of rseqs (raw, unaligned
1833 * Caller is responsible for free'ing memory allocated
1834 * to ret_rseqs, ret_weights, and ret_names.
1836 * Weights are currently only supported for MSF format.
1837 * Sequences read from all other formats will be assigned
1838 * weights of 1.0. If the caller isn't interested in
1839 * weights, it passes NULL as ret_weights.
1841 * Returns 1 on success. Returns 0 on failure and sets
1842 * squid_errno to indicate the cause.
1845 ReadMultipleRseqs(char *seqfile,
1848 SQINFO **ret_sqinfo,
1851 SQINFO *sqinfo; /* array of sequence optional info */
1852 SQFILE *dbfp; /* open ptr for sequential access of file */
1853 char **rseqs; /* sequence array */
1854 int numalloced; /* num of seqs currently alloced for */
1860 rseqs = (char **) MallocOrDie (numalloced * sizeof(char *));
1861 sqinfo = (SQINFO *) MallocOrDie (numalloced * sizeof(SQINFO));
1862 if ((dbfp = SeqfileOpen(seqfile, fformat, NULL)) == NULL) return 0;
1864 while (ReadSeq(dbfp, dbfp->format, &rseqs[num], &(sqinfo[num])))
1867 if (num == numalloced) /* more seqs coming, alloc more room */
1870 rseqs = (char **) ReallocOrDie (rseqs, numalloced*sizeof(char *));
1871 sqinfo = (SQINFO *) ReallocOrDie (sqinfo, numalloced * sizeof(SQINFO));
1877 *ret_sqinfo = sqinfo;
1883 /* Function: String2SeqfileFormat()
1884 * Date: SRE, Sun Jun 27 15:25:54 1999 [TW 723 over Canadian Shield]
1886 * Purpose: Convert a string (e.g. from command line option arg)
1887 * to a format code. Case insensitive. Return
1888 * MSAFILE_UNKNOWN/SQFILE_UNKNOWN if string is bad.
1889 * Uses codes defined in squid.h (unaligned formats) and
1890 * msa.h (aligned formats).
1892 * Args: s - string to convert; e.g. "stockholm"
1894 * Returns: format code; e.g. MSAFILE_STOCKHOLM
1897 String2SeqfileFormat(char *s)
1900 int code = SQFILE_UNKNOWN;
1902 if (s == NULL) return SQFILE_UNKNOWN;
1903 s2 = sre_strdup(s, -1);
1906 if (strcmp(s2, "FASTA") == 0) code = SQFILE_FASTA;
1908 else if (strcmp(s2, "FA") == 0) code = SQFILE_FASTA;
1909 else if (strcmp(s2, "VIENNA") == 0) code = SQFILE_VIENNA;
1910 else if (strcmp(s2, "VIE") == 0) code = SQFILE_VIENNA;
1912 else if (strcmp(s2, "GENBANK") == 0) code = SQFILE_GENBANK;
1914 else if (strcmp(s2, "GB") == 0) code = SQFILE_GENBANK;
1916 else if (strcmp(s2, "EMBL") == 0) code = SQFILE_EMBL;
1917 else if (strcmp(s2, "GCG") == 0) code = SQFILE_GCG;
1918 else if (strcmp(s2, "GCGDATA") == 0) code = SQFILE_GCGDATA;
1919 else if (strcmp(s2, "RAW") == 0) code = SQFILE_RAW;
1920 else if (strcmp(s2, "IG") == 0) code = SQFILE_IG;
1921 else if (strcmp(s2, "STRIDER") == 0) code = SQFILE_STRIDER;
1922 else if (strcmp(s2, "IDRAW") == 0) code = SQFILE_IDRAW;
1923 else if (strcmp(s2, "ZUKER") == 0) code = SQFILE_ZUKER;
1924 else if (strcmp(s2, "PIR") == 0) code = SQFILE_PIR;
1925 else if (strcmp(s2, "SQUID") == 0) code = SQFILE_SQUID;
1926 else if (strcmp(s2, "STOCKHOLM") == 0) code = MSAFILE_STOCKHOLM;
1928 else if (strcmp(s2, "ST") == 0) code = MSAFILE_STOCKHOLM;
1929 else if (strcmp(s2, "STK") == 0) code = MSAFILE_STOCKHOLM;
1931 else if (strcmp(s2, "SELEX") == 0) code = MSAFILE_SELEX;
1932 else if (strcmp(s2, "MSF") == 0) code = MSAFILE_MSF;
1933 else if (strcmp(s2, "CLUSTAL") == 0) code = MSAFILE_CLUSTAL;
1935 else if (strcmp(s2, "CLU") == 0) code = MSAFILE_CLUSTAL;
1937 else if (strcmp(s2, "A2M") == 0) code = MSAFILE_A2M;
1938 else if (strcmp(s2, "PHYLIP") == 0) code = MSAFILE_PHYLIP;
1940 else if (strcmp(s2, "PHY") == 0) code = MSAFILE_PHYLIP;
1942 else if (strcmp(s2, "EPS") == 0) code = MSAFILE_EPS;
1944 else code = SQFILE_UNKNOWN;
1950 SeqfileFormat2String(int code)
1953 case SQFILE_UNKNOWN: return "unknown";
1954 case SQFILE_FASTA: return "FASTA";
1956 case SQFILE_VIENNA: return "Vienna";
1958 case SQFILE_GENBANK: return "Genbank";
1959 case SQFILE_EMBL: return "EMBL";
1960 case SQFILE_GCG: return "GCG";
1961 case SQFILE_GCGDATA: return "GCG data library";
1962 case SQFILE_RAW: return "raw";
1963 case SQFILE_IG: return "Intelligenetics";
1964 case SQFILE_STRIDER: return "MacStrider";
1965 case SQFILE_IDRAW: return "Idraw Postscript";
1966 case SQFILE_ZUKER: return "Zuker";
1967 case SQFILE_PIR: return "PIR";
1968 case SQFILE_SQUID: return "SQUID";
1969 case MSAFILE_STOCKHOLM: return "Stockholm";
1970 case MSAFILE_SELEX: return "SELEX";
1971 case MSAFILE_MSF: return "MSF";
1972 case MSAFILE_CLUSTAL: return "Clustal";
1973 case MSAFILE_A2M: return "a2m";
1974 case MSAFILE_PHYLIP: return "Phylip";
1975 case MSAFILE_EPS: return "EPS";
1977 Die("Bad code passed to MSAFormat2String()");
1984 /* Function: MSAToSqinfo()
1985 * Date: SRE, Tue Jul 20 14:36:56 1999 [St. Louis]
1987 * Purpose: Take an MSA and generate a SQINFO array suitable
1988 * for use in annotating the unaligned sequences.
1991 * Permanent temporary code. sqinfo was poorly designed.
1992 * it must eventually be replaced, but the odds
1993 * of this happening soon are nil, so I have to deal.
1995 * Args: msa - the alignment
1997 * Returns: ptr to allocated sqinfo array.
1998 * Freeing is ghastly: free in each individual sqinfo[i]
1999 * with FreeSequence(NULL, &(sqinfo[i])), then
2003 MSAToSqinfo(MSA *msa)
2008 sqinfo = MallocOrDie(sizeof(SQINFO) * msa->nseq);
2010 for (idx = 0; idx < msa->nseq; idx++)
2012 sqinfo[idx].flags = 0;
2013 SetSeqinfoString(&(sqinfo[idx]),
2014 msa->sqname[idx], SQINFO_NAME);
2015 SetSeqinfoString(&(sqinfo[idx]),
2016 MSAGetSeqAccession(msa, idx), SQINFO_ACC);
2017 SetSeqinfoString(&(sqinfo[idx]),
2018 MSAGetSeqDescription(msa, idx), SQINFO_DESC);
2020 if (msa->ss != NULL && msa->ss[idx] != NULL) {
2021 MakeDealignedString(msa->aseq[idx], msa->alen,
2022 msa->ss[idx], &(sqinfo[idx].ss));
2023 sqinfo[idx].flags |= SQINFO_SS;
2026 if (msa->sa != NULL && msa->sa[idx] != NULL) {
2027 MakeDealignedString(msa->aseq[idx], msa->alen,
2028 msa->sa[idx], &(sqinfo[idx].sa));
2029 sqinfo[idx].flags |= SQINFO_SA;
2032 sqinfo[idx].len = DealignedLength(msa->aseq[idx]);
2033 sqinfo[idx].flags |= SQINFO_LEN;
2040 /* cc -o sqio_test -DA_QUIET_DAY -L. sqio.c -lsquid */
2044 main(int argc, char **argv)
2056 buf = malloc(sizeof(char) * 256);
2057 if ((fp = fopen(filename, "r")) == NULL)
2058 Die("open of %s failed", filename);
2059 while (fgets(buf, 255, fp) != NULL)
2063 } else if (mode == 2) {
2064 if ((fp = fopen(filename, "r")) == NULL)
2065 Die("open of %s failed", filename);
2066 buf = NULL; len = 0;
2067 while (sre_fgets(&buf, &len, fp) != NULL)
2068 SSIGetFilePosition(fp, SSI_OFFSET_I32, &off);
2071 } else if (mode == 3) {
2075 if ((dbfp = SeqfileOpen(filename, SQFILE_FASTA, NULL)) == NULL)
2076 Die("open of %s failed", filename);
2077 while (ReadSeq(dbfp, dbfp->format, &buf, &info)) {
2078 SSIGetFilePosition(dbfp->f, SSI_OFFSET_I32, &off);
2079 FreeSequence(buf, &info);