Debian Codegraph @

hmmer/easel/esl_sqio_ascii.c

raw symbols SCIP
1 /* Unaligned ascii sequence file i/o.
2 *
3 * Contents:
4 * 1. An <ESL_SQFILE> object, in text mode.
5 * 2. An <ESL_SQFILE> object, in digital mode.
6 * 3. Miscellaneous routines.
7 * 4. Sequence reading (sequential).
8 * 5. Sequence/subsequence fetching, random access
9 * 6. Internal routines shared by parsers.
10 * 7. Internal routines for EMBL format (including UniProt, TrEMBL)
11 * 8. Internal routines for GenBank format
12 * 9. Internal routines for FASTA format
13 * 10. Internal routines for daemon format
14 * 11. Internal routines for HMMPGMD format
15 *
16 * This module shares remote evolutionary homology with Don Gilbert's
17 * seminal, public domain ReadSeq package, though the last common
18 * ancestor was circa 1991 and no recognizable vestiges are likely to
19 * remain. Thanks Don!
20 *
21 */
22 #include <esl_config.h>
23
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <unistd.h>
29
30 #include "easel.h"
31 #include "esl_alphabet.h"
32 #include "esl_msa.h"
33 #include "esl_msafile.h"
34 #include "esl_sqio.h"
35 #include "esl_sq.h"
36 #include "esl_ssi.h"
37
38 /* format specific routines */
39 static int sqascii_GuessFileFormat(ESL_SQFILE *sqfp, int *ret_fmt);
40 static int sqascii_Position (ESL_SQFILE *sqfp, off_t offset);
41 static void sqascii_Close (ESL_SQFILE *sqfp);
42 static int sqascii_SetDigital (ESL_SQFILE *sqfp, const ESL_ALPHABET *abc);
43 static int sqascii_GuessAlphabet (ESL_SQFILE *sqfp, int *ret_type);
44 static int sqascii_Read (ESL_SQFILE *sqfp, ESL_SQ *sq);
45 static int sqascii_ReadInfo (ESL_SQFILE *sqfp, ESL_SQ *sq);
46 static int sqascii_ReadSequence (ESL_SQFILE *sqfp, ESL_SQ *sq);
47 static int sqascii_ReadWindow (ESL_SQFILE *sqfp, int C, int W, ESL_SQ *sq);
48 static int sqascii_ReadBlock (ESL_SQFILE *sqfp, ESL_SQ_BLOCK *sqBlock, int max_residues, int max_sequences, int max_init_window, int long_target);
49 static int sqascii_Echo (ESL_SQFILE *sqfp, const ESL_SQ *sq, FILE *ofp);
50
51 static int sqascii_IsRewindable (const ESL_SQFILE *sqfp);
52 static const char *sqascii_GetError (const ESL_SQFILE *sqfp);
53
54 static int sqascii_OpenSSI (ESL_SQFILE *sqfp, const char *ssifile_hint);
55 static int sqascii_PositionByKey (ESL_SQFILE *sqfp, const char *key);
56 static int sqascii_PositionByNumber(ESL_SQFILE *sqfp, int which);
57 static int sqascii_Fetch (ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq);
58 static int sqascii_FetchInfo (ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq);
59 static int sqascii_FetchSubseq (ESL_SQFILE *sqfp, const char *source, int64_t start, int64_t end, ESL_SQ *sq);
60
61 /* Internal routines shared by parsers. */
62 static int loadmem (ESL_SQFILE *sqfp);
63 static int loadbuf (ESL_SQFILE *sqfp);
64 static int nextchar (ESL_SQFILE *sqfp, char *ret_c);
65 static int seebuf (ESL_SQFILE *sqfp, int64_t maxn, int64_t *opt_nres, int64_t *opt_endpos);
66 static void addbuf (ESL_SQFILE *sqfp, ESL_SQ *sq, int64_t nres);
67 static void skipbuf (ESL_SQFILE *sqfp, int64_t nskip);
68 static int read_nres(ESL_SQFILE *sqfp, ESL_SQ *sq, int64_t nskip, int64_t nres, int64_t *opt_actual_nres);
69 static int skip_whitespace(ESL_SQFILE *sqfp);
70
71 /* EMBL format; also UniProt, TrEMBL */
72 static void config_embl(ESL_SQFILE *sqfp);
73 static void inmap_embl (ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap);
74 static int header_embl(ESL_SQFILE *sqfp, ESL_SQ *sq);
75 static int skip_embl (ESL_SQFILE *sqfp, ESL_SQ *sq);
76 static int end_embl (ESL_SQFILE *sqfp, ESL_SQ *sq);
77
78 /* GenBank format; also DDBJ */
79 static void config_genbank(ESL_SQFILE *sqfp);
80 static void inmap_genbank (ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap);
81 static int header_genbank(ESL_SQFILE *sqfp, ESL_SQ *sq);
82 static int skip_genbank (ESL_SQFILE *sqfp, ESL_SQ *sq);
83 static int end_genbank (ESL_SQFILE *sqfp, ESL_SQ *sq);
84
85 /* FASTA format */
86 static void config_fasta(ESL_SQFILE *sqfp);
87 static void inmap_fasta (ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap);
88 static int header_fasta(ESL_SQFILE *sqfp, ESL_SQ *sq);
89 static int skip_fasta (ESL_SQFILE *sqfp, ESL_SQ *sq);
90 static int end_fasta (ESL_SQFILE *sqfp, ESL_SQ *sq);
91
92 /* daemon format */
93 static void config_daemon(ESL_SQFILE *sqfp);
94 static void inmap_daemon (ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap);
95 static int end_daemon (ESL_SQFILE *sqfp, ESL_SQ *sq);
96
97 /* HMMPGMD format */
98 static int fileheader_hmmpgmd(ESL_SQFILE *sqfp);
99
100
101 /*****************************************************************
102 *# 1. An <ESL_SQFILE> object, in text mode.
103 *****************************************************************/
104
105 /* Function: esl_sqascii_Open()
106 * Synopsis: Open a sequence file for reading.
107 *
108 * Purpose: Open a sequence file <filename> for reading.
109 * The opened <ESL_SQFILE> is returned through <ret_sqfp>.
110 *
111 * The format of the file is asserted to be <format> (for
112 * example, <eslSQFILE_FASTA>). If <format> is
113 * <eslSQFILE_UNKNOWN> then the routine attempts to
114 * autodetect the file format.
115 *
116 * There are two special cases for <filename>. If
117 * <filename> is "-", the sequence data are read from a
118 * <STDIN> pipe. If <filename> ends in ".gz", the file is
119 * assumed to be compressed with <gzip>, and it is opened
120 * by a pipe from <gzip -dc>. Reading gzip files only works
121 * on POSIX-compliant systems that have pipes
122 * (specifically, the POSIX.2 popen() call).
123 *
124 * Returns: <eslOK> on success, and <*ret_sqfp> points to a new
125 * open <ESL_SQFILE>. Caller deallocates this object with
126 * <esl_sqfile_Close()>.
127 *
128 * Returns <eslENOTFOUND> if <filename> can't be found or
129 * opened. Returns <eslEFORMAT> if the file is empty, or
130 * if autodetection is attempted and the format can't be
131 * determined. On any error condition, <*ret_sqfp> is
132 * returned NULL.
133 *
134 * Throws: <eslEMEM> on allocation failure.
135 */
136 int
137 esl_sqascii_Open(char *filename, int format, ESL_SQFILE *sqfp)
138 {
139 int status;/* return status from an ESL call */
140 int n;
141 int nc;
142
143 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
144
145 /* before we go any further, make sure we can handle the format */
146 if (format == eslSQFILE_NCBI) return eslENOTFOUND;
147
148 /* Default initializations */
149 ascii->fp = NULL;
150 ascii->do_gzip = FALSE;
151 ascii->do_stdin = FALSE;
152 ascii->do_buffer = FALSE;
153
154 ascii->mem = NULL;
155 ascii->allocm = 0;
156 ascii->mn = 0;
157 ascii->mpos = 0;
158 ascii->moff = -1;
159 ascii->is_recording = FALSE;
160
161 ascii->buf = NULL;
162 ascii->boff = 0;
163 ascii->balloc = 0;
164 ascii->nc = 0;
165 ascii->bpos = 0;
166 ascii->L = 0;
167 ascii->linenumber = 1;
168
169 ascii->bookmark_offset = 0;
170 ascii->bookmark_linenum = 0;
171
172 ascii->is_linebased = FALSE;
173 ascii->eof_is_ok = FALSE;
174 ascii->parse_header = NULL;
175 ascii->skip_header = NULL;
176 ascii->parse_end = NULL;
177
178 ascii->afp = NULL;
179 ascii->msa = NULL;
180 ascii->idx = -1;
181
182 ascii->ssifile = NULL;
183 ascii->rpl = -1; /* -1 = not set yet */
184 ascii->bpl = -1; /* (ditto) */
185 ascii->prvrpl = -1; /* (ditto) */
186 ascii->prvbpl = -1; /* (ditto) */
187 ascii->currpl = -1;
188 ascii->curbpl = -1;
189 ascii->ssi = NULL;
190
191 /* MSA formats are handled entirely by msafile module -
192 * let it handle stdin, .gz, etc
193 */
194 if (! esl_sqio_IsAlignment(format))
195 {
196 if (strcmp(filename, "-") == 0) /* stdin special case */
197 {
198 ascii->fp = stdin;
199 ascii->do_stdin = TRUE;
200 }
201 else
202 { /* Check the current working directory first. */
203 if ((ascii->fp = fopen(filename, "r")) == NULL) {
204 status = eslENOTFOUND;
205 goto ERROR;
206 }
207 }
208
209 /* Deal with the .gz special case: to popen(), "success" only means
210 * it found and executed gzip -dc. If gzip -dc doesn't find our
211 * file, popen() still blithely returns success, so we have to be
212 * sure the file exists. That's why we fopen()'ed it above, only to
213 * close it and popen() it here.
214 */
215 #ifdef HAVE_POPEN
216 n = strlen(filename);
217 if (n > 3 && strcmp(filename+n-3, ".gz") == 0)
218 {
219 char *cmd;
220 fclose(ascii->fp);
221 nc = strlen("gzip -dc ") + n + 1;
222 ESL_ALLOC(cmd, nc);
223 snprintf(cmd, nc, "gzip -dc %s", filename);
224 ascii->fp = popen(cmd, "r");
225 if (ascii->fp == NULL) { status = eslENOTFOUND; goto ERROR; }
226 ascii->do_gzip = TRUE;
227 free(cmd);
228 }
229 #endif /*HAVE_POPEN*/
230
231 /* If we don't know the format yet, try to autodetect it now. */
232 if (format == eslSQFILE_UNKNOWN)
233 {
234 status = sqascii_GuessFileFormat(sqfp, &format);
235 if (status == eslOK) sqfp->format = format;
236 else if (status != eslEFORMAT) goto ERROR; /* <format> might still be eslSQFILE_UNKNOWN, for MSA files */
237 }
238
239 /* If the format is still unknown, it may be an MSA file. The
240 * msafile module is capable of autodetecting format even in a .gz
241 * or stdin pipe, but the stuff above has already read from these
242 * nonrewindable sources, trying to guess an unaligned format. We
243 * could open a second .gz pipe, but that's ugly; and in any case,
244 * we can't rewind stdin. Eventually, this will get resolved, by
245 * having sqio open an ESL_BUFFER, then doing an
246 * esl_msafile_OpenBuffer() if we need to hand control to the
247 * msafile module. For now, sqio is already documented to be
248 * unable to autodetect MSA file formats in stdin or .gz pipes,
249 * so leave it that way.
250 */
251 if (format == eslSQFILE_UNKNOWN && (ascii->do_gzip || ascii->do_stdin))
252 { status = eslEFORMAT; goto ERROR; }
253 }
254
255 /* If format is definitely an MSA, open it through the msafile interface.
256 * Or, if format is still unknown, try to open the file as an MSA file,
257 * using msafile autodetection.
258 */
259 if (format == eslSQFILE_UNKNOWN || esl_sqio_IsAlignment(format))
260 {
261 status = esl_msafile_Open(NULL, filename, NULL, format, NULL, &(ascii->afp));
262 if (status != eslOK) { status = eslEFORMAT; goto ERROR; } /* This was our last attempt. Failure to open == failure to detect format */
263 sqfp->format = format = ascii->afp->format;
264 }
265 if (format == eslSQFILE_UNKNOWN) { status = eslEFORMAT; goto ERROR; }
266
267
268 /* Configure the <sqfp>'s parser and inmaps for this format. */
269 if (!esl_sqio_IsAlignment(format))
270 {
271 switch (format) {
272 case eslSQFILE_EMBL: config_embl(sqfp); inmap_embl(sqfp, NULL); break;
273 case eslSQFILE_UNIPROT: config_embl(sqfp); inmap_embl(sqfp, NULL); break;
274 case eslSQFILE_GENBANK: config_genbank(sqfp); inmap_genbank(sqfp, NULL); break;
275 case eslSQFILE_DDBJ: config_genbank(sqfp); inmap_genbank(sqfp, NULL); break;
276 case eslSQFILE_FASTA: config_fasta(sqfp); inmap_fasta(sqfp, NULL); break;
277 case eslSQFILE_DAEMON: config_daemon(sqfp); inmap_daemon(sqfp, NULL); break;
278 case eslSQFILE_HMMPGMD: config_fasta(sqfp); inmap_fasta(sqfp, NULL); break;
279 default:status = eslEFORMAT; goto ERROR;
280 }
281
282 /* Preload the first line or chunk of file. */
283 status = loadbuf(sqfp);
284 if (status == eslEOF) { status = eslEFORMAT; goto ERROR; }
285 else if (status != eslOK) { goto ERROR; }
286
287 /* hmmpgmd is a special case: we need to skip first line before parsing it.
288 * generalize that a little: this could be a section for parsing a file header,
289 * and leaving the buf positioned at the first char of the first record
290 * (just as expected if there's no file header)
291 */
292 switch (format) {
293 case eslSQFILE_HMMPGMD: status = fileheader_hmmpgmd(sqfp); break;
294 default: status = eslOK; break;
295 }
296 if (status != eslOK) goto ERROR;
297 }
298 else
299 {
300 ascii->is_linebased = TRUE;
301 ascii->eof_is_ok = FALSE; /* no-op for msa's */
302 ascii->parse_header = NULL; /* no-op for msa's */
303 ascii->skip_header = NULL; /* no-op for msa's */
304 ascii->parse_end = NULL; /* no-op for msa's */
305 }
306
307 /* initialize the function pointers for the ascii routines */
308 sqfp->position = &sqascii_Position;
309 sqfp->close = &sqascii_Close;
310
311 sqfp->set_digital = &sqascii_SetDigital;
312 sqfp->guess_alphabet = &sqascii_GuessAlphabet;
313
314 sqfp->is_rewindable = &sqascii_IsRewindable;
315
316 sqfp->read = &sqascii_Read;
317 sqfp->read_info = &sqascii_ReadInfo;
318 sqfp->read_seq = &sqascii_ReadSequence;
319 sqfp->read_window = &sqascii_ReadWindow;
320 sqfp->echo = &sqascii_Echo;
321
322 sqfp->read_block = &sqascii_ReadBlock;
323
324 sqfp->open_ssi = &sqascii_OpenSSI;
325 sqfp->pos_by_key = &sqascii_PositionByKey;
326 sqfp->pos_by_number = &sqascii_PositionByNumber;
327
328 sqfp->fetch = &sqascii_Fetch;
329 sqfp->fetch_info = &sqascii_FetchInfo;
330 sqfp->fetch_subseq = &sqascii_FetchSubseq;
331 sqfp->get_error = &sqascii_GetError;
332
333 return eslOK;
334
335 ERROR:
336 sqascii_Close(sqfp);
337 return status;
338 }
339
340
341 /* Function: sqascii_GuessFileFormat()
342 * Synopsis: Guess the format of an open <ESL_SQFILE>.
343 *
344 * Purpose: Try to guess the sequence file format of <sqfp>, and
345 * return the format code in <*ret_fmt>.
346 *
347 * First we attempt to guess based on the <filename>'s
348 * suffix. <*.fa> is assumed to be in FASTA format; <*.gb>
349 * is assumed to be in GenBank format.
350 *
351 * If that fails, we attempt to guess based on peeking at
352 * the first nonblank line of <filename>. If the line
353 * starts with $>$, we assume FASTA format; if the line
354 * starts with <ID>, we assume EMBL format; if the line
355 * starts with <LOCUS> or it contains the string <Genetic
356 * Sequence Data Bank> we assume GenBank format.
357 *
358 * If that fails too, return an <eslEFORMAT> error, and
359 * <*ret_fmt> is set to <eslSQFILE_UNKNOWN>.
360 *
361 * Returns: <eslOK> on success, and <*ret_fmt> contains
362 * a valid sequence file format code, such as
363 * <eslSQFILE_FASTA>.
364 *
365 * Returns <eslEFORMAT> if we opened <filename> but it
366 * contains no nonblank lines, or if we peeked at the first
367 * nonblank line and still couldn't guess the format;
368 * <*ret_fmt> is then <eslSQFILE_UNKNOWN>.
369 *
370 * Throws: <eslEMEM> on allocation failure.
371 */
372 static int
373 sqascii_GuessFileFormat(ESL_SQFILE *sqfp, int *ret_fmt)
374 {
375 int n = strlen(sqfp->filename);
376 const char *sfx = NULL;
377 int is_gzip = FALSE;
378 int nsfx;
379 int status;
380
381 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
382
383 /* On any premature exit, *ret_fmt is eslSQFILE_UNKNOWN */
384 *ret_fmt = eslSQFILE_UNKNOWN;
385
386 /* Is <filename> gzip'ed? Look at suffix. */
387 if (n > 3 && strcmp(sqfp->filename+n-3, ".gz") == 0) is_gzip = TRUE;
388
389 /* Locate the suffix that might indicate format (ignore .gz) */
390 for (nsfx = 1, sfx = sqfp->filename + n - 1 - (is_gzip ? 3 : 0);
391 sfx != sqfp->filename && *sfx != '.';
392 sfx--)
393 nsfx++;
394
395 /* now sfx points either to filename (we didn't find a suffix) or to the . of the suffix,
396 * and nsfx is the suffix length inclusive of the .
397 */
398
399 /* Attempt to guess file format based on file name suffix. */
400 if (nsfx && strcmp(sfx, ".fa") == 0) { *ret_fmt = eslSQFILE_FASTA; return eslOK; }
401 else if (nsfx && strcmp(sfx, ".gb") == 0) { *ret_fmt = eslSQFILE_GENBANK; return eslOK; }
402
403 /* If that didn't work, we'll have a peek at the stream;
404 * turn recording on, and set for line based input.
405 */
406 if (ascii->is_recording == -1) ESL_EXCEPTION(eslEINVAL, "sq file already too advanced");
407 ascii->is_recording = TRUE;
408 ascii->is_linebased = TRUE;
409 loadbuf(sqfp);/* now ascii->buf is a line of the file */
410
411 /* get first nonblank line */
412 while (esl_str_IsBlank(ascii->buf)) {
413 status = loadbuf(sqfp);
414 if (status == eslEOF) ESL_XFAIL(eslEFORMAT, ascii->errbuf, "No data found in file");
415 else if (status != eslOK) goto ERROR;
416 }
417
418 /* formats that can be determined from the first line: */
419 if (*(ascii->buf) == '>') *ret_fmt = eslSQFILE_FASTA;
420 else if (strncmp(ascii->buf, "ID ", 5) == 0) *ret_fmt = eslSQFILE_EMBL;
421 else if (strncmp(ascii->buf, "LOCUS ", 8) == 0) *ret_fmt = eslSQFILE_GENBANK;
422 else if (strstr(ascii->buf, "Genetic Sequence Data Bank") != NULL) *ret_fmt = eslSQFILE_GENBANK;
423
424 /* reset the sqfp */
425 ascii->mpos = 0;
426 ascii->is_recording = FALSE;
427 ascii->is_linebased = FALSE;
428 free(ascii->buf);
429 ascii->buf = NULL;
430 ascii->balloc = 0;
431 return (*ret_fmt == eslSQFILE_UNKNOWN) ? eslEFORMAT : eslOK;
432
433 ERROR:
434 ascii->mpos = 0;
435 ascii->is_recording = FALSE;
436 ascii->is_linebased = FALSE;
437 if (ascii->buf != NULL) { free(ascii->buf); ascii->balloc = 0; }
438 return status;
439 }
440
441 /* Function: sqascii_Position()
442 * Synopsis: Reposition an open sequence file to an offset.
443 *
444 * Purpose: Reposition an open <sqfp> to offset <offset>.
445 * <offset> would usually be the first byte of a
446 * desired sequence record.
447 *
448 * Only normal sequence files can be positioned to a
449 * nonzero offset. If <sqfp> corresponds to a standard
450 * input stream or gzip -dc stream, it may not be
451 * repositioned. If <sqfp> corresponds to a multiple
452 * sequence alignment file, the only legal <offset>
453 * is 0, to rewind the file to the beginning and
454 * be able to read the entire thing again.
455 *
456 * After <esl_sqfile_Position()> is called on a nonzero
457 * <offset>, <sqfp->linenumber> and other bookkeeping
458 * information is unknown. If caller knows it, it should
459 * set it explicitly.
460 *
461 * See the SSI module for manipulating offsets and indices.
462 *
463 * Returns: <eslOK> on success;
464 * <eslEOF> if no data can be read from this position.
465 *
466 * Throws: <eslESYS> if the fseeko() or fread() call fails.
467 * <eslEMEM> on (re-)allocation failure.
468 * <eslEINVAL> if the <sqfp> is not positionable.
469 * <eslENOTFOUND> if in trying to rewind an alignment file
470 * by closing and reopening it, the open fails.
471 * On errors, the state of <sqfp> is indeterminate, and
472 * it should not be used again.
473 */
474 static int
475 sqascii_Position(ESL_SQFILE *sqfp, off_t offset)
476 {
477 int status;
478
479 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
480
481 if (ascii->do_stdin) ESL_EXCEPTION(eslEINVAL, "can't Position() in standard input");
482 if (ascii->do_gzip) ESL_EXCEPTION(eslEINVAL, "can't Position() in a gzipped file");
483 if (offset < 0) ESL_EXCEPTION(eslEINVAL, "bad offset");
484 if (offset > 0 && ascii->afp != NULL) ESL_EXCEPTION(eslEINVAL, "can't use esl_sqfile_Position() w/ nonzero offset on MSA file");
485
486 if (esl_sqio_IsAlignment(sqfp->format))
487 {/* msa file: close and reopen. maybe sometime we'll have esl_msafile_Rewind() */
488 /* we have already verified that offset==0 for MSA file */
489 esl_msafile_Close(ascii->afp);
490 if (ascii->msa != NULL) esl_msa_Destroy(ascii->msa);
491 ascii->afp = NULL;
492 ascii->msa = NULL;
493 ascii->idx = 0;
494
495 /* we know we successfully opened it the first time, so a
496 failure to reopen is an exception, not a user-reportable
497 normal error. ENOTFOUND is the only normal error;
498 EFORMAT error can't occur because we know the format and
499 don't use autodetection.
500 */
501 status = esl_msafile_Open(NULL, sqfp->filename, NULL, sqfp->format, NULL, &(ascii->afp));
502 if (status == eslENOTFOUND) ESL_EXCEPTION(eslENOTFOUND, "failed to reopen alignment file");
503 else if (status != eslOK) return status;
504 }
505 else/* normal case: unaligned sequence file */
506 {
507 if (fseeko(ascii->fp, offset, SEEK_SET) != 0) ESL_EXCEPTION(eslESYS, "fseeko() failed");
508
509 ascii->currpl = -1;
510 ascii->curbpl = -1;
511 ascii->prvrpl = -1;
512 ascii->prvbpl = -1;
513 ascii->linenumber = (offset == 0) ? 1 : -1; /* -1 is "unknown" */
514 ascii->L = -1;
515 ascii->mpos = ascii->mn;/* this forces loadbuf to load new data */
516 if ((status = loadbuf(sqfp)) != eslOK) return status;
517 }
518 return eslOK;
519 }
520
521
522
523 /* Function: sqascii_Close()
524 * Synopsis: Close a sequence file.
525 *
526 * Purpose: Closes an open <sqfp>.
527 *
528 * Returns: (void).
529 */
530 static void
531 sqascii_Close(ESL_SQFILE *sqfp)
532 {
533 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
534
535 #ifdef HAVE_POPEN
536 if (ascii->do_gzip) pclose(ascii->fp);
537 else
538 #endif
539 if (! ascii->do_stdin && ascii->fp != NULL) fclose(ascii->fp);
540
541 if (ascii->ssifile != NULL) free(ascii->ssifile);
542 if (ascii->mem != NULL) free(ascii->mem);
543 if (ascii->balloc > 0) free(ascii->buf);
544 if (ascii->ssi != NULL) esl_ssi_Close(ascii->ssi);
545
546 if (ascii->afp != NULL) esl_msafile_Close(ascii->afp);
547 if (ascii->msa != NULL) esl_msa_Destroy(ascii->msa);
548
549 ascii->do_gzip = FALSE;
550 ascii->do_stdin = FALSE;
551
552 ascii->fp = NULL;
553
554 ascii->ssifile = NULL;
555 ascii->mem = NULL;
556
557 ascii->balloc = 0;
558 ascii->buf = NULL;
559
560 ascii->ssi = NULL;
561
562 ascii->afp = NULL;
563 ascii->msa = NULL;
564
565 return;
566 }
567 /*------------------- ESL_SQFILE open/close -----------------------*/
568
569
570 /*****************************************************************
571 *# 2. An <ESL_SQFILE> object, in digital mode [with <alphabet>]
572 *****************************************************************/
573
574 /* Function: sqascii_SetDigital()
575 * Synopsis: Set an open <ESL_SQFILE> to read in digital mode.
576 *
577 * Purpose: Given an <ESL_SQFILE> that's already been opened,
578 * configure it to expect subsequent input to conform
579 * to the digital alphabet <abc>.
580 *
581 * Calling <esl_sqfile_Open(); esl_sqfile_SetDigital()> is
582 * equivalent to <esl_sqfile_OpenDigital()>. The two-step
583 * version is useful when you need a
584 * <esl_sqfile_GuessAlphabet()> call in between, guessing
585 * the file's alphabet in text mode before you set it to
586 * digital mode.
587 *
588 * Returns: <eslOK> on success.
589 */
590 static int
591 sqascii_SetDigital(ESL_SQFILE *sqfp, const ESL_ALPHABET *abc)
592 {
593 int status = eslOK;
594
595 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
596
597 if (!esl_sqio_IsAlignment(sqfp->format))
598 {
599 switch (sqfp->format) {
600 case eslSQFILE_EMBL: inmap_embl(sqfp, abc->inmap); break;
601 case eslSQFILE_UNIPROT: inmap_embl(sqfp, abc->inmap); break;
602 case eslSQFILE_GENBANK: inmap_genbank(sqfp, abc->inmap); break;
603 case eslSQFILE_DDBJ: inmap_genbank(sqfp, abc->inmap); break;
604 case eslSQFILE_FASTA: inmap_fasta(sqfp, abc->inmap); break;
605 case eslSQFILE_DAEMON: inmap_daemon(sqfp, abc->inmap); break;
606
607 default: status = eslEFORMAT; break;
608 }
609 }
610 else
611 esl_msafile_SetDigital(ascii->afp, abc);
612
613 return status;
614 }
615
616 /* Function: sqascii_GuessAlphabet()
617 * Synopsis: Guess the alphabet of an open <ESL_SQFILE>.
618 *
619 * Purpose: After opening <sqfp>, attempt to guess what alphabet
620 * its sequences are in, by inspecting the first sequence
621 * in the file, and return this alphabet type in <*ret_type>.
622 *
623 * Returns: <eslOK> on success, and <*ret_type> is set to <eslDNA>,
624 * <eslRNA>, or <eslAMINO>.
625 *
626 * Returns <eslENOALPHABET> and sets <*ret_type> to
627 * <eslUNKNOWN> if the first sequence (or alignment)
628 * in the file contains no more than ten residues total,
629 * or if its alphabet cannot be guessed (i.e. it contains
630 * IUPAC degeneracy codes, but no amino acid specific
631 * residues).
632 *
633 * Returns <eslEFORMAT> if a parse error is encountered in
634 * trying to read the sequence file. <ascii->errbuf> is set
635 * to a useful error message if this occurs,
636 * <sqfp->linenumber> is the line on which the error
637 * occurred, and <*ret_type> is set to <eslUNKNOWN>.
638 *
639 * Returns <eslENODATA> and sets <*ret_type> to <eslUNKNOWN>
640 * if the file appears to be empty.
641 *
642 * Throws: <eslEMEM> on allocation error;
643 * <eslEINCONCEIVABLE> on unimaginable internal errors.
644 */
645 static int
646 sqascii_GuessAlphabet(ESL_SQFILE *sqfp, int *ret_type)
647 {
648 ESL_SQ *sq = NULL;
649 int status;
650
651 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
652
653 /* Special case: for MSA files, hand this off to msafile_GuessAlphabet. */
654 if (esl_sqio_IsAlignment(sqfp->format)) return esl_msafile_GuessAlphabet(ascii->afp, ret_type);
655
656 /* set the sqfp to record; we'll rewind afterwards and use the recording */
657 ascii->is_recording = TRUE;
658
659 if ((sq = esl_sq_Create()) == NULL) { status = eslEMEM; goto ERROR; }
660
661 status = sqascii_ReadWindow(sqfp, 0, 4000, sq);
662 if (status == eslEOF) { status = eslENODATA; goto ERROR; }
663 else if ((status != eslOK) && (status != eslEOD)) goto ERROR;
664
665 if ((status = esl_sq_GuessAlphabet(sq, ret_type)) != eslOK) goto ERROR;
666
667 /* reset the sqfp, so it uses the recording next */
668 ascii->mpos = 0;
669 ascii->linenumber = 1;
670 ascii->is_recording = FALSE;
671 if ((status = loadbuf(sqfp)) != eslOK) ESL_EXCEPTION(status, "buffer load failed, but shouldn't have");
672 esl_sq_Destroy(sq);
673 return eslOK;
674
675 ERROR:
676 esl_sq_Destroy(sq);
677 *ret_type = eslUNKNOWN;
678 return status;
679 }
680 /*-------------- end, digital mode ESL_SQFILE -------------------*/
681
682
683
684
685 /*****************************************************************
686 *# 3. Miscellaneous routines
687 *****************************************************************/
688
689 /* Function: sqascii_IsRewindable()
690 * Synopsis: Return <TRUE> if <sqfp> can be rewound.
691 *
692 * Purpose: Returns <TRUE> if <sqfp> can be rewound (positioned
693 * to an offset of zero), in order to read it a second
694 * time.
695 */
696 static int
697 sqascii_IsRewindable(const ESL_SQFILE *sqfp)
698 {
699 if (sqfp->data.ascii.do_gzip == TRUE) return FALSE;
700 if (sqfp->data.ascii.do_stdin == TRUE) return FALSE;
701 return TRUE;
702 }
703
704 /* Function: sqascii_GetError()
705 * Synopsis: Return <TRUE> if <sqfp> can be rewound.
706 *
707 * Purpose: Returns <TRUE> if <sqfp> can be rewound (positioned
708 * to an offset of zero), in order to read it a second
709 * time.
710 */
711 static const char *
712 sqascii_GetError(const ESL_SQFILE *sqfp)
713 {
714 return sqfp->data.ascii.errbuf;
715 }
716
717
718 /*****************************************************************
719 *# 4. Sequence reading (sequential)
720 *****************************************************************/
721
722 /* Function: sqascii_Read()
723 * Synopsis: Read the next sequence from a file.
724 *
725 * Purpose: Reads the next sequence from open sequence file <sqfp> into
726 * <sq>. Caller provides an allocated and initialized <s>, which
727 * will be internally reallocated if its space is insufficient.
728 *
729 * Returns: <eslOK> on success; the new sequence is stored in <s>.
730 *
731 * Returns <eslEOF> when there is no sequence left in the
732 * file (including first attempt to read an empty file).
733 *
734 * Returns <eslEFORMAT> if there's a problem with the format,
735 * such as an illegal character; the line number that the parse
736 * error occurs on is in <sqfp->linenumber>, and an informative
737 * error message is placed in <ascii->errbuf>.
738 *
739 * Throws: <eslEMEM> on allocation failure;
740 * <eslEINCONCEIVABLE> on internal error.
741 */
742 static int
743 sqascii_Read(ESL_SQFILE *sqfp, ESL_SQ *sq)
744 {
745 int status;
746 int64_t epos;
747 int64_t n;
748
749 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
750
751 if (esl_sqio_IsAlignment(sqfp->format))
752 {
753 ESL_SQ *tmpsq = NULL;
754 if (ascii->msa == NULL || ascii->idx >= ascii->msa->nseq)
755 { /* we need to load a new alignment? */
756 esl_msa_Destroy(ascii->msa);
757 status = esl_msafile_Read(ascii->afp, &(ascii->msa));
758 if (status == eslEFORMAT)
759 { /* oops, a parse error; upload the error info from afp to sqfp */
760 ascii->linenumber = ascii->afp->linenumber;
761 strcpy(ascii->errbuf, ascii->afp->errmsg); /* errbufs same size! */
762 return eslEFORMAT;
763 }
764 if (status != eslOK) return status;
765 ascii->idx = 0;
766 }
767
768 /* grab next seq from alignment */
769 /* this is inefficient; it goes via a temporarily allocated copy of the sequence */
770 if ((status = esl_sq_FetchFromMSA(ascii->msa, ascii->idx, &tmpsq)) != eslOK) return status;
771 esl_sq_GrowTo(sq, tmpsq->n);
772 esl_sq_Copy(tmpsq, sq);
773 esl_sq_Destroy(tmpsq);
774 ascii->idx++;
775
776 sq->start = 1;
777 sq->end = sq->n;
778 sq->C = 0;
779 sq->W = sq->n;
780 sq->L = sq->n;
781 return eslOK;
782 }
783
784 /* Main case: read next seq from sqfp's stream */
785 if (ascii->nc == 0) return eslEOF;
786 if ((status = ascii->parse_header(sqfp, sq)) != eslOK) return status; /* EMEM, EOF, EFORMAT */
787
788 do {
789 if ((status = seebuf(sqfp, -1, &n, &epos)) == eslEFORMAT) return status;
790 if (esl_sq_GrowTo(sq, sq->n + n) != eslOK) return eslEMEM;
791 addbuf(sqfp, sq, n);
792 ascii->L += n;
793 sq->eoff = ascii->boff + epos - 1;
794 if (status == eslEOD) break;
795 } while ((status = loadbuf(sqfp)) == eslOK);
796
797 if (status == eslEOF)
798 {
799 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected EOF; file truncated?");
800 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
801 }
802 else if (status == eslEOD)
803 {
804 ascii->bpos = epos;
805 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
806 }
807 else if (status != eslOK) return status;
808
809 if (sq->dsq != NULL) sq->dsq[sq->n+1] = eslDSQ_SENTINEL;
810 else sq->seq[sq->n] = '\0';
811 sq->start = 1;
812 sq->end = sq->n;
813 sq->C = 0;
814 sq->W = sq->n;
815 sq->L = sq->n;
816 return eslOK;
817 }
818
819
820 /* Function: sqascii_ReadInfo()
821 * Synopsis: Read sequence info, but not the sequence itself.
822 *
823 * Purpose: Read the next sequence from open sequence file <sqfp>,
824 * but don't store the sequence (or secondary structure).
825 * Upon successful return, <s> holds all the available
826 * information about the sequence -- its name, accession,
827 * description, and overall length <sq->L>.
828 *
829 * This is useful for indexing sequence files, where
830 * individual sequences might be ginormous, and we'd rather
831 * avoid reading complete seqs into memory.
832 *
833 * Returns: <eslOK> on success.
834 *
835 * Throws: <eslEMEM> on allocation error.
836 */
837 static int
838 sqascii_ReadInfo(ESL_SQFILE *sqfp, ESL_SQ *sq)
839 {
840 int status;
841 int64_t epos;
842 int64_t n;
843
844 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
845
846 if (esl_sqio_IsAlignment(sqfp->format))
847 {
848 ESL_SQ *tmpsq = NULL;
849 if (ascii->msa == NULL || ascii->idx >= ascii->msa->nseq)
850 { /* we need to load a new alignment? */
851 esl_msa_Destroy(ascii->msa);
852 status = esl_msafile_Read(ascii->afp, &(ascii->msa));
853 if (status == eslEFORMAT)
854 { /* oops, a parse error; upload the error info from afp to sqfp */
855 ascii->linenumber = ascii->afp->linenumber;
856 strcpy(ascii->errbuf, ascii->afp->errmsg); /* errbufs same size! */
857 return eslEFORMAT;
858 }
859 if (status != eslOK) return status;
860 ascii->idx = 0;
861 }
862
863 /* grab next seq from alignment */
864 /* this is inefficient; it goes via a temporarily allocated copy of the sequence */
865 if ((status = esl_sq_FetchFromMSA(ascii->msa, ascii->idx, &tmpsq)) != eslOK) return status;
866 if (tmpsq->dsq != NULL) tmpsq->dsq[1] = eslDSQ_SENTINEL;
867 else tmpsq->seq[0] = '\0';
868 esl_sq_Copy(tmpsq, sq);
869 esl_sq_Destroy(tmpsq);
870 ascii->idx++;
871
872 if (sq->dsq != NULL) sq->dsq[1] = eslDSQ_SENTINEL;
873 else sq->seq[0] = '\0';
874 if (sq->ss != NULL) { free(sq->ss); sq->ss = NULL; }
875
876 sq->n = 0;
877 sq->start = 0;
878 sq->end = 0;
879 sq->C = 0;
880 sq->W = 0;
881 return eslOK;
882 }
883
884 if (ascii->nc == 0) return eslEOF;
885 if ((status = ascii->parse_header(sqfp, sq)) != eslOK) return status; /* EOF, EFORMAT */
886
887 ascii->L = 0;
888 do {
889 status = seebuf(sqfp, -1, &n, &epos);
890 ascii->L += n;
891 sq->eoff = ascii->boff + epos - 1;
892 if (status == eslEFORMAT) return status;
893 if (status == eslEOD) break;
894 } while ((status = loadbuf(sqfp)) == eslOK);
895
896 if (status == eslEOF)
897 {
898 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected EOF; file truncated?");
899 }
900 else if (status == eslEOD)
901 {
902 ascii->bpos = epos;
903 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
904 }
905 else if (status != eslOK) return status;
906 sq->L = ascii->L;
907
908 /* Set coord system for an info-only ESL_SQ */
909 if (sq->dsq != NULL) sq->dsq[1] = eslDSQ_SENTINEL;
910 else sq->seq[0] = '\0';
911 if (sq->ss != NULL) { free(sq->ss); sq->ss = NULL; }
912 sq->n = 0;
913 sq->start = 0;
914 sq->end = 0;
915 sq->C = 0;
916 sq->W = 0;
917 return eslOK;
918 }
919
920
921 /* Function: sqascii_ReadSequence()
922 * Synopsis: Read the next sequence from a file.
923 *
924 * Purpose: Reads the next sequence from open sequence file <sqfp> into
925 * <sq>. Caller provides an allocated and initialized <s>, which
926 * will be internally reallocated if its space is insufficient.
927 *
928 * Returns: <eslOK> on success; the new sequence is stored in <s>.
929 *
930 * Returns <eslEOF> when there is no sequence left in the
931 * file (including first attempt to read an empty file).
932 *
933 * Returns <eslEFORMAT> if there's a problem with the format,
934 * such as an illegal character; the line number that the parse
935 * error occurs on is in <sqfp->linenumber>, and an informative
936 * error message is placed in <ascii->errbuf>.
937 *
938 * Throws: <eslEMEM> on allocation failure;
939 * <eslEINCONCEIVABLE> on internal error.
940 */
941 static int
942 sqascii_ReadSequence(ESL_SQFILE *sqfp, ESL_SQ *sq)
943 {
944 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
945 int64_t epos;
946 int64_t n;
947 int status;
948
949 if (esl_sqio_IsAlignment(sqfp->format))
950 {
951 ESL_SQ *tmpsq = NULL;
952 if (ascii->msa == NULL || ascii->idx >= ascii->msa->nseq)
953 { /* we need to load a new alignment? */
954 esl_msa_Destroy(ascii->msa);
955 status = esl_msafile_Read(ascii->afp, &(ascii->msa));
956 if (status == eslEFORMAT)
957 { /* oops, a parse error; upload the error info from afp to sqfp */
958 ascii->linenumber = ascii->afp->linenumber;
959 strcpy(ascii->errbuf, ascii->afp->errmsg); /* errbufs same size! */
960 return eslEFORMAT;
961 }
962 if (status != eslOK) return status;
963 ascii->idx = 0;
964 }
965
966 /* grab next seq from alignment */
967 /* this is inefficient; it goes via a temporarily allocated copy of the sequence */
968 status = esl_sq_FetchFromMSA(ascii->msa, ascii->idx, &tmpsq); // eslEMEM | eslEOD
969 if (status != eslOK) return status;
970
971 esl_sq_GrowTo(sq, tmpsq->n);
972 esl_sq_Copy(tmpsq, sq);
973 esl_sq_Destroy(tmpsq);
974 ascii->idx++;
975
976 sq->start = 1;
977 sq->end = sq->n;
978 sq->C = 0;
979 sq->W = sq->n;
980 sq->L = sq->n;
981 return eslOK;
982 }
983
984 /* Main case: read next seq from sqfp's stream */
985 if (ascii->nc == 0) return eslEOF;
986 if ((status = ascii->skip_header(sqfp, sq)) != eslOK) return status; /* EOF, EFORMAT */
987
988 do {
989 if ((status = seebuf(sqfp, -1, &n, &epos)) == eslEFORMAT) return status;
990 if (esl_sq_GrowTo(sq, sq->n + n) != eslOK) return eslEMEM;
991 addbuf(sqfp, sq, n);
992 ascii->L += n;
993 sq->eoff = ascii->boff + epos - 1;
994 if (status == eslEOD) break;
995 } while ((status = loadbuf(sqfp)) == eslOK);
996
997 if (status == eslEOF)
998 {
999 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected EOF; file truncated?");
1000 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
1001 }
1002 else if (status == eslEOD)
1003 {
1004 ascii->bpos = epos;
1005 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
1006 }
1007 else if (status != eslOK) return status;
1008
1009 if (sq->dsq != NULL) sq->dsq[sq->n+1] = eslDSQ_SENTINEL;
1010 else sq->seq[sq->n] = '\0';
1011 sq->start = 1;
1012 sq->end = sq->n;
1013 sq->C = 0;
1014 sq->W = sq->n;
1015 sq->L = sq->n;
1016 return eslOK;
1017 }
1018
1019
1020 /* Function: sqascii_ReadWindow()
1021 * Synopsis: Read next window of sequence.
1022 *
1023 * Purpose: Read a next window of <W> residues from open file <sqfp>,
1024 * keeping <C> residues from the previous window as
1025 * context, and keeping previous annotation in the <sq>
1026 * as before.
1027 *
1028 * If this is the first window of a new sequence record,
1029 * <C> is ignored (there's no previous context yet), and
1030 * the annotation fields of the <sq> (name, accession, and
1031 * description) are initialized by reading the sequence
1032 * record's header. This is the only time the annotation
1033 * fields are initialized.
1034 *
1035 * On return, <sq->dsq[]> contains the window and its
1036 * context; residues <1..sq->C> are the previous context,
1037 * and residues <sq->C+1..sq->n> are the new window. The
1038 * start and end coordinates of the whole <dsq[1..n]>
1039 * (including context) in the original source sequence are
1040 * <sq->start..sq->end>. (Or, for text mode sequences,
1041 * <sq->seq[0..sq->C-1,sq->C..sq->n-1]>, while <start> and
1042 * <end> coords are still <1..L>.)
1043 *
1044 * When a sequence record is completed and no more data
1045 * remain, <eslEOD> is returned, with an ``info'' <sq>
1046 * structure (containing the annotation and the total
1047 * sequence length <L>, but no sequence). (The total
1048 * sequence length <L> is unknown in <sq> until this
1049 * <eslEOD> return.)
1050 *
1051 * The caller may then do one of two things before calling
1052 * <esl_sq_ReadWindow()> again; it can reset the sequence
1053 * with <esl_sq_Reuse()> to continue reading the next
1054 * sequence in the file, or it can set a negative <W> as a
1055 * signal to read windows from the reverse complement
1056 * (Crick) strand. Reverse complement reading only works
1057 * for nucleic acid sequence.
1058 *
1059 * If you read the reverse complement strand, you must read
1060 * the whole thing, calling <esl_sqio_ReadWindow()> with
1061 * negative <W> windows until <eslEOD> is returned again
1062 * with an empty (info-only) <sq> structure. When that
1063 * <EOD> is reached, the <sqfp> is repositioned at the
1064 * start of the next sequence record; the caller should now
1065 * <Reuse()> the <sq>, and the next <esl_sqio_ReadWindow()>
1066 * call must have a positive <W>, corresponding to starting
1067 * to read the Watson strand of the next sequence.
1068 *
1069 * Note that the <ReadWindow()> interface is designed for
1070 * an idiom of sequential reading of complete sequences in
1071 * overlapping windows, possibly on both strands; if you
1072 * want more freedom to move around in the sequence
1073 * grabbing windows in another order, you can use the
1074 * <FetchSubseq()> interface.
1075 *
1076 * Reading the reverse complement strand requires file
1077 * repositioning, so it will not work on non-repositionable
1078 * streams like gzipped files or a stdin pipe. Moreover,
1079 * for reverse complement input to be efficient, the
1080 * sequence file should have consistent line lengths,
1081 * suitable for SSI's fast subsequence indexing.
1082 *
1083 * Returns: <eslOK> on success; <sq> now contains next window of
1084 * sequence, with at least 1 new residue. The number
1085 * of new residues is <sq->W>; <sq->C> residues are
1086 * saved from the previous window. Caller may now
1087 * process residues <sq->dsq[sq->C+1]..sq->dsq[sq->n]>.
1088 *
1089 * <eslEOD> if no new residues were read for this sequence
1090 * and strand, and <sq> now contains an empty info-only
1091 * structure (annotation and <L> are valid). Before calling
1092 * <esl_sqio_ReadWindow()> again, caller will either want
1093 * to make <W> negative (to start reading the Crick strand
1094 * of the current sequence), or it will want to reset the
1095 * <sq> (with <esl_sq_Reuse()>) to go on the next sequence.
1096 *
1097 * <eslEOF> if we've already returned <eslEOD> before to
1098 * signal the end of the previous seq record, and moreover,
1099 * there's no more sequence records in the file.
1100 *
1101 * <eslEINVAL> if an invalid residue is found in the
1102 * sequence, or if you attempt to take the reverse
1103 * complement of a sequence that can't be reverse
1104 * complemented.
1105 *
1106 * Throws: <eslESYNTAX> if you try to read a reverse window before
1107 * you've read forward strand.
1108 *
1109 * <eslECORRUPT> if something goes awry internally in the
1110 * coordinate system.
1111 *
1112 * <eslEMEM> on allocation error.
1113 */
1114 static int
1115 sqascii_ReadWindow(ESL_SQFILE *sqfp, int C, int W, ESL_SQ *sq)
1116 {
1117 int actual_start;
1118 int64_t nres;
1119 int64_t line;
1120 off_t offset;
1121 int status;
1122 ESL_SQ *tmpsq = NULL;
1123
1124 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1125
1126 if (esl_sqio_IsAlignment(sqfp->format))
1127 {
1128 /* special: if we're initializing a revcomp window read, back ascii->idx up one */
1129 if (W < 0 && sq->start == 0) ascii->idx--;
1130
1131 if (ascii->msa == NULL || ascii->idx >= ascii->msa->nseq)
1132 { /* need new alignment? */
1133 esl_msa_Destroy(ascii->msa);
1134 status = esl_msafile_Read(ascii->afp, &(ascii->msa));
1135 if (status == eslEFORMAT)
1136 { /* oops, a parse error; upload the error info from afp to sqfp */
1137 ascii->linenumber = ascii->afp->linenumber;
1138 strcpy(ascii->errbuf, ascii->afp->errmsg); /* errbufs same size! */
1139 return eslEFORMAT;
1140 }
1141 else if (status != eslOK) goto ERROR;
1142 ascii->idx = 0;
1143 }
1144
1145 /* grab appropriate seq from alignment into tmpsq */
1146 if ((status = esl_sq_FetchFromMSA(ascii->msa, ascii->idx, &tmpsq)) != eslOK) goto ERROR;
1147
1148 /*by default, tmpsq is an ascii sequence, convert it to digital if that's what sq is*/
1149 if (sq->seq == NULL &&
1150 (( status = esl_sq_Digitize(sq->abc, tmpsq)) != eslOK))
1151 goto ERROR;
1152
1153 /* Figure out tmpsq coords we'll put in sq */
1154 if (W > 0)
1155 {/* forward strand */
1156 sq->C = ESL_MIN(sq->n, C);
1157 sq->start = sq->end - sq->C + 1;
1158 sq->end = ESL_MIN(tmpsq->L, sq->end + W);
1159 sq->n = sq->end - sq->start + 1;
1160 sq->W = sq->n - sq->C;
1161 }
1162 else
1163 {/* reverse strand */
1164 if (sq->L == -1) ESL_XEXCEPTION(eslESYNTAX, "Can't read reverse complement until you've read forward strand");
1165
1166 sq->C = ESL_MIN(sq->n, sq->end + C - 1);
1167 sq->end = (sq->start == 0 ? sq->L : sq->end + sq->C - 1);
1168 sq->start = ESL_MAX(1, sq->end + W - sq->C - 1);
1169 sq->n = sq->end - sq->start + 1;
1170 sq->W = sq->n - sq->C;
1171 }
1172
1173 if (sq->W == 0)/* no new sequence? that's the EOD case */
1174 {
1175 sq->start = 0;
1176 sq->end = 0;
1177 sq->C = 0;
1178 sq->W = 0;
1179 sq->n = 0;
1180 sq->L = tmpsq->L;
1181 if (sq->dsq) sq->dsq[1] = eslDSQ_SENTINEL;
1182 else if (sq->seq) sq->seq[0] = '\0';
1183
1184 ascii->idx++;
1185 esl_sq_Destroy(tmpsq);
1186 return eslEOD;
1187 }
1188
1189 /* Copy the sequence frag. */
1190 if (tmpsq->ss != NULL && sq->ss == NULL) ESL_ALLOC(sq->ss, sizeof(char) * (sq->salloc)); /* this *must* be for salloc */
1191 esl_sq_GrowTo(sq, sq->n);
1192 if (tmpsq->seq != NULL)
1193 {/* text mode */
1194 memcpy(sq->seq, tmpsq->seq + sq->start - 1, sizeof(char) * sq->n);
1195 sq->seq[sq->n] = '\0';
1196 if (tmpsq->ss != NULL) {
1197 memcpy(sq->ss, tmpsq->ss + sq->start - 1, sizeof(char) * sq->n);
1198 sq->ss[sq->n] = '\0';
1199 }
1200 }
1201 else
1202 {
1203 memcpy(sq->dsq + 1, tmpsq->dsq + sq->start, sizeof(ESL_DSQ) * sq->n);
1204 sq->dsq[sq->n+1] = eslDSQ_SENTINEL;
1205 if (tmpsq->ss != NULL) {
1206 memcpy(sq->ss + 1, tmpsq->ss + sq->start, sizeof(char) * sq->n);
1207 sq->ss[sq->n+1] = '\0';
1208 }
1209 }
1210 if (W < 0 && (status = esl_sq_ReverseComplement(sq)) != eslOK)
1211 ESL_XFAIL(eslEINVAL, ascii->errbuf, "Can't reverse complement that sequence window");
1212
1213 /* Copy annotation */
1214 if ((status = esl_sq_SetName (sq, tmpsq->name)) != eslOK) goto ERROR;
1215 if ((status = esl_sq_SetSource (sq, tmpsq->name)) != eslOK) goto ERROR;
1216 if ((status = esl_sq_SetAccession(sq, tmpsq->acc)) != eslOK) goto ERROR;
1217 if ((status = esl_sq_SetDesc (sq, tmpsq->desc)) != eslOK) goto ERROR;
1218 sq->roff = -1;
1219 sq->doff = -1;
1220 sq->eoff = -1;
1221 sq->hoff = -1;
1222
1223 esl_sq_Destroy(tmpsq);
1224 return eslOK;
1225 }
1226
1227 /* Now for the normal case: we're reading a normal unaligned seq file, not an alignment. */
1228 /* Negative W indicates reverse complement direction */
1229 if (W < 0)
1230 {
1231 if (sq->L == -1) ESL_EXCEPTION(eslESYNTAX, "Can't read reverse complement until you've read forward strand");
1232
1233 if (sq->end == 1 || sq->L == 0)
1234 { /* last end == 1 means last window was the final one on reverse strand,
1235 * so we're EOD; jump back to last forward position.
1236 *
1237 * Also check for the unusual case of sq->L == 0, a completely empty sequence:
1238 * in that case, immediately return eslEOD.
1239 */
1240 if (ascii->bookmark_offset > 0)
1241 {
1242 if (esl_sqfile_Position(sqfp, ascii->bookmark_offset) != eslOK)
1243 ESL_EXCEPTION(eslECORRUPT, "Failed to reposition seq file at last forward bookmark");
1244 ascii->linenumber = ascii->bookmark_linenum;
1245 }
1246 else
1247 ascii->nc = 0; /* signals EOF */
1248
1249 ascii->bookmark_offset = 0;
1250 ascii->bookmark_linenum = 0;
1251
1252 sq->start = 0;
1253 sq->end = 0;
1254 sq->C = 0;
1255 sq->W = 0;
1256 sq->n = 0;
1257 /* sq->L stays as it is */
1258 if (sq->dsq != NULL) sq->dsq[1] = eslDSQ_SENTINEL;
1259 else sq->seq[0] = '\0';
1260 return eslEOD;
1261 }
1262
1263 /* If sq->start == 0, we haven't read any reverse windows yet;
1264 * init reading from sq->L
1265 */
1266 W = -W;
1267 if (sq->start == 0)
1268 {
1269 sq->start = ESL_MAX(1, (sq->L - W + 1));
1270 sq->end = sq->L;
1271 sq->C = 0;
1272 sq->W = sq->end - sq->start + 1;
1273 ascii->curbpl = -1;
1274 ascii->currpl = -1;
1275 ascii->prvbpl = -1;
1276 ascii->prvrpl = -1;
1277 ascii->linenumber = -1;
1278 ascii->L = -1;
1279 }
1280 else
1281 { /* Else, we're continuing to next window; prv was <end>..<start> */
1282 sq->C = ESL_MIN(C, sq->L - sq->end + 1); /* based on prev window's end */
1283 sq->end = sq->end + sq->C - 1; /* also based on prev end */
1284 sq->start = ESL_MAX(1, (sq->end - W - sq->C + 1));
1285 sq->W = sq->end - sq->start + 1 - sq->C;
1286 }
1287
1288 /* Now position for a subseq fetch of <start..end> on fwd strand, using SSI offset calc */
1289 ESL_DASSERT1(( sq->doff != 0 ));
1290 if (ascii->bpl == 0 || ascii->rpl == 0) /* no help; brute force resolution. */
1291 {
1292 offset = sq->doff;
1293 actual_start = 1;
1294 }
1295 else if (ascii->bpl == ascii->rpl+1) /* residue resolution */
1296 {
1297 line = (sq->start-1) / ascii->rpl; /* data line #0.. that <end> is on */
1298 offset = sq->doff + line * ascii->bpl + (sq->start-1)%ascii->rpl;
1299 actual_start = sq->start;
1300 }
1301 else /* line resolution */
1302 {
1303 line = (sq->start-1) / ascii->rpl; /* data line #0.. that <end> is on */
1304 offset = sq->doff + line * ascii->bpl;
1305 actual_start = 1 + line * ascii->rpl;
1306 }
1307
1308 if (esl_sqfile_Position(sqfp, offset) != eslOK)
1309 ESL_EXCEPTION(eslECORRUPT, "Failed to reposition seq file for reverse window read");
1310
1311 /* grab the subseq and rev comp it */
1312 if ((status = esl_sq_GrowTo(sq, sq->C+sq->W)) != eslOK) return status;
1313 sq->n = 0;
1314 status = read_nres(sqfp, sq, (sq->start - actual_start), (sq->end - sq->start + 1), &nres);
1315
1316 if (status != eslOK || nres < (sq->end - sq->start + 1))
1317 ESL_EXCEPTION(eslECORRUPT, "Failed to extract %d..%d", sq->start, sq->end);
1318
1319 status = esl_sq_ReverseComplement(sq);
1320 if (status == eslEINVAL) ESL_FAIL(eslEINVAL, ascii->errbuf, "can't reverse complement that seq - it's not DNA/RNA");
1321 else if (status != eslOK) return status;
1322
1323 return eslOK;
1324 }
1325
1326 /* Else, we're reading the forward strand */
1327 else
1328 { /* sq->start == 0 means we haven't read any windows on this sequence yet...
1329 * it's a new record, and we need to initialize with the header and
1330 * the first window. This is the only case that we're allowed to return
1331 * EOF from.
1332 */
1333 if (sq->start == 0)
1334 {
1335 if (ascii->nc == 0) return eslEOF;
1336 if ((status = ascii->parse_header(sqfp, sq)) != eslOK) return status; /* EOF, EFORMAT */
1337 sq->start = 1;
1338 sq->C = 0;/* no context in first window */
1339 sq->L = -1;/* won't be known 'til EOD. */
1340 ascii->L = 0;/* init to 0, so we can count residues as we go */
1341 esl_sq_SetSource(sq, sq->name);
1342 /* the <ascii->buf> is now positioned at the start of seq data */
1343 /* ascii->linenumber is ok where it is */
1344 /* the header_*() routines initialized rpl,bpl bookkeeping at start of seq line,
1345 * and also sq->doff,roff.
1346 */
1347 }
1348 else
1349 { /* else we're reading a window other than first; slide context over. */
1350 sq->C = ESL_MIN(C, sq->n);
1351
1352 /* if the case where the window is smaller than the context and the
1353 * context is not full, it is not necessary to move the context part
1354 * of the sequence that has been read in.
1355 */
1356 if (sq->C >= C) {
1357 /* now handle the case where the context is full */
1358 if (sq->seq != NULL) memmove(sq->seq, sq->seq + sq->n - sq->C, sq->C);
1359 else memmove(sq->dsq+1, sq->dsq + sq->n - sq->C + 1, sq->C);
1360 sq->start = ascii->L - sq->C + 1;
1361 sq->n = C;
1362 }
1363 }
1364
1365 if ((status = esl_sq_GrowTo(sq, C+W)) != eslOK) return status; /* EMEM */
1366 status = read_nres(sqfp, sq, 0, W, &nres);
1367 ascii->L += nres;
1368
1369 if (status == eslEOD)
1370 { /* Forward strand is done. 0 residues were read. Return eslEOD and an empty (info) <sq>. */
1371 if ((status = ascii->parse_end(sqfp, sq)) != eslOK) return status;
1372
1373 sq->start = 0;
1374 sq->end = 0;
1375 sq->C = 0;
1376 sq->W = 0;
1377 sq->L = ascii->L;
1378 sq->n = 0;
1379
1380 if (ascii->nc > 0) {
1381 ascii->bookmark_offset = ascii->boff+ascii->bpos; /* remember where the next seq starts. */
1382 //ascii->bookmark_linenum = ascii->bookmark_linenum;
1383 } else {
1384 ascii->bookmark_offset = 0; /* signals for EOF, no more seqs */
1385 ascii->bookmark_linenum = 0;
1386 }
1387
1388 if (sq->dsq != NULL) sq->dsq[1] = eslDSQ_SENTINEL; /* erase the saved context */
1389 else sq->seq[0] = '\0';
1390 return eslEOD;
1391 }
1392 else if (status == eslOK)
1393 { /* Forward strand is still in progress. <= W residues were read. Return eslOK. */
1394 sq->end = sq->start + sq->C + nres - 1;
1395 sq->W = nres;
1396 return eslOK;
1397 }
1398 else return status;/* EFORMAT,EMEM */
1399 }
1400 /*NOTREACHED*/
1401 return eslOK;
1402
1403 ERROR:
1404 if (tmpsq != NULL) esl_sq_Destroy(tmpsq);
1405 return status;
1406 }
1407
1408 /* Function: sqascii_ReadBlock()
1409 * Synopsis: Read the next block of sequences from a file.
1410 *
1411 * Purpose: Reads a block of sequences from open sequence file <sqfp> into
1412 * <sqBlock>.
1413 *
1414 * In the case that <long_target> is false, the sequences are
1415 * expected to be protein - individual sequences won't be long
1416 * so read them in one-whole-sequence at a time. If <max_sequences> is set
1417 * to a number > 0 read <max_sequences> sequences, up to at most
1418 * MAX_RESIDUE_COUNT residues. <max_init_window> value is irrelevant
1419 * if <long_target> is false.
1420 *
1421 * If <long_target> is true, the sequences are expected to be DNA.
1422 * Because sequences in a DNA database can exceed MAX_RESIDUE_COUNT,
1423 * this function uses ReadWindow to read chunks of sequence no
1424 * larger than <max_residues>, and must allow for the possibility that a
1425 * request will be made to continue reading a partly-read
1426 * sequence. This case also respects the <max_sequences> limit.
1427 *
1428 * If <long_target> is true and <max_init_window> is TRUE,
1429 * the first window read from each sequence (of length L)
1430 * is always min(L, <max_residues>). If <max_init_window>
1431 * is FALSE, then the length of the first window read from
1432 * each sequence is calculated differently as
1433 * max(<max_residues> - <size>, <max_residues> * .05);
1434 * where <size> is total number of residues already existing
1435 * in the block. <max_init_window> == TRUE mode was added
1436 * to ensure that the window boundaries read are not dependent
1437 * on the order of the sequence in the file, thus ensuring
1438 * reproducibility if (for example) a user extracts one
1439 * sequence from a file and reruns a program on it (and all
1440 * else remains equal).
1441 *
1442 * Returns: <eslOK> on success; the new sequence is stored in <sqBlock>.
1443 *
1444 * Returns <eslEOF> when there is no sequence left in the
1445 * file (including first attempt to read an empty file).
1446 *
1447 * Returns <eslEFORMAT> if there's a problem with the format,
1448 * such as an illegal character; the line number that the parse
1449 * error occurs on is in <sqfp->linenumber>, and an informative
1450 * error message is placed in <ascii->errbuf>.
1451 *
1452 * Throws: <eslEMEM> on allocation failure;
1453 * <eslEINCONCEIVABLE> on internal error.
1454 */
1455 static int
1456 sqascii_ReadBlock(ESL_SQFILE *sqfp, ESL_SQ_BLOCK *sqBlock, int max_residues, int max_sequences, int max_init_window, int long_target)
1457 {
1458 int i = 0;
1459 int size = 0;
1460 int status = eslOK;
1461 ESL_SQ *tmpsq = NULL;
1462
1463 sqBlock->count = 0;
1464 if (max_sequences < 1 || max_sequences > sqBlock->listSize)
1465 max_sequences = sqBlock->listSize;
1466
1467
1468 if ( !long_target )
1469 { /* in these cases, an individual sequence won't ever be really long,
1470 so just read in a sequence at a time */
1471
1472 for (i = 0; i < max_sequences && size < MAX_RESIDUE_COUNT; ++i)
1473 {
1474 status = sqascii_Read(sqfp, sqBlock->list + i);
1475
1476 if (status != eslOK) break;
1477 size += sqBlock->list[i].n;
1478 ++sqBlock->count;
1479 }
1480 }
1481 else
1482 { /* DNA, not an alignment. Might be really long sequences */
1483
1484 if (max_residues < 1)
1485 max_residues = MAX_RESIDUE_COUNT;
1486
1487 tmpsq = esl_sq_CreateDigital(sqBlock->list->abc);
1488 //if complete flag is set to FALSE, then the prior block must have ended with a window that was a possibly
1489 //incomplete part of it's full sequence. Read another overlapping window.
1490 if (! sqBlock->complete )
1491 {
1492 //overloading C as indicator of how big C should be for this window reading action
1493 status = sqascii_ReadWindow(sqfp, sqBlock->list->C, max_residues, sqBlock->list);
1494 if (status == eslOK)
1495 {
1496 sqBlock->count = i = 1;
1497 size = sqBlock->list->n - sqBlock->list->C;
1498 sqBlock->list->L = sqfp->data.ascii.L;
1499 if (size == max_residues)
1500 { // Filled the block with a single very long window.
1501
1502 sqBlock->complete = FALSE; // default value, unless overridden below
1503 status = skip_whitespace(sqfp);
1504 if ( status != eslOK ) { // either EOD or end of buffer (EOF) was reached before the next character was seen
1505 sqBlock->complete = TRUE;
1506 status = eslOK;
1507 }
1508
1509 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1510 return status;
1511 }
1512 else
1513 {
1514 // Burn off EOD (see notes for similar entry ~25 lines below), then go fetch the next sequence
1515 esl_sq_Reuse(tmpsq);
1516 tmpsq->start = sqBlock->list->start ;
1517 tmpsq->C = 0;
1518 status = sqascii_ReadWindow(sqfp, 0, max_residues, tmpsq);
1519 if (status != eslEOD) {
1520 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1521 return status; //surprising
1522 }
1523 //sqBlock->list->L = tmpsq->L;
1524 }
1525 }
1526 else if (status == eslEOD)
1527 { // turns out there isn't any more of the sequence to read, after all
1528 }
1529 else
1530 {
1531 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1532 return status;
1533 }
1534 } // otherwise, just start at the beginning
1535
1536
1537 for ( ; i < max_sequences && size < max_residues; ++i) {
1538 /* restricted request_size is used to ensure that all blocks are pretty close to the
1539 * same size. Without it, we may either naively keep asking for max_residue windows,
1540 * which can result in a window with ~2*max_residues ... or we can end up with absurdly
1541 * short fragments at the end of blocks
1542 */
1543 int request_size = (max_init_window) ? max_residues : ESL_MAX(max_residues-size, max_residues * .05);
1544
1545 esl_sq_Reuse(tmpsq);
1546 esl_sq_Reuse(sqBlock->list + i);
1547
1548 status = sqascii_ReadWindow(sqfp, 0, request_size , tmpsq);
1549 esl_sq_Copy(tmpsq, sqBlock->list +i);
1550 if (status != eslOK && status != eslEOD){
1551 break;
1552 } /* end of sequences (eslEOF), or we read an empty seq (eslEOD) or error (other) */
1553 size += sqBlock->list[i].n - sqBlock->list[i].C;
1554 sqBlock->list[i].L = sqfp->data.ascii.L;
1555 ++(sqBlock->count);
1556
1557 if (size >= max_residues) {
1558 // a full window worth of sequence has been read; did we reach the end of the final sequence in the block?
1559 sqBlock->complete = FALSE; // default value, unless overridden below
1560
1561 status = skip_whitespace(sqfp);
1562 if ( status != eslOK ) { // either EOD or end of buffer (EOF) was reached before the next character was seen
1563 sqBlock->complete = TRUE;
1564 status = eslOK;
1565 }
1566
1567 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1568 return status;
1569 } else if(status == eslEOD) {
1570 /* We've read an empty sequence of length 0, rare, but
1571 * possible, and we need to be able to handle it
1572 * gracefully. Ensure L is 0, set status to eslOK and move
1573 * on, we've already incremented sqBlock->count by 1
1574 * above. This means our block may contain zero-length
1575 * sequences when we return (that is, we still add these
1576 * seqs onto the block instead of skipping them altogether).
1577 */
1578 sqBlock->list[i].L = 0; /* actually, this should already be 0... */
1579 status = eslOK;
1580 } else {
1581 /* Sequence finished, but haven't yet reached max_residues. Need to burn off the EOD value
1582 that will be returned by the next ReadWindow call. Can just use a tmp sq, after setting
1583 a couple values ReadWindow needs to see for correct processing.
1584 */
1585 esl_sq_Reuse(tmpsq);
1586 tmpsq->start = sqBlock->list[i].start ;
1587 tmpsq->C = 0;
1588 status = sqascii_ReadWindow(sqfp, 0, max_residues, tmpsq);
1589
1590 if (status != eslEOD) {
1591 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1592 return status; //surprising
1593 }
1594 //sqBlock->list[i].L = tmpsq->L;
1595 status = eslOK;
1596 }
1597 }
1598 }
1599
1600 /* EOF will be returned only in the case were no sequences were read */
1601 if (status == eslEOF && i > 0) status = eslOK;
1602
1603 sqBlock->complete = TRUE;
1604
1605 if(tmpsq != NULL) esl_sq_Destroy(tmpsq);
1606
1607 return status;
1608 }
1609
1610 /* Function: sqascii_Echo()
1611 * Synopsis: Echo a sequence's record onto output stream.
1612 *
1613 * Purpose: Given a complete <sq> that we have read by some means
1614 * from an open <sqfp>; echo that sequence's record
1615 * onto the output stream <ofp>.
1616 *
1617 * This allows records to be regurgitated exactly as they
1618 * appear, rather than writing the subset of information
1619 * stored in an <ESL_SQ>. <esl-sfetch> in the miniapps uses
1620 * this, for example.
1621 *
1622 * Because this relies on repositioning the <sqfp>, it
1623 * cannot be called on non-positionable streams (stdin or
1624 * gzipped files). Because it relies on the sequence lying
1625 * in a contiguous sequence of bytes in the file, it cannot
1626 * be called on a sequence in a multiple alignment file.
1627 * Trying to do so throws an <eslEINVAL> exception.
1628 *
1629 * Returns: <eslOK> on success.
1630 *
1631 * Throws: <eslEINVAL> if <sqfp> isn't a repositionable sequence file.
1632 * <eslECORRUPT> if we run out of data, probably from bad offsets
1633 * <eslEMEM> on allocation failure.
1634 * <eslESYS> on system call failures.
1635 *
1636 *
1637 */
1638 static int
1639 sqascii_Echo(ESL_SQFILE *sqfp, const ESL_SQ *sq, FILE *ofp)
1640 {
1641 int status;
1642 int64_t save_linenumber;
1643 int save_currpl;
1644 int save_curbpl;
1645 int save_prvrpl;
1646 int save_prvbpl;
1647 int64_t save_L;
1648 int n;
1649 int nwritten;
1650
1651 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1652
1653 if (ascii->do_stdin) ESL_EXCEPTION(eslEINVAL, "can't Echo() a sequence from standard input");
1654 if (ascii->do_gzip) ESL_EXCEPTION(eslEINVAL, "can't Echo() a sequence from a gzipped file");
1655 if (esl_sqio_IsAlignment(sqfp->format)) ESL_EXCEPTION(eslEINVAL, "can't Echo() a sequence from an alignment file");
1656 if (sq->roff == -1 || sq->eoff == -1) ESL_EXCEPTION(eslEINVAL, "can't Echo() a sequence without disk offset info");
1657
1658 save_linenumber = ascii->linenumber;
1659 save_currpl = ascii->currpl;
1660 save_curbpl = ascii->curbpl;
1661 save_prvrpl = ascii->prvrpl;
1662 save_prvbpl = ascii->prvbpl;
1663 save_L = ascii->L;
1664
1665 status = esl_sqfile_Position(sqfp, sq->roff);
1666 if (status == eslEOF) ESL_EXCEPTION(eslECORRUPT, "repositioning failed; bad offset?");
1667 else if (status != eslOK) return status;
1668
1669 while (ascii->boff + ascii->nc <= sq->eoff)
1670 {
1671 if (fwrite(ascii->buf, sizeof(char), ascii->nc, ofp) != ascii->nc) ESL_EXCEPTION(eslESYS, "fwrite() failed");
1672 if (loadbuf(sqfp) != eslOK) ESL_EXCEPTION(eslECORRUPT, "repositioning failed; bad offset?");
1673 }
1674 n = sq->eoff - ascii->boff + 1;
1675 nwritten = fwrite(ascii->buf, sizeof(char), n, ofp);
1676 if (nwritten != n) ESL_EXCEPTION(eslESYS, "fwrite() failed");
1677
1678 status = esl_sqfile_Position(sqfp, sq->roff);
1679 if (status == eslEOF) ESL_EXCEPTION(eslECORRUPT, "repositioning failed; bad offset?");
1680 else if (status != eslOK) return status;
1681
1682 ascii->linenumber = save_linenumber;
1683 ascii->currpl = save_currpl;
1684 ascii->curbpl = save_curbpl;
1685 ascii->prvrpl = save_prvrpl;
1686 ascii->prvbpl = save_prvbpl;
1687 ascii->L = save_L;
1688 return eslOK;
1689 }
1690 /*------------------ end, sequential sequence input -------------*/
1691
1692
1693 /*****************************************************************
1694 *# 5. Sequence/subsequence fetching, random access [with <ssi>]
1695 *****************************************************************/
1696
1697 /* Function: sqascii_OpenSSI()
1698 * Synopsis: Opens an SSI index associated with a sequence file.
1699 *
1700 * Purpose: Opens an SSI index file associated with the already open
1701 * sequence file <sqfp>. If successful, the necessary
1702 * information about the open SSI file is stored internally
1703 * in <sqfp>.
1704 *
1705 * The SSI index file name is determined in one of two
1706 * ways, depending on whether a non-<NULL> <ssifile_hint>
1707 * is provided.
1708 *
1709 * If <ssifile_hint> is <NULL>, the default for
1710 * constructing the SSI filename from the sequence
1711 * filename, by using exactly the same path (if any) for
1712 * the sequence filename, and appending the suffix <.ssi>.
1713 * For example, the SSI index for <foo> is <foo.ssi>, for
1714 * <./foo.fa> is <./foo.fa.ssi>, and for
1715 * </my/path/to/foo.1.fa> is </my/path/to/foo.1.fa.ssi>.
1716 *
1717 * If <ssifile_hint> is <non-NULL>, this exact fully
1718 * qualified path is used as the SSI file name.
1719 *
1720 * Returns: <eslOK> on success, and <sqfp->ssi> is now internally
1721 * valid.
1722 *
1723 * <eslENOTFOUND> if no SSI index file is found;
1724 * <eslEFORMAT> if it's found, but appears to be in incorrect format;
1725 * <eslERANGE> if the SSI file uses 64-bit offsets but we're on
1726 * a system that doesn't support 64-bit file offsets.
1727 *
1728 * Throws: <eslEINVAL> if the open sequence file <sqfp> doesn't
1729 * correspond to a normal sequence flatfile -- we can't
1730 * random access in .gz compressed files, standard input,
1731 * or multiple alignment files that we're reading
1732 * sequentially.
1733 *
1734 * Throws <eslEMEM> on allocation error.
1735 */
1736 static int
1737 sqascii_OpenSSI(ESL_SQFILE *sqfp, const char *ssifile_hint)
1738 {
1739 int status;
1740
1741 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1742
1743 if (ascii->do_gzip) ESL_EXCEPTION(eslEINVAL, "can't open an SSI index for a .gz compressed seq file");
1744 if (ascii->do_stdin) ESL_EXCEPTION(eslEINVAL, "can't open an SSI index for standard input");
1745 if (ascii->afp != NULL) ESL_EXCEPTION(eslEINVAL, "can't open an SSI index for sequential input from an MSA");
1746
1747 if (ssifile_hint == NULL) {
1748 if ((status = esl_strdup(sqfp->filename, -1, &(ascii->ssifile))) != eslOK) return status;
1749 if ((status = esl_strcat(&(ascii->ssifile), -1, ".ssi", 4)) != eslOK) return status;
1750 } else {
1751 if ((status = esl_strdup(ssifile_hint, -1, &(ascii->ssifile))) != eslOK) return status;
1752 }
1753
1754 return esl_ssi_Open(ascii->ssifile, &(ascii->ssi));
1755 }
1756
1757
1758
1759 /* Function: sqascii_PositionByKey()
1760 * Synopsis: Use SSI to reposition seq file to a particular sequence.
1761 *
1762 * Purpose: Reposition <sqfp> so that the next sequence we read will
1763 * be the one named (or accessioned) <key>.
1764 *
1765 * <sqfp->linenumber> is reset to be relative to the start
1766 * of the record named <key>, rather than the start of the
1767 * file.
1768 *
1769 * Returns: <eslOK> on success, and the file <sqfp> is repositioned
1770 * so that the next <esl_sqio_Read()> call will read the
1771 * sequence named <key>.
1772 *
1773 * Returns <eslENOTFOUND> if <key> isn't found in the
1774 * index; in this case, the position of <sqfp> in the file
1775 * is unchanged.
1776 *
1777 * Returns <eslEFORMAT> if something goes wrong trying to
1778 * read the index, almost certainly indicating a format
1779 * problem in the SSI file.
1780 *
1781 * Returns <eslEOF> if, after repositioning, we fail to
1782 * load the next line or buffer from the sequence file;
1783 * this probably also indicates a format problem in the SSI
1784 * file.
1785 *
1786 * Throws: <eslEMEM> on allocation error;
1787 * <eslEINVAL> if there's no open SSI index in <sqfp>;
1788 * <eslESYS> if the <fseek()> fails.
1789 *
1790 * In all these cases, the state of <sqfp> becomes
1791 * undefined, and the caller should not use it again.
1792 */
1793 static int
1794 sqascii_PositionByKey(ESL_SQFILE *sqfp, const char *key)
1795 {
1796 uint16_t fh;
1797 off_t offset;
1798 int status;
1799
1800 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1801
1802 if (ascii->ssi == NULL) ESL_EXCEPTION(eslEINVAL,"Need an open SSI index to call esl_sqfile_PositionByKey()");
1803 if ((status = esl_ssi_FindName(ascii->ssi, key, &fh, &offset, NULL, NULL)) != eslOK) return status;
1804 return esl_sqfile_Position(sqfp, offset);
1805 }
1806
1807
1808 /* Function: sqascii_PositionByNumber()
1809 * Synopsis: Use SSI to reposition by sequence number
1810 *
1811 * Purpose: Reposition <sqfp> so that the next sequence we
1812 * read will be the <which>'th sequence, where <which>
1813 * is <0..sqfp->ssi->nprimary-1>.
1814 *
1815 * <sqfp->linenumber> is reset to be relative to the start
1816 * of the record named <key>, rather than the start of the
1817 * file.
1818 *
1819 * Returns: <eslOK> on success, and the file <sqfp> is repositioned.
1820 *
1821 * Returns <eslENOTFOUND> if there is no sequence number
1822 * <which> in the index; in this case, the position of
1823 * <sqfp> in the file is unchanged.
1824 *
1825 * Returns <eslEFORMAT> if something goes wrong trying to
1826 * read the index, almost certainly indicating a format
1827 * problem in the SSI file.
1828 *
1829 * Returns <eslEOF> if, after repositioning, we fail to
1830 * load the next line or buffer from the sequence file;
1831 * this probably also indicates a format problem in the SSI
1832 * file.
1833 *
1834 * Throws: <eslEMEM> on allocation error;
1835 * <eslEINVAL> if there's no open SSI index in <sqfp>;
1836 * <eslESYS> if the <fseek()> fails.
1837 *
1838 * In all these cases, the state of <sqfp> becomes
1839 * undefined, and the caller should not use it again.
1840 */
1841 static int
1842 sqascii_PositionByNumber(ESL_SQFILE *sqfp, int which)
1843 {
1844 uint16_t fh;
1845 off_t offset;
1846 int status;
1847
1848 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1849
1850 if (ascii->ssi == NULL) ESL_EXCEPTION(eslEINVAL,"Need open SSI index to call esl_sqfile_PositionByNumber()");
1851 if ((status = esl_ssi_FindNumber(ascii->ssi, which, &fh, &offset, NULL, NULL, NULL)) != eslOK) return status;
1852 return esl_sqfile_Position(sqfp, offset);
1853 }
1854
1855
1856 /* Function: sqascii_Fetch()
1857 * Synopsis: Fetch a complete sequence, using SSI indexing.
1858 *
1859 * Purpose: Fetch a sequence named (or accessioned) <key> from
1860 * the repositionable, open sequence file <sqfp>.
1861 * The open <sqfp> must have an open SSI index.
1862 * The sequence is returned in <sq>.
1863 *
1864 * Returns: <eslOK> on soccess.
1865 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
1866 * be repositioned.
1867 * <eslENOTFOUND> if <source> isn't found in the file.
1868 * <eslEFORMAT> if either the index file or the sequence file
1869 * can't be parsed, because of unexpected format issues.
1870 *
1871 * Throws: <eslEMEM> on allocation error.
1872 */
1873 static int
1874 sqascii_Fetch(ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq)
1875 {
1876 int status;
1877
1878 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1879
1880 if (ascii->ssi == NULL) ESL_FAIL(eslEINVAL, ascii->errbuf, "No SSI index for %s; can't fetch subsequences", sqfp->filename);
1881 if ((status = sqascii_PositionByKey(sqfp, key)) != eslOK) return status;
1882 if ((status = sqascii_Read(sqfp, sq)) != eslOK) return status;
1883 return eslOK;
1884 }
1885
1886 /* Function: sqascii_FetchInfo()
1887 * Synopsis: Fetch a sequence's info, using SSI indexing.
1888 *
1889 * Purpose: Fetch a sequence named (or accessioned) <key> from
1890 * the repositionable, open sequence file <sqfp>, reading
1891 * all info except the sequence (and secondary structure).
1892 * The open <sqfp> must have an open SSI index.
1893 * The sequence info is returned in <sq>.
1894 *
1895 * Returns: <eslOK> on soccess.
1896 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
1897 * be repositioned.
1898 * <eslENOTFOUND> if <source> isn't found in the file.
1899 * <eslEFORMAT> if either the index file or the sequence file
1900 * can't be parsed, because of unexpected format issues.
1901 *
1902 * Throws: <eslEMEM> on allocation error.
1903 */
1904 static int
1905 sqascii_FetchInfo(ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq)
1906 {
1907 int status;
1908
1909 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1910
1911 if (ascii->ssi == NULL) ESL_FAIL(eslEINVAL, ascii->errbuf, "No SSI index for %s; can't fetch subsequences", sqfp->filename);
1912 if ((status = sqascii_PositionByKey(sqfp, key)) != eslOK) return status;
1913 if ((status = sqascii_ReadInfo(sqfp, sq)) != eslOK) return status;
1914 return eslOK;
1915 }
1916
1917
1918 /* Function: sqascii_FetchSubseq()
1919 * Synopsis: Fetch a subsequence, using SSI indexing.
1920 *
1921 * Purpose: Fetch subsequence <start..end> from a sequence named (or
1922 * accessioned) <source>, in the repositionable, open sequence file <sqfp>.
1923 * The open <sqfp> must have an SSI index. Put the
1924 * subsequence in <sq>.
1925 *
1926 * As a special case, if <end> is 0, the subsequence is
1927 * fetched all the way to the end, so you don't need to
1928 * look up the sequence length <L> to fetch a suffix.
1929 *
1930 * The caller may want to rename/reaccession/reannotate the
1931 * subsequence. Upon successful return, <sq->name> is set
1932 * to <source/start-end>, and <sq->source> is set to
1933 * <source> The accession and description <sq->acc> and
1934 * <sq->desc> are set to the accession and description of
1935 * the source sequence.
1936 *
1937 * Returns: <eslOK> on success.
1938 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
1939 * be repositioned.
1940 * <eslENOTFOUND> if <source> isn't found in the file.
1941 * <eslEFORMAT> if either the index file or the sequence file
1942 * can't be parsed, because of unexpected format issues.
1943 * <eslERANGE> if the <start..end> coords don't lie entirely
1944 * within the <source> sequence.
1945 *
1946 * Throws: <eslEMEM> on allocation errors.
1947 */
1948 static int
1949 sqascii_FetchSubseq(ESL_SQFILE *sqfp, const char *source, int64_t start, int64_t end, ESL_SQ *sq)
1950 {
1951 uint16_t fh;/* SSI file handle */
1952 off_t r_off, d_off;
1953 int64_t L;
1954 int64_t actual_start;
1955 int64_t nskip;
1956 int64_t nres;
1957 int64_t n;
1958 int status;
1959
1960 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
1961
1962 if (ascii->ssi == NULL) ESL_FAIL(eslEINVAL, ascii->errbuf, "No SSI index for %s; can't fetch subsequences", sqfp->filename);
1963
1964 /* Find sequence info in the index */
1965 status = esl_ssi_FindSubseq(ascii->ssi, source, start, &fh, &r_off, &d_off, &L, &actual_start);
1966 if (status == eslENOTFOUND) ESL_FAIL(status, ascii->errbuf, "Didn't find sequence %s in the index", source);
1967 else if (status == eslEFORMAT) ESL_FAIL(status, ascii->errbuf, "Failure reading SSI index; corrupt or bad format");
1968 else if (status == eslERANGE) ESL_FAIL(status, ascii->errbuf, "Requested start %" PRIi64 " isn't in the sequence %s", start, source);
1969 else if (status != eslOK) ESL_FAIL(status, ascii->errbuf, "Unexpected failure in finding subseq offset");
1970
1971 /* The special case of end=0, asking for suffix fetch */
1972 if (end == 0) end = L;
1973
1974 /* Validate coords if we can */
1975 if (start > end) ESL_FAIL(eslERANGE, ascii->errbuf, "Subsequence start %" PRIi64 " is greater than end %" PRIi64 "\n", start, end);
1976 if (L > 0 && end > L) ESL_FAIL(eslERANGE, ascii->errbuf, "Subsequence end %" PRIi64 " is greater than length %" PRIi64 "\n", end, L);
1977
1978 /* Position the file at the record header; read the header info */
1979 status = esl_sqfile_Position(sqfp, r_off);
1980 if (status == eslEOF) ESL_FAIL(status, ascii->errbuf, "Position appears to be off the end of the file");
1981 else if (status == eslEINVAL) ESL_FAIL(status, ascii->errbuf, "Sequence file is not repositionable");
1982 else if (status != eslOK) ESL_FAIL(status, ascii->errbuf, "Failure in positioning sequence file");
1983 if ((status = ascii->parse_header(sqfp, sq)) != eslOK) return status;
1984
1985 /* Position the file close to the subseq: either at the start of the line
1986 * where the subseq starts, or exactly at the residue.
1987 */
1988 if (d_off != 0)
1989 {
1990 status = esl_sqfile_Position(sqfp, d_off);
1991 if (status == eslEOF) ESL_FAIL(eslERANGE, ascii->errbuf, "Position appears to be off the end of the file");
1992 else if (status == eslEINVAL) ESL_FAIL(status, ascii->errbuf, "Sequence file is not repositionable");
1993 else if (status != eslOK) ESL_FAIL(status, ascii->errbuf, "Failure in positioning sequence file");
1994 }
1995 /* even if we didn't have a data offset, we're positioned at the
1996 * start of the sequence anyway, because we parsed the full header
1997 */
1998 nskip = start - actual_start; /* how many residues do we still need to skip to reach start */
1999 nres = end - start + 1; /* how many residues do we need to read as subseq */
2000
2001 if ((status = esl_sq_GrowTo(sq, nres)) != eslOK) return status;
2002 status = read_nres(sqfp, sq, nskip, nres, &n);
2003 if (status != eslOK || n < nres) ESL_EXCEPTION(eslEINCONCEIVABLE, "Failed to fetch subsequence residues -- corrupt coords?");
2004
2005 /* Set the coords */
2006 sq->start = start;
2007 sq->end = end;
2008 sq->C = 0;
2009 sq->W = sq->n;
2010 sq->L = (L > 0 ? L : -1);
2011 esl_sq_FormatName(sq, "%s/%" PRId64 "-%" PRId64, source, start, end);
2012 esl_sq_SetSource (sq, source);
2013 return eslOK;
2014 }
2015 /*------------- end, random sequence access with SSI -------------------*/
2016
2017
2018 /*****************************************************************
2019 * 6. Internal routines shared by parsers
2020 *****************************************************************/
2021
2022
2023 /* loadmem()
2024 *
2025 * Load the next block of data from stream into mem buffer,
2026 * either concatenating to previous buffer (if we're recording) or
2027 * overwriting (if not).
2028 *
2029 * This block is loaded at sqfp->mem + sqfp->mpos.
2030 *
2031 * Upon return:
2032 * sqfp->mem now contains up to eslREADBUFSIZE more chars
2033 * sqfp->mpos is position of first byte in newly read block
2034 * sqfp->allocm may have increased by eslREADBUFSIZE, if we concatenated
2035 * sqfp->mn is # of chars in <mem>; <mn-1> is pos of last byte in new block
2036 *
2037 * Returns <eslEOF> (and mpos == mn) if no new data can be read;
2038 * Returns <eslOK> (and mpos < mn) if new data is read.
2039 * Throws <eslEMEM> on allocation error.
2040 */
2041 static int
2042 loadmem(ESL_SQFILE *sqfp)
2043 {
2044 void *tmp;
2045 int n = 0;
2046 int status;
2047
2048 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2049
2050 if (ascii->do_buffer)
2051 {
2052 ascii->mpos = 0;
2053 ascii->mn = 0;
2054 }
2055 else if (ascii->is_recording == TRUE)
2056 {
2057 if (ascii->mem == NULL) ascii->moff = ftello(ascii->fp); /* first time init of the offset */
2058 ESL_RALLOC(ascii->mem, tmp, sizeof(char) * (ascii->allocm + eslREADBUFSIZE));
2059 ascii->allocm += eslREADBUFSIZE;
2060 n = fread(ascii->mem + ascii->mpos, sizeof(char), eslREADBUFSIZE, ascii->fp);
2061 ascii->mn += n;
2062 }
2063 else
2064 {
2065 if (ascii->mem == NULL) {
2066 ESL_ALLOC(ascii->mem, sizeof(char) * eslREADBUFSIZE);
2067 ascii->allocm = eslREADBUFSIZE;
2068 }
2069 ascii->is_recording = -1;/* no more recording is possible now */
2070 ascii->mpos = 0;
2071 ascii->moff = ftello(ascii->fp);
2072 n = fread(ascii->mem, sizeof(char), eslREADBUFSIZE, ascii->fp); /* see note [1] below */
2073 ascii->mn = n;
2074 }
2075 return (n == 0 ? eslEOF : eslOK);
2076
2077 ERROR:
2078 return status;
2079 }
2080
2081 /* [1] Be alert for a possible problem above in that fread().
2082 * Farrar had inserted an alternative case as follows:
2083 * "If we are reading from stdin, buffered read cannot be used
2084 * because if will block until EOF or the buffer is full, ie
2085 * eslREADBUFSIZE characters have been read. Usually this would
2086 * not be a problem, unless stdin is from a pipe. In that case
2087 * if the sequence is less than eslREADBUFSIZE we would block.
2088 *
2089 * NOTE: any changes to the IO stream ascii->fp, such as fseek,
2090 * might not have any affect on the file descriptor for the stream.
2091 *
2092 * if (ascii->do_stdin) {
2093 * n = read(fileno(ascii->fp), ascii->mem, eslREADBUFSIZE);
2094 * } else {
2095 * ...
2096 *
2097 * but that's a bug, because you can't mix read and fread;
2098 * the i17-stdin.pl test fails, in particular.
2099 */
2100
2101
2102
2103
2104 /* loadbuf()
2105 * Set sqfp->buf to contain next line of data, or point to next block.
2106 * This might just mean working with previously buffered memory in <sqfp->mem>
2107 * or might require reading new data from <sqfp->fp>.
2108 *
2109 * Reset sqfp->boff to be the position of the start of the block/line.
2110 * Reset sqfp->bpos to 0.
2111 * Reset sqfp->nc to the number of chars (bytes) in the new block/line.
2112 * Returns eslOK on success; eslEOF if there's no more data in the file.
2113 * (sqfp->nc == 0 is the same as eslEOF: no data in the new buffer.)
2114 * Can throw an <eslEMEM> error.
2115 */
2116 static int
2117 loadbuf(ESL_SQFILE *sqfp)
2118 {
2119 void *tmp;
2120 char *nlp;
2121 int n;
2122 int status = eslOK;
2123
2124 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2125
2126 if (! ascii->is_linebased)
2127 {
2128 if (ascii->mpos >= ascii->mn) {
2129 if ((status = loadmem(sqfp)) == eslEMEM) return status;
2130 }
2131 ascii->buf = ascii->mem + ascii->mpos;
2132 ascii->boff = ascii->moff + ascii->mpos;
2133 ascii->balloc = 0;
2134 ascii->bpos = 0;
2135 ascii->nc = ascii->mn - ascii->mpos;
2136 ascii->mpos += ascii->nc;
2137 }
2138 else
2139 { /* Copy next line from <mem> into <buf>. Might require new load(s) into <mem>. */
2140 if (ascii->mpos >= ascii->mn) {
2141 if ((status = loadmem(sqfp)) == eslEMEM) return status;
2142 }
2143 ascii->boff = ascii->moff + ascii->mpos;
2144 ascii->nc = 0;
2145 nlp = memchr(ascii->mem + ascii->mpos, '\n', ascii->mn - ascii->mpos);
2146 while (nlp == NULL)
2147 {
2148 n = ascii->mn - ascii->mpos;
2149 while (ascii->nc + n + 1 > ascii->balloc) { /* +1: it'll hold the terminal \0 */
2150 ESL_RALLOC(ascii->buf, tmp, sizeof(char) * (ascii->balloc + eslREADBUFSIZE));
2151 ascii->balloc += eslREADBUFSIZE;
2152 }
2153 memcpy(ascii->buf + ascii->nc, ascii->mem + ascii->mpos, n);
2154 ascii->mpos += n;
2155 ascii->nc += n;
2156 status = loadmem(sqfp);
2157 if (status == eslEOF) { break; }
2158 else if (status != eslOK) return status;
2159 nlp = memchr(ascii->mem + ascii->mpos, '\n', ascii->mn - ascii->mpos);
2160 }
2161 if (status != eslEOF) {
2162 n = nlp - (ascii->mem + ascii->mpos) + 1; /* inclusive of \n */
2163 if (ascii->nc + n + 1 > ascii->balloc) {
2164 ESL_RALLOC(ascii->buf, tmp, sizeof(char) * (ascii->balloc + eslREADBUFSIZE));
2165 ascii->balloc += eslREADBUFSIZE;
2166 }
2167 memcpy(ascii->buf + ascii->nc, ascii->mem + ascii->mpos, n);
2168 ascii->mpos += n;
2169 ascii->nc += n;
2170 }
2171 ascii->bpos = 0;
2172 ascii->buf[ascii->nc] = '\0';
2173 }
2174 return (ascii->nc == 0 ? eslEOF : eslOK);
2175
2176 ERROR:
2177 return status;
2178 }
2179
2180 /* nextchar()
2181 *
2182 * Load next char from sqfp->buf into <*ret_c> and sets sqfp->bpos to
2183 * its position; usually this is c = sqfp->buf[++sqfp->bpos], but
2184 * we will refill the buffer w/ fresh fread() when needed, in which
2185 * case c = sqfp->buf[0] and sqfp->bpos = 0.
2186 *
2187 * Returns <eslOK> on success.
2188 * Return <eslEOF> if we ran out of data in <sqfp>.
2189 * May throw an <eslEMEM> error.
2190 */
2191 static int
2192 nextchar(ESL_SQFILE *sqfp, char *ret_c)
2193 {
2194 int status;
2195
2196 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2197
2198 ascii->bpos++;
2199 if (ascii->nc == ascii->bpos && (status = loadbuf(sqfp)) != eslOK) return status;
2200 *ret_c = ascii->buf[ascii->bpos];
2201 return eslOK;
2202 }
2203
2204 /* seebuf()
2205 *
2206 * Examine and validate the current buffer <sqfp->buf> from its
2207 * current position <sqfp->bpos> until either the buffer ends (we run
2208 * out of characters) or the sequence data ends (we see whatever
2209 * character indicates EOD in this format) or we've seen <maxn>
2210 * residues. If <maxn> is passed as -1, parse the entire buffer,
2211 * without a residue limit.
2212 *
2213 * There are three possible outcomes:
2214 * <eslOK>: The buffer is all residues that belong to the current
2215 * seq we're parsing (or chars we can ignore), at least
2216 * up to the <maxn> residue limit (if present).
2217 * <eslEOD>: Part of the buffer may be residues, but the current sequence
2218 * ends in this buffer (before <maxn> was reached).
2219 * <eslEFORMAT>: Somewhere before we reached the end of the buffer or
2220 * the sequence record, we saw an illegal character.
2221 *
2222 * On <eslOK>:
2223 * *opt_nres is the number of residues in the buffer (up to <maxn>)
2224 * *opt_endpos is sqfp->nc (off the end of the buffer by one)
2225 * The caller will want to deal with the buffer, then load the next one.
2226 *
2227 * On <eslEOD>: same as OK, except:
2228 * *opt_endpos is where sqfp->bpos *would* be at when we saw the EOD
2229 * signal (the next '>', in FASTA files) had we been parsing residues
2230 * Therefore on EOD, the caller will want to deal with the <*opt_nres>
2231 * residues in this buffer, then reposition the buffer by
2232 * <sqfp->bpos = *opt_epos> (without reloading the buffer), so
2233 * the next read will pick up there.
2234 *
2235 * On <eslEFORMAT>:
2236 * ascii->errbuf contains informative message about the format error.
2237 *
2238 * seebuf() also handles linenumber and SSI bookkeeping in
2239 * <sqfp>. Every newline character seen increments <linenumber> (thus,
2240 * on EFORMAT return, linenumber is set to the line on which the bad
2241 * char occurred). <curbpl>,<currpl>,<prvbpl>,<prvrpl> keep track of # of bytes,
2242 * residues on the current,prev line; they keep state across calls to seebuf().
2243 * <bpl>,<rpl> are tracking whether there's a constant number of
2244 * bytes/residues per line; these are either -1 for "not set yet", 0
2245 * for "no, not constant", or a number > 0. Because of this bookkeeping, it's important
2246 * to make sure that <seebuf()> never counts the same byte twice (hence
2247 * the need for the <maxn> limit, which ReadWindow() uses.)
2248 */
2249 static int
2250 seebuf(ESL_SQFILE *sqfp, int64_t maxn, int64_t *opt_nres, int64_t *opt_endpos)
2251 {
2252 int bpos;
2253 int64_t nres = 0;
2254 int64_t nres2 = 0;/* an optimization for determining lastrpl from nres, without incrementing lastrpl on every char */
2255 int sym;
2256 ESL_DSQ x;
2257 int lasteol;
2258 int status = eslOK;
2259
2260 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2261
2262 lasteol = ascii->bpos - 1;
2263 if (maxn == -1) maxn = ascii->nc; /* makes for a more efficient test. nc is a guaranteed upper bound on nres */
2264
2265 for (bpos = ascii->bpos; nres < maxn && bpos < ascii->nc; bpos++)
2266 {
2267 sym = ascii->buf[bpos];
2268 //printf ("nres: %d, bpos: %d (%d)\n", nres, bpos, sym);
2269 if (!isascii(sym)) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": non-ASCII character %c in sequence", ascii->linenumber, sym);
2270 x = sqfp->inmap[sym];
2271
2272 if (x <= 127) nres++;
2273 else if (x == eslDSQ_EOL)
2274 {
2275 if (ascii->curbpl != -1) ascii->curbpl += bpos - lasteol;
2276 if (ascii->currpl != -1) ascii->currpl += nres - nres2;
2277 nres2 += nres - nres2;
2278
2279 if (ascii->rpl != 0 && ascii->prvrpl != -1) { /* need to treat counts on last line in record differently (can be shorter but not longer), hence cur/prv */
2280 if (ascii->rpl == -1) ascii->rpl = ascii->prvrpl; /* init */
2281 else if (ascii->prvrpl != ascii->rpl) ascii->rpl = 0; /* inval */
2282 else if (ascii->currpl > ascii->rpl) ascii->rpl = 0; /* inval, this covers case when final line is longer */
2283 }
2284 if (ascii->bpl != 0 && ascii->prvbpl != -1) {
2285 if (ascii->bpl == -1) ascii->bpl = ascii->prvbpl; /* init */
2286 else if (ascii->prvbpl != ascii->bpl) ascii->bpl = 0; /* inval */
2287 else if (ascii->curbpl > ascii->bpl) ascii->bpl = 0; /* inval, this covers case when final line is longer */
2288 }
2289
2290 ascii->prvbpl = ascii->curbpl;
2291 ascii->prvrpl = ascii->currpl;
2292 ascii->curbpl = 0;
2293 ascii->currpl = 0;
2294 lasteol = bpos;
2295 if (ascii->linenumber != -1) ascii->linenumber++;
2296 }
2297 else if (x == eslDSQ_ILLEGAL) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": illegal character %c", ascii->linenumber, sym);
2298 else if (x == eslDSQ_EOD) { status = eslEOD; break; }
2299 else if (x != eslDSQ_IGNORED) ESL_FAIL(eslEFORMAT, ascii->errbuf, "inmap corruption?");
2300 }
2301
2302 if (ascii->curbpl != -1) ascii->curbpl += bpos - lasteol - 1;
2303 if (ascii->currpl != -1) ascii->currpl += nres - nres2;
2304 if (opt_nres != NULL) *opt_nres = nres;
2305 if (opt_endpos != NULL) *opt_endpos = bpos;
2306 return status;
2307 }
2308
2309 /* addbuf()
2310 * Add <nres> residues from the current buffer <sqfp->buf> to <sq>.
2311 * This is designed to work when we're constructing a complete
2312 * sequence (add the whole buffer); when we're adding a suffix
2313 * of the buffer (<sqfp->bpos> is skipped ahead already);
2314 * or when we're adding a prefix of the buffer (terminating a subseq
2315 * or window load).
2316 *
2317 * The caller must know that there are at least <nres> residues in
2318 * this buffer, and that all the characters are valid in the
2319 * format and alphabet, via a previous call to <seebuf()>.
2320 *
2321 * The caller also must have already allocated <sq> to hold at least
2322 * <nres> more residues.
2323 *
2324 * On input:
2325 * sqfp->buf[] contains an fread() buffer
2326 * sqfp->bpos is set to where we're going to start parsing residues
2327 * sqfp->nc is the length of <buf>
2328 *
2329 * On return:
2330 * sqfp->buf[] still contains the same buffer (no new freads here)
2331 * sqfp->bpos is set after the last residue we parsed
2332 * sq->seq/dsq now holds <nres> new residues
2333 * sq->n is incremented by <nres>
2334 */
2335 static void
2336 addbuf(ESL_SQFILE *sqfp, ESL_SQ *sq, int64_t nres)
2337 {
2338 ESL_DSQ x;
2339 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2340
2341 if (sq->dsq != NULL)
2342 {
2343 while (nres) {
2344 x = sq->abc->inmap[(int) ascii->buf[ascii->bpos++]];
2345 if (x <= 127) { nres--; sq->dsq[++sq->n] = x; }
2346 } /* we skipped IGNORED, EOL. EOD, ILLEGAL don't occur; seebuf() already checked */
2347 }
2348 else
2349 {
2350 while (nres) {
2351 x = sqfp->inmap[(int) ascii->buf[ascii->bpos++]];
2352 if (x <= 127) { nres--; sq->seq[sq->n++] = x; }
2353 }
2354 }
2355 }
2356
2357 /* skipbuf()
2358 * Like addbuf(), but we skip <nskip> residues instead of
2359 * reading them.
2360 */
2361 static void
2362 skipbuf(ESL_SQFILE *sqfp, int64_t nskip)
2363 {
2364 ESL_DSQ x;
2365 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2366
2367 while (nskip) {
2368 x = sqfp->inmap[(int) ascii->buf[ascii->bpos++]];
2369 if (x <= 127) nskip--;/* skip IGNORED, EOL. */
2370 }
2371 }
2372
2373
2374 /* skip_whitespace()
2375 * Like skipbuf(), but instead of skipping a fixed number of
2376 * residues, skip forward until one of three conditions is met:
2377 *
2378 * (1) end of the sequence record (a character indicating
2379 * the beginning of a new sequence); set ascii->bpos
2380 * to the beginning of the new record, and return eslEOD;
2381 * (2) a non-whitespace character in the current sequence is
2382 * reached that does not indicate the end of a sequence
2383 * record; set ascii->bpos to that character's position,
2384 * and return eslOK;
2385 * (3) end of file; return eslEOF.
2386 *
2387 */
2388 static int
2389 skip_whitespace(ESL_SQFILE *sqfp)
2390 {
2391 int status;
2392 int c;
2393 ESL_DSQ x;
2394 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2395
2396 if (ascii->nc == 0)
2397 return eslEOF;
2398
2399 /* if at end of buffer, reload it */
2400 if (ascii->bpos == ascii->nc)
2401 if ((status = loadbuf(sqfp)) == eslEOF)
2402 return eslEOF;
2403
2404 c = (int) ascii->buf[ascii->bpos];
2405 x = sqfp->inmap[c];
2406
2407 while ( isspace(c) ) {
2408
2409 ascii->bpos++;
2410
2411 /* if at end of buffer, reload it */
2412 if (ascii->bpos == ascii->nc)
2413 if ((status = loadbuf(sqfp)) == eslEOF)
2414 return eslEOF;
2415
2416 c = (int) ascii->buf[ascii->bpos];
2417 x = sqfp->inmap[c];
2418 }
2419 if (x == eslDSQ_EOD)
2420 return eslEOD;
2421
2422 return eslOK;
2423 }
2424
2425
2426
2427 /* read_nres()
2428 * Read the next <nres> residues from <sqfp> after skipping <nskip> residues, then stop.
2429 *
2430 * Returns <eslOK> and <0 < *ret_actual_nres <= nres> if it succeeded, and
2431 * there's more residues in the current seq record.
2432 * Returns <eslEOD> and <*ret_actual_nres == 0> if no more residues are
2433 * seen in the sequence record.
2434 *
2435 * Even on <eslEOD>, the <dsq/seq> is appropriately terminated here,
2436 * and <sq->n> is left the way it was (no new residues added - but there
2437 * may have been saved context C from a previous window).
2438 *
2439 * Returns <eslEFORMAT> on any parsing problem, and <ascii->errbuf> is set.
2440 *
2441 * On <eslOK>, sqfp->bpos is positioned on the next character past the last residue we store;
2442 * on <eslEOD>, sqfp->bpos is positioned for reading the next sequence.
2443 *
2444 * FetchSubseq() uses this with <nskip>, <nres>, and expects an
2445 * <eslOK> with <*opt_actual_nres = nres>. On <EOD>, or if fewer than
2446 * <nres> residues are obtained, the coords must've been screwed up,
2447 * because we didn't read the whole subseq we asked for.
2448 *
2449 * ReadWindow() on forward strand uses this with <nskip=0>, <nres=W>.
2450 * The last window might normally return <eslEOD> with
2451 * <*ret_actual_nres == 0>, and now <sqfp->bpos> is positioned at the
2452 * start of the next sequence on <EOD>, and at the next residue on
2453 * <OK>.
2454 *
2455 * ReadWindow() in reverse complement acts like a subseq fetch.
2456 *
2457 */
2458 static int
2459 read_nres(ESL_SQFILE *sqfp, ESL_SQ *sq, int64_t nskip, int64_t nres, int64_t *opt_actual_nres)
2460 {
2461 int64_t n;
2462 int64_t epos;
2463 int64_t actual_nres = 0;
2464 int status = eslOK;
2465
2466 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2467 status = seebuf(sqfp, nskip+nres, &n, &epos);
2468 while (status == eslOK && nskip - n > 0) {
2469 nskip -= n;
2470 if ((status = loadbuf(sqfp)) == eslEOF) break;
2471 status = seebuf(sqfp, nskip+nres, &n, &epos);
2472 }
2473
2474 if (status == eslEOF) {
2475 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Premature EOF before end of seq record");
2476 if (nskip > 0) ESL_EXCEPTION(eslECORRUPT, "premature EOD while trying to skip residues");
2477 n = 0;
2478 } else if (status == eslEOD) {
2479 if (n < nskip) ESL_EXCEPTION(eslECORRUPT, "premature EOD while trying to skip residues");
2480 } else if (status != eslOK)
2481 return status;
2482
2483 skipbuf(sqfp, nskip);
2484 n -= nskip;
2485
2486 while (status == eslOK && nres - n > 0)
2487 {
2488 addbuf(sqfp, sq, n);
2489 actual_nres += n;
2490 nres -= n;
2491 if ((status = loadbuf(sqfp)) == eslEOF) break;
2492 status = seebuf(sqfp, nres, &n, &epos);
2493 }
2494
2495
2496 if (status == eslEOF) {
2497 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Premature EOF before end of seq record");
2498 n = 0;
2499 } else if (status == eslEFORMAT) {
2500 return status;
2501 }
2502
2503 n = ESL_MIN(nres, n);
2504 addbuf(sqfp, sq, n); /* bpos now at last residue + 1 if OK/EOD, 0 if EOF */
2505 actual_nres += n;
2506
2507 if (sq->dsq != NULL) sq->dsq[sq->n+1] = eslDSQ_SENTINEL;
2508 else sq->seq[sq->n] = '\0';
2509
2510 if (status == eslEOD) {
2511 ascii->bpos = epos;
2512 }
2513
2514 if (opt_actual_nres != NULL) *opt_actual_nres = actual_nres;
2515 return (actual_nres == 0 ? eslEOD : eslOK);
2516 }
2517 /*--------------- end, buffer-based parsers --------------------*/
2518
2519
2520 /*****************************************************************
2521 *# 7. Internal routines for EMBL format (including UniProt, TrEMBL)
2522 *****************************************************************/
2523 /* EMBL and UniProt protein sequence database format.
2524 * See: http://us.expasy.org/sprot/userman.html
2525 * and: http://www.ebi.ac.uk/embl/Documentation/User_manual/usrman.html#3
2526 * We use the same parser for both formats, so we have to be
2527 * careful to only parse the conserved intersection of these two
2528 * very similar formats.
2529 */
2530 static void
2531 config_embl(ESL_SQFILE *sqfp)
2532 {
2533 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2534
2535 ascii->is_linebased = TRUE;
2536 ascii->eof_is_ok = FALSE;/* records end with // */
2537 ascii->parse_header = &header_embl;
2538 ascii->skip_header = &skip_embl;
2539 ascii->parse_end = &end_embl;
2540 }
2541
2542 static void
2543 inmap_embl(ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap)
2544 {
2545 int x;
2546
2547 if (abc_inmap != NULL) {
2548 for (x = 0; x < 128; x++) sqfp->inmap[x] = abc_inmap[x];
2549 sqfp->inmap['-'] = eslDSQ_ILLEGAL; // don't let the abc_inmap map the gap char; this is an ungapped file format
2550 } else {
2551 for (x = 0; x < 128; x++) sqfp->inmap[x] = eslDSQ_ILLEGAL;
2552 for (x = 'A'; x <= 'Z'; x++) sqfp->inmap[x] = x;
2553 for (x = 'a'; x <= 'z'; x++) sqfp->inmap[x] = x;
2554 }
2555 for (x = '0'; x <= '9'; x++)
2556 sqfp->inmap[x] = eslDSQ_IGNORED; /* EMBL DNA sequence format puts coordinates after each line */
2557 sqfp->inmap['*'] = '*'; /* accept * as a nonresidue/stop codon character */
2558 sqfp->inmap[' '] = eslDSQ_IGNORED;
2559 sqfp->inmap['\t'] = eslDSQ_IGNORED;
2560 sqfp->inmap['\n'] = eslDSQ_IGNORED;
2561 sqfp->inmap['\r'] = eslDSQ_IGNORED; /* DOS eol compatibility */
2562 sqfp->inmap['/'] = eslDSQ_EOD;
2563 }
2564
2565 /* header_embl()
2566 *
2567 * See: http://us.expasy.org/sprot/userman.html
2568 * And: http://www.ebi.ac.uk/embl/Documentation/User_manual/usrman.html#3
2569 * Our parser must work on the highest common denominator of EMBL DNA
2570 * and UniProt protein sequence files.
2571 *
2572 * sqfp->buf is the first (ID) line of the entry, or a blank line before
2573 * it (in which case we'll scan forwards skipping blank lines to find
2574 * the ID line).
2575 *
2576 * On success, returns <eslOK> and:
2577 * sq->name contains sequence name (and may have been reallocated, changing sq->nalloc)
2578 * sq->acc contains seq accession (and may have been reallocated, changing sq->aalloc)
2579 * sq->desc contains description line (and may have been reallocated, changing sq->dalloc)
2580 * sq->roff has been set to the record offset
2581 * sq->doff has been set to the data offset (start of sequence line)
2582 * sqfp->buf is the first seq line.
2583 *
2584 * If no more seqs are found in the file, returns <eslEOF>.
2585 * On parse failure, returns <eslEFORMAT>, leaves as mesg in ascii->errbuf.
2586 *
2587 * May also throw <eslEMEM> on allocation errors.
2588 */
2589 static int
2590 header_embl(ESL_SQFILE *sqfp, ESL_SQ *sq)
2591 {
2592 char *s;
2593 char *tok;
2594 int status;
2595
2596 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2597
2598 /* Find first line:
2599 * "Each entry must begin with an identification line (ID)..."
2600 * "The two-character line-type code that begins each line is always
2601 * followed by three blanks..."
2602 */
2603 if (ascii->nc == 0) return eslEOF;
2604 while (esl_str_IsBlank(ascii->buf)) {
2605 if ((status = loadbuf(sqfp)) == eslEOF) return eslEOF; /* normal */
2606 else if (status != eslOK) return status; /* abnormal */
2607 }
2608
2609 /* ID line is defined as:
2610 * ID ENTRY_NAME DATA_CLASS; MOLECULE_TYPE; SEQUENCE_LENGTH.
2611 * We're only after the ENTRY_NAME.
2612 * Examples:
2613 * ID SNRPA_DROME STANDARD; PRT; 216 AA.
2614 * ID SNRPA_DROME Reviewed; 216 AA.
2615 * ID X06347; SV 1; linear; mRNA; STD; HUM; 1209 BP.
2616 */
2617 if (strncmp(ascii->buf, "ID ", 5) != 0) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to find ID line", ascii->linenumber);
2618
2619 s = ascii->buf+5;
2620 if ((status = esl_strtok(&s, " ;", &tok)) != eslOK)
2621 ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to parse name on ID line", ascii->linenumber);
2622 if ((status = esl_sq_SetName(sq, tok)) != eslOK) return status;
2623 sq->roff = ascii->boff;/* record the offset of the ID line */
2624
2625 /* Look for SQ line; parsing optional info as we go.
2626 */
2627 do {
2628 if ((status = loadbuf(sqfp)) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to find SQ line", ascii->linenumber);
2629
2630 /* "The format of the AC line is:
2631 * AC AC_number_1;[ AC_number_2;]...[ AC_number_N;]
2632 * Researchers who wish to cite entries in their publications
2633 * should always cite the first accession number. This is
2634 * commonly referred to as the 'primary accession
2635 * number'."
2636 *
2637 * Examples:
2638 * AC P43332; Q9W4D7;
2639 * AC X06347;
2640 *
2641 * Note that Easel only stores primary accessions.
2642 * Because there can be more than one accession line, we check to
2643 * see if the accession is already set before storing a line.
2644 */
2645 if (strncmp(ascii->buf, "AC ", 5) == 0 && sq->acc[0] == '\0')
2646 {
2647 s = ascii->buf+5;
2648 if ((status = esl_strtok(&s, ";", &tok)) != eslOK)
2649 ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to parse accession on AC line", ascii->linenumber);
2650 if ((status = esl_sq_SetAccession(sq, tok)) != eslOK) return status;
2651 }
2652
2653 /* "The format of the DE line is:
2654 * DE Description.
2655 * ...In cases where more than one DE line is required, the text is
2656 * only divided between words and only the last DE line is
2657 * terminated by a period."
2658 *
2659 * Examples:
2660 * DE U1 small nuclear ribonucleoprotein A (U1 snRNP protein A) (U1-A) (Sex
2661 * DE determination protein snf).
2662 *
2663 * DE Human mRNA for U1 small nuclear RNP-specific A protein
2664 *
2665 * DE RecName: Full=U1 small nuclear ribonucleoprotein A;
2666 * DE Short=U1 snRNP protein A;
2667 * DE Short=U1-A;
2668 * DE AltName: Full=Sex determination protein snf;
2669 *
2670 * We'll make no attempt to parse the structured UniProt description header,
2671 * for the moment.
2672 */
2673 if (strncmp(ascii->buf, "DE ", 5) == 0)
2674 {
2675 s = ascii->buf+5;
2676 esl_strchop(s, ascii->nc-5);
2677 if ((status = esl_sq_AppendDesc(sq, s)) != eslOK)
2678 ESL_FAIL(status, ascii->errbuf, "Line %" PRId64 ": failed to parse description on DE line", ascii->linenumber);
2679 }
2680
2681 /* UniProt: "The format of the SQ line is:
2682 * SQ SEQUENCE XXXX AA; XXXXX MW; XXXXXXXXXXXXXXXX CRC64;"
2683 * EMBL: "The SQ (SeQuence header) line marks the beginning of
2684 * the sequence data and Gives a summary of its content.
2685 * An example is:
2686 * SQ Sequence 1859 BP; 609 A; 314 C; 355 G; 581 T; 0 other;"
2687 *
2688 * We don't parse this line; we just look for it as the last line
2689 * before the sequence starts.
2690 */
2691 } while (strncmp(ascii->buf, "SQ ", 5) != 0);
2692
2693 if (loadbuf(sqfp) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find any sequence");
2694 sq->hoff = ascii->boff - 1;
2695 sq->doff = ascii->boff;
2696 return eslOK;
2697 }
2698
2699 /* skip_embl()
2700 *
2701 * Skip past the EMBL header and position to start of the sequence line.
2702 *
2703 * On success, returns <eslOK> and:
2704 * sq->roff has been set to the record offset
2705 * sq->doff has been set to the data offset (start of sequence line)
2706 * sqfp->buf is the first seq line.
2707 *
2708 * If no more seqs are found in the file, returns <eslEOF>.
2709 * On parse failure, returns <eslEFORMAT>, leaves as mesg in ascii->errbuf.
2710 *
2711 * May also throw <eslEMEM> on allocation errors.
2712 */
2713 static int
2714 skip_embl(ESL_SQFILE *sqfp, ESL_SQ *sq)
2715 {
2716 int status;
2717
2718 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2719
2720 /* Find first line:
2721 * "Each entry must begin with an identification line (ID)..."
2722 * "The two-character line-type code that begins each line is always
2723 * followed by three blanks..."
2724 */
2725 if (ascii->nc == 0) return eslEOF;
2726 while (esl_str_IsBlank(ascii->buf)) {
2727 if ((status = loadbuf(sqfp)) == eslEOF) return eslEOF; /* normal */
2728 else if (status != eslOK) return status; /* abnormal */
2729 }
2730
2731 /* ID line */
2732 if (strncmp(ascii->buf, "ID ", 5) != 0) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to find ID line", ascii->linenumber);
2733
2734 sq->roff = ascii->boff;/* record the offset of the ID line */
2735
2736 /* zero out the name, accession and description */
2737 sq->name[0] = '\0';
2738 sq->acc[0] = '\0';
2739 sq->desc[0] = '\0';
2740
2741 /* Look for SQ line; parsing optional info as we go. */
2742 do {
2743 if ((status = loadbuf(sqfp)) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to find SQ line", ascii->linenumber);
2744 } while (strncmp(ascii->buf, "SQ ", 5) != 0);
2745
2746 if (loadbuf(sqfp) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find any sequence");
2747 sq->hoff = ascii->boff - 1;
2748 sq->doff = ascii->boff;
2749 return eslOK;
2750 }
2751
2752 static int
2753 end_embl(ESL_SQFILE *sqfp, ESL_SQ *sq)
2754 {
2755 int status;
2756
2757 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2758
2759 if (strncmp(ascii->buf, "//", 2) != 0) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": did not find // terminator at end of seq record", ascii->linenumber);
2760 sq->eoff = ascii->boff + ascii->nc - 1;
2761 status = loadbuf(sqfp);
2762 if (status == eslEOF) return eslOK; /* ok, actually. */
2763 else if (status == eslOK) return eslOK;
2764 else return status;
2765 }
2766
2767 /*---------------------- EMBL format ---------------------------------*/
2768
2769
2770
2771 /*****************************************************************
2772 *# 8. Internal routines for GenBank format
2773 *****************************************************************/
2774 /* NCBI GenBank sequence database format.
2775 * See GenBank release notes; for example,
2776 * ftp://ftp.ncbi.nih.gov/genbank/gbrel.txt
2777 */
2778
2779 static void
2780 config_genbank(ESL_SQFILE *sqfp)
2781 {
2782 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2783
2784 ascii->is_linebased = TRUE;
2785 ascii->eof_is_ok = FALSE;/* records end with // */
2786 ascii->parse_header = &header_genbank;
2787 ascii->skip_header = &skip_genbank;
2788 ascii->parse_end = &end_genbank;
2789 }
2790
2791 static void
2792 inmap_genbank(ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap)
2793 {
2794 int x;
2795
2796 if (abc_inmap != NULL) {
2797 for (x = 0; x < 128; x++) sqfp->inmap[x] = abc_inmap[x];
2798 sqfp->inmap['-'] = eslDSQ_ILLEGAL; // don't let the abc_inmap map the gap char; this is an ungapped file format
2799 } else {
2800 for (x = 0; x < 128; x++) sqfp->inmap[x] = eslDSQ_ILLEGAL;
2801 for (x = 'A'; x <= 'Z'; x++) sqfp->inmap[x] = x;
2802 for (x = 'a'; x <= 'z'; x++) sqfp->inmap[x] = x;
2803 }
2804 for (x = '0'; x <= '9'; x++)
2805 sqfp->inmap[x] = eslDSQ_IGNORED;
2806 sqfp->inmap['*'] = '*'; /* accept * as a nonresidue/stop codon character */
2807 sqfp->inmap[' '] = eslDSQ_IGNORED;
2808 sqfp->inmap['\t'] = eslDSQ_IGNORED;
2809 sqfp->inmap['\n'] = eslDSQ_IGNORED;
2810 sqfp->inmap['\r'] = eslDSQ_IGNORED;/* DOS eol compatibility */
2811 sqfp->inmap['/'] = eslDSQ_EOD;
2812 }
2813
2814 /* header_genbank()
2815 *
2816 * sqfp->buf is the first (LOCUS) line of the entry, or a line before
2817 * it (in which case we'll scan forwards to find the LOCUS line - even
2818 * skipping non-blank lines, because there are sometimes headers at
2819 * the start of GenBank files).
2820 *
2821 * On success, returns <eslOK> and:
2822 * sq->name contains sequence name (and may have been reallocated, changing sq->nalloc)
2823 * sq->acc contains seq accession (and may have been reallocated, changing sq->aalloc)
2824 * sq->desc contains description line (and may have been reallocated, changing sq->dalloc)
2825 * sq->roff has been set to the record offset
2826 * sq->doff has been set to the data offset (start of sequence line)
2827 * sqfp->buf is the first seq line.
2828 *
2829 * If no more seqs are found in the file, returns <eslEOF>.
2830 * On parse failure, returns <eslEFORMAT>, leaves as mesg in ascii->errbuf.
2831 *
2832 * May also throw <eslEMEM> on allocation errors.
2833 */
2834 static int
2835 header_genbank(ESL_SQFILE *sqfp, ESL_SQ *sq)
2836 {
2837 char *s;
2838 char *tok;
2839 int status;
2840
2841 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2842
2843 /* Find LOCUS line, allowing for ignoration of a file header. */
2844 if (ascii->nc == 0) return eslEOF;
2845 while (strncmp(ascii->buf, "LOCUS ", 8) != 0) {
2846 if ((status = loadbuf(sqfp)) == eslEOF) return eslEOF; /* normal */
2847 else if (status != eslOK) return status; /* abnormal */
2848 }
2849
2850 s = ascii->buf+12;
2851 if ((status = esl_strtok(&s, " ", &tok)) != eslOK)
2852 ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to parse name on LOCUS line", ascii->linenumber);
2853 if ((status = esl_sq_SetName(sq, tok)) != eslOK) return status;
2854 sq->roff = ascii->boff;/* record the disk offset to the LOCUS line */
2855
2856 /* Look for ORIGIN line, parsing optional info as we go. */
2857 do {
2858 if ((status = loadbuf(sqfp)) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find ORIGIN line");
2859
2860 /* Optional VERSION line is parsed as "accession". */
2861 if (strncmp(ascii->buf, "VERSION ", 10) == 0)
2862 {
2863 s = ascii->buf+12;
2864 if ((status = esl_strtok(&s, " \t\n", &tok)) != eslOK)
2865 ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": failed to parse VERSION line", ascii->linenumber);
2866 if ((status = esl_sq_SetAccession(sq, tok)) != eslOK) return status;
2867 }
2868
2869 /* Optional DEFINITION Line is parsed as "description". */
2870 if (strncmp(ascii->buf, "DEFINITION ", 11) == 0)
2871 {
2872 s = ascii->buf+12;
2873 esl_strchop(s, ascii->nc-12);
2874 if ((status = esl_sq_AppendDesc(sq, s)) != eslOK)
2875 ESL_FAIL(status, ascii->errbuf, "Line %" PRId64 ": failed to parse desc on DEFINITION line", ascii->linenumber);
2876 }
2877 } while (strncmp(ascii->buf, "ORIGIN", 6) != 0);
2878
2879 if (loadbuf(sqfp) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find any sequence");
2880 sq->hoff = ascii->boff - 1;
2881 sq->doff = ascii->boff;
2882 return eslOK;
2883 }
2884
2885 /* skip_genbank()
2886 *
2887 * Skip past the GenBank header and position to start of the sequence line.
2888 *
2889 * On success, returns <eslOK> and:
2890 * sq->roff has been set to the record offset
2891 * sq->doff has been set to the data offset (start of sequence line)
2892 * sqfp->buf is the first seq line.
2893 *
2894 * If no more seqs are found in the file, returns <eslEOF>.
2895 * On parse failure, returns <eslEFORMAT>, leaves as mesg in ascii->errbuf.
2896 *
2897 * May also throw <eslEMEM> on allocation errors.
2898 */
2899 static int
2900 skip_genbank(ESL_SQFILE *sqfp, ESL_SQ *sq)
2901 {
2902 int status;
2903
2904 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2905
2906 /* Find LOCUS line, allowing for ignoration of a file header. */
2907 if (ascii->nc == 0) return eslEOF;
2908 while (strncmp(ascii->buf, "LOCUS ", 8) != 0) {
2909 if ((status = loadbuf(sqfp)) == eslEOF) return eslEOF; /* normal */
2910 else if (status != eslOK) return status; /* abnormal */
2911 }
2912
2913 sq->roff = ascii->boff;/* record the disk offset to the LOCUS line */
2914
2915 /* zero out the name, accession and description */
2916 sq->name[0] = '\0';
2917 sq->acc[0] = '\0';
2918 sq->desc[0] = '\0';
2919
2920 /* Look for ORIGIN line, parsing optional info as we go. */
2921 do {
2922 if ((status = loadbuf(sqfp)) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find ORIGIN line");
2923 } while (strncmp(ascii->buf, "ORIGIN", 6) != 0);
2924
2925 if (loadbuf(sqfp) != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Failed to find any sequence");
2926 sq->hoff = ascii->boff - 1;
2927 sq->doff = ascii->boff;
2928 return eslOK;
2929 }
2930
2931 static int
2932 end_genbank(ESL_SQFILE *sqfp, ESL_SQ *sq)
2933 {
2934 int status;
2935
2936 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2937
2938 if (strncmp(ascii->buf, "//", 2) != 0) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": did not find // terminator at end of seq record", ascii->linenumber);
2939 sq->eoff = ascii->boff + ascii->nc - 1;
2940 status = loadbuf(sqfp);
2941 if (status == eslEOF) return eslOK; /* ok, actually; we'll detect EOF on next sq read */
2942 else if (status == eslOK) return eslOK;
2943 else return status;
2944 }
2945 /*----------------- end GenBank format -------------------------------*/
2946
2947
2948
2949 /*****************************************************************
2950 *# 9. Internal routines for FASTA format
2951 *****************************************************************/
2952
2953 static void
2954 config_fasta(ESL_SQFILE *sqfp)
2955 {
2956 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
2957
2958 ascii->is_linebased = FALSE;
2959 ascii->eof_is_ok = TRUE;
2960 ascii->parse_header = &header_fasta;
2961 ascii->skip_header = &skip_fasta;
2962 ascii->parse_end = &end_fasta;
2963 }
2964
2965 static void
2966 inmap_fasta(ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap)
2967 {
2968 int x;
2969
2970 if (abc_inmap != NULL) {
2971 for (x = 0; x < 128; x++) sqfp->inmap[x] = abc_inmap[x];
2972 sqfp->inmap['-'] = eslDSQ_ILLEGAL; // don't let the abc_inmap map the gap char; this is an ungapped file format
2973 } else {
2974 for (x = 0; x < 128; x++) sqfp->inmap[x] = eslDSQ_ILLEGAL;
2975 for (x = 'A'; x <= 'Z'; x++) sqfp->inmap[x] = x;
2976 for (x = 'a'; x <= 'z'; x++) sqfp->inmap[x] = x;
2977 }
2978 sqfp->inmap['*'] = '*'; /* accept * as a nonresidue/stop codon character */
2979 sqfp->inmap[' '] = eslDSQ_IGNORED;
2980 sqfp->inmap['\t'] = eslDSQ_IGNORED;
2981 sqfp->inmap['\r'] = eslDSQ_IGNORED;/* DOS eol compatibility */
2982 sqfp->inmap['\n'] = eslDSQ_EOL;
2983 sqfp->inmap['>'] = eslDSQ_EOD;
2984 /* \n is special - fasta reader detects it as an eol */
2985 }
2986
2987
2988 /* header_fasta()
2989 *
2990 * sqfp->buf[sqfp->bpos] is sitting at the start of a FASTA record, or
2991 * at a space before it (in which case we'll advance, skipping whitespace,
2992 * until a > is reached).
2993 * Parse the header line, storing name and description in <sq>.
2994 *
2995 * On success, returns <eslOK> and:
2996 * sq->name contains sequence name (and may have been reallocated, changing sq->nalloc)
2997 * sq->desc contains description line (and may have been reallocated, changing sq->dalloc)
2998 * sq->roff has been set to the record offset
2999 * sq->doff has been set to the data offset (start of sequence line)
3000 * sqfp->buf[sqfp->bpos] is sitting at the start of the seq line.
3001 * sqfp->currpl,curbpl set to 0, to start bookkeeping data line lengths
3002 *
3003 * If no more seqs are found in the file, returns <eslEOF>.
3004 * On parse failure, return <eslEFORMAT>, leaves as mesg in ascii->errbuf.
3005 *
3006 * May also throw <eslEMEM> on allocation errors.
3007 */
3008 static int
3009 header_fasta(ESL_SQFILE *sqfp, ESL_SQ *sq)
3010 {
3011 char c;
3012 int status = eslOK;
3013 void *tmp;
3014 int pos;
3015
3016 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3017
3018 /* make sure there are characters in the buffer */
3019 if (ascii->nc == ascii->bpos && (status = loadbuf(sqfp)) != eslOK) return status;
3020
3021 c = ascii->buf[ascii->bpos];
3022 while (status == eslOK && isspace(c)) status = nextchar(sqfp, &c); /* skip space (including \n) */
3023
3024 if (status == eslEOF) return eslEOF;
3025
3026 if (status == eslOK && c == '>') { /* accept the > */
3027 sq->roff = ascii->boff + ascii->bpos; /* store SSI record offset */
3028 status = nextchar(sqfp, &c);
3029 } else if (c != '>') ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": unexpected char %c; expected FASTA to start with >", ascii->linenumber, c);
3030
3031 while (status == eslOK && (c == '\t' || c == ' ')) status = nextchar(sqfp, &c); /* skip space */
3032
3033 /* Store the name (space delimited) */
3034 pos = 0;
3035 while (status == eslOK && ! isspace(c))
3036 {
3037 sq->name[pos++] = c;
3038 if (pos == sq->nalloc-1) { ESL_RALLOC(sq->name, tmp, sq->nalloc*2); sq->nalloc*=2; }
3039 status = nextchar(sqfp, &c);
3040 }
3041 if (pos == 0) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": no FASTA name found", ascii->linenumber);
3042 sq->name[pos] = '\0';
3043
3044 while (status == eslOK && (c == '\t' || c == ' ')) status = nextchar(sqfp, &c); /* skip space */
3045
3046 /* Store the description (end-of-line delimited) */
3047 /* Patched to deal with NCBI NR desclines: delimit by ctrl-A (0x01) too. [SRE:H1/82] */
3048 pos = 0;
3049 while (status == eslOK && c != '\n' && c != '\r' && c != 1)
3050 {
3051 sq->desc[pos++] = c;
3052 if (pos == sq->dalloc-1) { ESL_RALLOC(sq->desc, tmp, sq->dalloc*2); sq->dalloc*= 2; }
3053 status = nextchar(sqfp, &c);
3054 }
3055 sq->desc[pos] = '\0';
3056
3057 /* Because of the NCBI NR patch, c might be0x01 ctrl-A now; skip to eol.
3058 * (TODO: I'm worried about the efficiency of this nextchar() stuff. Revisit.)
3059 */
3060 while (status == eslOK && c != '\n' && c != '\r')
3061 status = nextchar(sqfp, &c);
3062 sq->hoff = ascii->boff + ascii->bpos;
3063
3064 while (status == eslOK && (c == '\n' || c == '\r')) status = nextchar(sqfp, &c); /* skip past eol (DOS \r\n, MAC \r, UNIX \n */
3065 if (status != eslOK && status != eslEOF) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected failure in parsing FASTA name/description line");
3066 /* Edge case: if the last sequence in the file is L=0, no residues, we are EOF now, not OK; but we'll return OK because we parsed the header line */
3067
3068 sq->doff = ascii->boff + ascii->bpos;
3069 ascii->prvrpl = ascii->prvbpl = -1;
3070 ascii->currpl = ascii->curbpl = 0;
3071 ascii->linenumber++;
3072 return eslOK;
3073
3074 ERROR:
3075 return status;/* eslEMEM, from failed realloc */
3076 }
3077
3078 /* skip_fasta()
3079 *
3080 * Skip past the fasta header and position to start of the sequence line.
3081 *
3082 * On success, returns <eslOK> and:
3083 * sq->roff has been set to the record offset
3084 * sq->doff has been set to the data offset (start of sequence line)
3085 * sqfp->buf[sqfp->bpos] is sitting at the start of the seq line.
3086 * sqfp->currpl,curbpl set to 0, to start bookkeeping data line lengths
3087 *
3088 * If no more seqs are found in the file, returns <eslEOF>.
3089 * On parse failure, return <eslEFORMAT>, leaves as mesg in ascii->errbuf.
3090 *
3091 * May also throw <eslEMEM> on allocation errors.
3092 */
3093 static int
3094 skip_fasta(ESL_SQFILE *sqfp, ESL_SQ *sq)
3095 {
3096 char c;
3097 int status = eslOK;
3098
3099 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3100
3101 c = ascii->buf[ascii->bpos];
3102 while (status == eslOK && isspace(c)) status = nextchar(sqfp, &c); /* skip space (including \n) */
3103
3104 if (status == eslEOF) return eslEOF;
3105 if (status != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected parsing error %d", status);
3106 if (c != '>') ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": unexpected char %c; expecting '>'", ascii->linenumber, c);
3107
3108 sq->roff = ascii->boff + ascii->bpos; /* store SSI record offset */
3109
3110 /* zero out the name, accession and description */
3111 sq->name[0] = '\0';
3112 sq->acc[0] = '\0';
3113 sq->desc[0] = '\0';
3114
3115 status = nextchar(sqfp, &c);
3116
3117 /* skip to end of line */
3118 while (status == eslOK && c != '\n' && c != '\r') status = nextchar(sqfp, &c);
3119 sq->doff = ascii->boff + ascii->bpos;
3120
3121 /* skip past end of line */
3122 while (status == eslOK && (c == '\n' || c == '\r')) status = nextchar(sqfp, &c);
3123
3124 if (status != eslOK) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Premature EOF in parsing FASTA name/description line");
3125 sq->doff = ascii->boff + ascii->bpos;
3126
3127 ascii->linenumber++;
3128 return eslOK;
3129 }
3130
3131
3132 static int
3133 end_fasta(ESL_SQFILE *sqfp, ESL_SQ *sq)
3134 {
3135 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3136
3137 if (ascii->bpos < ascii->nc) {
3138 if (ascii->buf[ascii->bpos] != '>') ESL_FAIL(eslEFORMAT, ascii->errbuf, "Whoops, FASTA reader is corrupted");
3139 sq->eoff = ascii->boff + ascii->bpos - 1; /* this puts eoff at the last \n */
3140 } /* else, EOF, and we don't have to do anything. */
3141 return eslOK;
3142 }
3143
3144
3145 /* Function: esl_sqascii_WriteFasta()
3146 * Synopsis: Write a sequence in FASTA foramt
3147 *
3148 * Purpose: Write sequence <sq> in FASTA format to the open stream <fp>.
3149 *
3150 * If <save_offsets> is TRUE, then store record, data, and end
3151 * offsets in <sq>; this ability is used by unit tests.
3152 *
3153 * Returns: <eslOK> on success.
3154 *
3155 * Throws: <eslEMEM> on allocation failure.
3156 * <eslEWRITE> on system write error.
3157 */
3158 int
3159 esl_sqascii_WriteFasta(FILE *fp, ESL_SQ *sq, int save_offsets)
3160 {
3161 char buf[61];
3162 int64_t pos;
3163
3164 if (save_offsets) sq->roff = ftello(fp);
3165 if (fprintf(fp, ">%s", sq->name) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "fasta seq write failed");
3166 if (sq->acc[0] != 0 && fprintf(fp, " %s", sq->acc) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "fasta seq write failed");
3167 if (sq->desc[0] != 0 && fprintf(fp, " %s", sq->desc) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "fasta seq write failed");
3168 if (save_offsets) sq->hoff = ftello(fp);
3169 if (fputc('\n', fp) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "fasta seq write failed");
3170
3171 buf[60] = '\0';
3172 if (save_offsets) sq->doff = ftello(fp);
3173 for (pos = 0; pos < sq->n; pos += 60)
3174 {
3175 if (sq->dsq != NULL) esl_abc_TextizeN(sq->abc, sq->dsq+pos+1, 60, buf);
3176 else strncpy(buf, sq->seq+pos, 60);
3177 if (fprintf(fp, "%s\n", buf) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "fasta seq write failed");
3178 }
3179 if (save_offsets) sq->eoff = ftello(fp) - 1;
3180 return eslOK;
3181 }
3182 /*------------------- end of FASTA i/o ---------------------------*/
3183
3184 /*****************************************************************
3185 *# 10. Internal routines for daemon format
3186 *****************************************************************/
3187
3188 /* Special case FASTA format where each sequence is terminated with "//".
3189 *
3190 * The use case is where the sequences are being read from a pipe and a
3191 * way is needed to signal the end of the sequence so it can be processed.
3192 * The next sequence might not be in the pipe, so the usual '>' is not
3193 * present to signal the end of the sequence. Also, an EOF is not
3194 * an option, since the daemon might run continuously.
3195 */
3196
3197 static void
3198 config_daemon(ESL_SQFILE *sqfp)
3199 {
3200 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3201
3202 ascii->is_linebased = FALSE;
3203 ascii->eof_is_ok = FALSE;
3204 ascii->parse_header = &header_fasta;
3205 ascii->skip_header = &skip_fasta;
3206 ascii->parse_end = &end_daemon;
3207 }
3208
3209 static void
3210 inmap_daemon(ESL_SQFILE *sqfp, const ESL_DSQ *abc_inmap)
3211 {
3212 int x;
3213
3214 if (abc_inmap != NULL) {
3215 for (x = 0; x < 128; x++) sqfp->inmap[x] = abc_inmap[x];
3216 sqfp->inmap['-'] = eslDSQ_ILLEGAL; // don't let the abc_inmap map the gap char; this is an ungapped file format
3217 } else {
3218 for (x = 0; x < 128; x++) sqfp->inmap[x] = eslDSQ_ILLEGAL;
3219 for (x = 'A'; x <= 'Z'; x++) sqfp->inmap[x] = x;
3220 for (x = 'a'; x <= 'z'; x++) sqfp->inmap[x] = x;
3221 }
3222 sqfp->inmap['*'] = '*'; /* accept * as a nonresidue/stop codon character */
3223 sqfp->inmap[' '] = eslDSQ_IGNORED;
3224 sqfp->inmap['\t'] = eslDSQ_IGNORED;
3225 sqfp->inmap['\r'] = eslDSQ_IGNORED;/* DOS eol compatibility */
3226 sqfp->inmap['\n'] = eslDSQ_EOL;
3227 sqfp->inmap['/'] = eslDSQ_EOD;
3228 /* \n is special - fasta reader detects it as an eol */
3229 }
3230
3231
3232 /* end_daemon()
3233 *
3234 * Special case FASTA format where each sequence is terminated with "//".
3235 *
3236 * The use case is were the sequences are being read from a pipe and a
3237 * way is needed to signal the end of the sequence so it can be processed.
3238 */
3239 static int
3240 end_daemon(ESL_SQFILE *sqfp, ESL_SQ *sq)
3241 {
3242 char c;
3243
3244 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3245
3246 if (ascii->nc < 3) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Whoops, daemon input stream is corrupted");
3247
3248 c = ascii->buf[ascii->bpos++];
3249 if (c != '/') ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": did not find // terminator at end of seq record", ascii->linenumber);
3250
3251 c = ascii->buf[ascii->bpos++];
3252 if (c != '/') ESL_FAIL(eslEFORMAT, ascii->errbuf, "Line %" PRId64 ": did not find // terminator at end of seq record", ascii->linenumber);
3253
3254 /* skip to end of line */
3255 while (c != '\n' && c != '\r' && ascii->bpos < ascii->nc) c = ascii->buf[ascii->bpos++];
3256
3257 /* skip past end of line */
3258 while ((c == '\n' || c == '\r') && ascii->bpos < ascii->nc) c = ascii->buf[ascii->bpos++];
3259
3260 return eslOK;
3261 }
3262
3263
3264 /* esl_sqascii_Parse()
3265 *
3266 * Parse a sequence already read into a buffer.
3267 */
3268 int
3269 esl_sqascii_Parse(char *buf, int size, ESL_SQ *sq, int format)
3270 {
3271 int status;
3272 int64_t epos;
3273 int64_t n;
3274
3275 ESL_SQFILE sqfp;
3276 ESL_SQASCII_DATA *ascii = &sqfp.data.ascii;
3277
3278 /* fill in a dummy esl_sqfile structure used to parse buf */
3279 ascii->fp = NULL;
3280 ascii->do_gzip = FALSE;
3281 ascii->do_stdin = FALSE;
3282 ascii->do_buffer = TRUE;
3283
3284 ascii->mem = buf;
3285 ascii->allocm = 0;
3286 ascii->mn = size;
3287 ascii->mpos = 0;
3288 ascii->moff = -1;
3289 ascii->is_recording = FALSE;
3290
3291 ascii->buf = NULL;
3292 ascii->boff = 0;
3293 ascii->balloc = 0;
3294 ascii->nc = 0;
3295 ascii->bpos = 0;
3296 ascii->L = 0;
3297 ascii->linenumber = 1;
3298
3299 ascii->afp = NULL;
3300 ascii->msa = NULL;
3301 ascii->idx = -1;
3302
3303 ascii->ssifile = NULL;
3304 ascii->rpl = -1;/* -1 = not set yet */
3305 ascii->bpl = -1;/* (ditto) */
3306 ascii->prvrpl = -1;/* (ditto) */
3307 ascii->prvbpl = -1;/* (ditto) */
3308 ascii->currpl = -1;
3309 ascii->curbpl = -1;
3310 ascii->ssi = NULL;
3311
3312 /* Configure the <sqfp>'s parser and inmaps for this format. */
3313 switch (format) {
3314 case eslSQFILE_EMBL:
3315 case eslSQFILE_UNIPROT:
3316 config_embl(&sqfp);
3317 inmap_embl(&sqfp, NULL);
3318 break;
3319 case eslSQFILE_GENBANK:
3320 case eslSQFILE_DDBJ:
3321 config_genbank(&sqfp);
3322 inmap_genbank(&sqfp, NULL);
3323 break;
3324 case eslSQFILE_FASTA:
3325 config_fasta(&sqfp);
3326 inmap_fasta(&sqfp, NULL);
3327 break;
3328 case eslSQFILE_DAEMON:
3329 config_daemon(&sqfp);
3330 inmap_daemon(&sqfp, NULL);
3331 break;
3332 default:
3333 return eslEFORMAT;
3334 }
3335
3336 /* Main case: read next seq from sqfp's stream */
3337 if ((status = ascii->parse_header(&sqfp, sq)) != eslOK) return status; /* EOF, EFORMAT */
3338
3339 do {
3340 if ((status = seebuf(&sqfp, -1, &n, &epos)) == eslEFORMAT) return status;
3341 if (esl_sq_GrowTo(sq, sq->n + n) != eslOK) return eslEMEM;
3342 addbuf(&sqfp, sq, n);
3343 ascii->L += n;
3344 sq->eoff = ascii->boff + epos - 1;
3345 if (status == eslEOD) break;
3346 } while ((status = loadbuf(&sqfp)) == eslOK);
3347
3348 if (status == eslEOF)
3349 {
3350 if (! ascii->eof_is_ok) ESL_FAIL(eslEFORMAT, ascii->errbuf, "Unexpected EOF; file truncated?");
3351 if ((status = ascii->parse_end(&sqfp, sq)) != eslOK) return status;
3352 }
3353 else if (status == eslEOD)
3354 {
3355 ascii->bpos = epos;
3356 if ((status = ascii->parse_end(&sqfp, sq)) != eslOK) return status;
3357 }
3358 else if (status != eslOK) return status;
3359
3360 if (sq->dsq != NULL) sq->dsq[sq->n+1] = eslDSQ_SENTINEL;
3361 else sq->seq[sq->n] = '\0';
3362 sq->start = 1;
3363 sq->end = sq->n;
3364 sq->C = 0;
3365 sq->W = sq->n;
3366 sq->L = sq->n;
3367
3368 if (ascii->balloc > 0) free(ascii->buf);
3369
3370 return eslOK;
3371 }
3372 /*-------------------- end of daemon ----------------------------*/
3373
3374 /*****************************************************************
3375 *# 11. Internal routines for HMMPGMD format
3376 *****************************************************************/
3377
3378 static int
3379 fileheader_hmmpgmd(ESL_SQFILE *sqfp)
3380 {
3381 ESL_SQASCII_DATA *ascii = &sqfp->data.ascii;
3382 char c;
3383 int status = eslOK;
3384
3385 /* We've just loaded first buffer, after an Open. First char should be the # of the hmmpgmd file,
3386 * but let's tolerate leading whitespace anyway
3387 */
3388 c = ascii->buf[ascii->bpos];
3389 while (status == eslOK && isspace(c)) status = nextchar(sqfp, &c); /* skip space (including \n, \r) */
3390 if (status == eslEOF) return eslEOF;
3391
3392 if (c != '#') ESL_FAIL(eslEFORMAT, ascii->errbuf, "hmmpgmd file expected to start with #");
3393
3394 /* skip first line; remainder of file is FASTA format */
3395 while (status == eslOK && (c != '\n' && c != '\r')) status = nextchar(sqfp, &c);
3396 if (status == eslEOF) return eslEOF;
3397
3398 /* next character read should be the '>' of the first FASTA record. We're properly positioned at "start of file". */
3399 return eslOK;
3400 }
3401 /*-------------------- end of HMMPGMD ---------------------------*/
3402
3403