Debian Codegraph @

easel/esl_sqio.c

raw symbols SCIP
1 /* Unaligned sequence file i/o.
2 *
3 * Contents:
4 * 1. An <ESL_SQFILE> object, text mode.
5 * 2. An <ESL_SQFILE> object, digital mode. [with <alphabet>]
6 * 3. Sequence reading.
7 * 4. Sequence writing.
8 * 5. Miscellaneous routines.
9 * 6. Sequence/subsequence fetching, random access [with <ssi>]
10 * 7. Sequence database caching.
11 * 8. Internal functions.
12 * 9. Benchmark driver.
13 * 10. Unit tests.
14 * 11. Test driver.
15 * 12. Examples.
16 *
17 * This module shares remote evolutionary homology with Don Gilbert's
18 * seminal, public domain ReadSeq package, though the last common
19 * ancestor was circa 1991 and no recognizable vestiges are likely to
20 * remain. Thanks Don!
21 *
22 */
23 #include <esl_config.h>
24
25 #include <stdlib.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <ctype.h>
29 #ifdef HAVE_STRINGS_H
30 #include <strings.h> /* POSIX strcasecmp() */
31 #endif
32
33 #include "easel.h"
34 #include "esl_alphabet.h"
35 #include "esl_msa.h"
36 #include "esl_msafile.h"
37 #include "esl_sqio.h"
38 #include "esl_sq.h"
39 #include "esl_sqio_ascii.h"
40 #include "esl_sqio_ncbi.h"
41
42 static int convert_sq_to_msa(ESL_SQ *sq, ESL_MSA **ret_msa);
43
44
45 /*****************************************************************
46 *# 1. An <ESL_SQFILE> object, in text mode.
47 *****************************************************************/
48
49 static int sqfile_open(const char *filename, int format, const char *env, ESL_SQFILE **ret_sqfp);
50
51 /* Function: esl_sqfile_Open()
52 * Synopsis: Open a sequence file <filename> for reading.
53 *
54 * Purpose: Open a sequence file <filename> for reading.
55 * The opened <ESL_SQFILE> is returned through <ret_sqfp>.
56 *
57 * The format of the file is asserted to be <format> (for
58 * example, <eslSQFILE_FASTA>). If <format> is
59 * <eslSQFILE_UNKNOWN> then the routine attempts to
60 * autodetect the file format.
61 *
62 * If <env> is non-NULL, it is the name of an environment
63 * variable that contains a colon-delimited list of
64 * directories in which we may find this <filename>.
65 * For example, if we had
66 * <setenv BLASTDB /nfs/db/blast-db:/nfs/db/genomes/>
67 * in the environment, a database search application
68 * could pass "BLASTDB" as <env>.
69 *
70 * Returns: <eslOK> on success, and <*ret_sqfp> points to a new
71 * open <ESL_SQFILE>. Caller deallocates this object with
72 * <esl_sqfile_Close()>.
73 *
74 * Returns <eslENOTFOUND> if <filename> can't be opened.
75 *
76 * Returns <eslEFORMAT> if the file is empty, or
77 * if autodetection is attempted and the format can't be
78 * determined.
79 *
80 * On any error condition, <*ret_sqfp> is returned NULL.
81 *
82 * Throws: <eslEMEM> on allocation failure.
83 */
84 int
85 esl_sqfile_Open(const char *filename, int format, const char *env, ESL_SQFILE **ret_sqfp)
86 {
87 return sqfile_open(filename, format, env, ret_sqfp);
88 }
89
90
91 /* Function: esl_sqfile_Close()
92 * Synopsis: Close a sequence file.
93 *
94 * Purpose: Closes an open <sqfp>.
95 *
96 * Returns: (void).
97 */
98 void
99 esl_sqfile_Close(ESL_SQFILE *sqfp)
100 {
101 if (sqfp == NULL) return;
102
103 if (sqfp->close != NULL) sqfp->close(sqfp);
104 if (sqfp->filename != NULL) free(sqfp->filename);
105 free(sqfp);
106
107 return;
108 }
109
110
111 /* sqfile_open():
112 * This is the routine that actually opens an ESL_SQFILE.
113 * esl_sqfile_Open() and esl_sqfile_OpenDigital() are
114 * small wrappers around it.
115 */
116 static int
117 sqfile_open(const char *filename, int format, const char *env, ESL_SQFILE **ret_sqfp)
118 {
119 ESL_SQFILE *sqfp = NULL;
120 int status; /* return status from an ESL call */
121 int n;
122
123 char *s1;
124 char *s2;
125 char *list = NULL;
126 char *path = NULL;
127
128 ESL_ALLOC(sqfp, sizeof(ESL_SQFILE));
129 *ret_sqfp = NULL;
130
131 sqfp->filename = NULL;
132
133 sqfp->do_digital = FALSE;
134 sqfp->abc = NULL;
135
136 sqfp->format = format;
137
138 /* initialize the function pointers to NULL */
139 sqfp->position = NULL;
140 sqfp->close = NULL;
141
142 sqfp->set_digital = NULL;
143 sqfp->guess_alphabet = NULL;
144
145 sqfp->is_rewindable = NULL;
146
147 sqfp->read = NULL;
148 sqfp->read_info = NULL;
149 sqfp->read_seq = NULL;
150 sqfp->read_window = NULL;
151 sqfp->echo = NULL;
152
153 sqfp->read_block = NULL;
154
155 sqfp->open_ssi = NULL;
156 sqfp->pos_by_key = NULL;
157 sqfp->pos_by_number = NULL;
158
159 sqfp->fetch = NULL;
160 sqfp->fetch_info = NULL;
161 sqfp->fetch_subseq = NULL;
162
163 sqfp->get_error = NULL;
164
165 /* save the user supplied file name */
166 ESL_ALLOC(sqfp->filename, sizeof(char) * (strlen(filename) + 1));
167 strcpy(sqfp->filename, filename);
168
169 /* we need to process the list of directories starting with the local
170 * directory followed by the list in env one directory at a time
171 * passing the path to the different sequence parsers until we get a hit.
172 */
173 if (strcmp(filename, "-") == 0) { /* stdin special case */
174 if ((status = esl_strdup(filename, -1, &path)) != eslOK) goto ERROR;
175 if ((status = esl_sqascii_Open(path, sqfp->format, sqfp)) != eslOK) goto ERROR;
176 } else {
177
178 /* check the local directory first */
179 status = eslENOTFOUND;
180
181 if (format == eslSQFILE_NCBI && status == eslENOTFOUND)
182 status = esl_sqncbi_Open(sqfp->filename, sqfp->format, sqfp);
183
184 if (status == eslENOTFOUND)
185 status = esl_sqascii_Open(sqfp->filename, sqfp->format, sqfp);
186
187 /* if it's not there, then check in directory list provided by <env>. */
188 if (status == eslENOTFOUND && env != NULL) {
189 if ((s1 = getenv(env)) == NULL) { status = eslENOTFOUND; goto ERROR; }
190 ESL_ALLOC(list, sizeof(char) * (strlen(s1) + 1));
191 strcpy(list + 2, s1);
192
193 ESL_ALLOC(path, sizeof(char) * (strlen(filename) + strlen(list) + 3));
194
195 s1 = list;
196 while (s1 != NULL && status == eslENOTFOUND) {
197 if ((s2 = strchr(s1, ':')) != NULL) { *s2 = '\0'; s2++;}
198 n = strlen(s1);
199 strcpy(path, s1);
200 path[n] = eslDIRSLASH;
201 strcpy(path+n+1, filename);
202 s1 = s2;
203
204
205 if (format == eslSQFILE_NCBI && status == eslENOTFOUND)
206 status = esl_sqncbi_Open(path, sqfp->format, sqfp);
207
208 if (status == eslENOTFOUND)
209 status = esl_sqascii_Open(path, sqfp->format, sqfp);
210 }
211 }
212 }
213
214 if (status != eslOK) goto ERROR;
215
216 if (list != NULL) free(list);
217 if (path != NULL) free(path);
218
219 *ret_sqfp = sqfp;
220 return eslOK;
221
222 ERROR:
223 esl_sqfile_Close(sqfp);
224 if (list != NULL) free(list);
225 if (path != NULL) free(path);
226 *ret_sqfp = NULL;
227 return status;
228 }
229 /*------------------- ESL_SQFILE open/close -----------------------*/
230
231
232
233 /*****************************************************************
234 *# 2. An <ESL_SQFILE> object, in digital mode [with <alphabet>]
235 *****************************************************************/
236
237 /* Function: esl_sqfile_OpenDigital()
238 * Synopsis: Open an <ESL_SQFILE> for digital input.
239 *
240 * Purpose: Same as <esl_sqfile_Open()>, but we will expect all
241 * sequence input to conform to the digital alphabet <abc>.
242 *
243 * Normally, after opening the sequence file in digital
244 * mode, you'd read sequence into a digital <ESL_SQ>.
245 * However, you don't actually have to. The state of the
246 * <ESL_SQ> controls how the input is stored; the state of
247 * the <ESL_SQFILE> controls how the input is validated.
248 *
249 * Returns: <eslOK> on success, and <*ret_sqfp> points to a new
250 * open <ESL_SQFILE>.
251 *
252 * Returns <eslENOTFOUND> if <filename> can't be opened.
253 * Returns <eslEFORMAT> if the file is empty, or if
254 * autodetection is attempted and the format can't be
255 * determined. On any error conditions, <*ret_sqfp> is
256 * returned NULL.
257 *
258 * Throws: <eslEMEM> on allocation failure.
259 */
260 int
261 esl_sqfile_OpenDigital(const ESL_ALPHABET *abc, const char *filename, int format, const char *env, ESL_SQFILE **ret_sqfp)
262 {
263 int status;
264
265 if ((status = sqfile_open(filename, format, env, ret_sqfp)) != eslOK) return status;
266 return esl_sqfile_SetDigital(*ret_sqfp, abc);
267 }
268
269 /* Function: esl_sqfile_SetDigital()
270 * Synopsis: Set an open <ESL_SQFILE> to read in digital mode.
271 *
272 * Purpose: Given an <ESL_SQFILE> that's already been opened,
273 * configure it to expect subsequent input to conform
274 * to the digital alphabet <abc>.
275 *
276 * Calling <esl_sqfile_Open(); esl_sqfile_SetDigital()> is
277 * equivalent to <esl_sqfile_OpenDigital()>. The two-step
278 * version is useful when you need a
279 * <esl_sqfile_GuessAlphabet()> call in between, guessing
280 * the file's alphabet in text mode before you set it to
281 * digital mode.
282 *
283 * Returns: <eslOK> on success.
284 */
285 int
286 esl_sqfile_SetDigital(ESL_SQFILE *sqfp, const ESL_ALPHABET *abc)
287 {
288 sqfp->set_digital(sqfp, abc);
289
290 sqfp->do_digital = TRUE;
291 sqfp->abc = abc;
292 return eslOK;
293 }
294
295
296 /* Function: esl_sqfile_GuessAlphabet()
297 * Synopsis: Guess the alphabet of an open <ESL_SQFILE>.
298 *
299 * Purpose: After opening <sqfp>, attempt to guess what alphabet
300 * its sequences are in, by inspecting the first sequence
301 * in the file, and return this alphabet type in <*ret_type>.
302 *
303 * Returns: <eslOK> on success, and <*ret_type> is set to <eslDNA>,
304 * <eslRNA>, or <eslAMINO>.
305 *
306 * Returns <eslENOALPHABET> if the alphabet can't be
307 * reliably guessed.
308 *
309 * Returns <eslEFORMAT> if a parse error is encountered.
310 * Call <esl_sqfile_GetErrorBuf()> to get a ptr to a
311 * user-directed error message describing the problem,
312 * including the line number on which it was found.
313 *
314 * Returns <eslENODATA> if the file appears to be empty.
315 *
316 * On any error, <*ret_type> is <eslSQFILE_UNKNOWN>.
317 *
318 * Throws: <eslEMEM> on allocation error;
319 * <eslEINCONCEIVABLE> on unimaginable internal errors.
320 */
321 int
322 esl_sqfile_GuessAlphabet(ESL_SQFILE *sqfp, int *ret_type)
323 {
324 return sqfp->guess_alphabet(sqfp, ret_type);
325 }
326
327 /*-------------- end, digital mode ESL_SQFILE -------------------*/
328
329
330
331 /*****************************************************************
332 *# 3. Sequence reading (sequential)
333 *****************************************************************/
334
335 /* Function: esl_sqio_Read()
336 * Synopsis: Read the next sequence from a file.
337 *
338 * Purpose: Reads the next sequence from open sequence file <sqfp> into
339 * <sq>. Caller provides an allocated and initialized <sq>, which
340 * will be internally reallocated if its space is insufficient.
341 *
342 * Returns: <eslOK> on success; the new sequence is stored in <sq>.
343 *
344 * Returns <eslEOF> when there is no sequence left in the
345 * file (including first attempt to read an empty file).
346 *
347 * Returns <eslEFORMAT> if a parse error is encountered.
348 * Call <esl_sqfile_GetErrorBuf()> to get a ptr to a
349 * user-directed error message describing the problem,
350 * including the line number on which it was found.
351 *
352 * Throws: <eslEMEM> on allocation failure;
353 * <eslEINCONCEIVABLE> on internal error.
354 */
355 int
356 esl_sqio_Read(ESL_SQFILE *sqfp, ESL_SQ *sq)
357 {
358 return sqfp->read(sqfp, sq);
359 }
360
361
362 /* Function: esl_sqio_ReadInfo()
363 * Synopsis: Read sequence info, but not the sequence itself.
364 *
365 * Purpose: Read the next sequence from open sequence file <sqfp>,
366 * but don't store the sequence (or secondary structure).
367 * Upon successful return, <s> holds all the available
368 * information about the sequence -- its name, accession,
369 * description, and overall length <sq->L>.
370 *
371 * This is useful for indexing sequence files, where
372 * individual sequences might be ginormous, and we'd rather
373 * avoid reading complete seqs into memory.
374 *
375 * Returns: <eslOK> on success.
376 */
377 int
378 esl_sqio_ReadInfo(ESL_SQFILE *sqfp, ESL_SQ *sq)
379 {
380 return sqfp->read_info(sqfp, sq);
381 }
382
383
384 /* Function: esl_sqio_ReadSequence()
385 * Synopsis: Read sequence, but not the header itself.
386 *
387 * Purpose: Read the next sequence from open sequence file <sqfp>,
388 * skipping over the header data. Upon successful return,
389 * <s> holds just the sequece data. File offsets will be
390 * filled in.
391 *
392 * This is useful fast reads of binary formats where the
393 * header information and sequences are stored in different
394 * files.
395 *
396 * Returns: <eslOK> on success.
397 */
398 int
399 esl_sqio_ReadSequence(ESL_SQFILE *sqfp, ESL_SQ *sq)
400 {
401 return sqfp->read_seq(sqfp, sq);
402 }
403
404
405 /* Function: esl_sqio_ReadWindow()
406 * Synopsis: Read next window of sequence.
407 *
408 * Purpose: Read a next window of <W> residues from open file <sqfp>,
409 * keeping <C> residues from the previous window as
410 * context, and keeping previous annotation in the <sq>
411 * as before.
412 *
413 * If this is the first window of a new sequence record,
414 * <C> is ignored (there's no previous context yet), and
415 * the annotation fields of the <sq> (name, accession, and
416 * description) are initialized by reading the sequence
417 * record's header. This is the only time the annotation
418 * fields are initialized.
419 *
420 * On return, <sq->dsq[]> contains the window and its
421 * context; residues <1..sq->C> are the previous context,
422 * and residues <sq->C+1..sq->n> are the new window. The
423 * start and end coordinates of the whole <dsq[1..n]>
424 * (including context) in the original source sequence are
425 * <sq->start..sq->end>. (Or, for text mode sequences,
426 * <sq->seq[0..sq->C-1,sq->C..sq->n-1]>, while <start> and
427 * <end> coords are still <1..L>.)
428 *
429 * When a sequence record is completed and no more data
430 * remain, <eslEOD> is returned, with an ``info'' <sq>
431 * structure (containing the annotation and the total
432 * sequence length <L>, but no sequence). (The total
433 * sequence length <L> is unknown in <sq> until this
434 * <eslEOD> return.)
435 *
436 * The caller may then do one of two things before calling
437 * <esl_sq_ReadWindow()> again; it can reset the sequence
438 * with <esl_sq_Reuse()> to continue reading the next
439 * sequence in the file, or it can set a negative <W> as a
440 * signal to read windows from the reverse complement
441 * (Crick) strand. Reverse complement reading only works
442 * for nucleic acid sequence.
443 *
444 * If you read the reverse complement strand, you must read
445 * the whole thing, calling <esl_sqio_ReadWindow()> with
446 * negative <W> windows until <eslEOD> is returned again
447 * with an empty (info-only) <sq> structure. When that
448 * <EOD> is reached, the <sqfp> is repositioned at the
449 * start of the next sequence record; the caller should now
450 * <Reuse()> the <sq>, and the next <esl_sqio_ReadWindow()>
451 * call must have a positive <W>, corresponding to starting
452 * to read the Watson strand of the next sequence.
453 *
454 * Note that the <ReadWindow()> interface is designed for
455 * an idiom of sequential reading of complete sequences in
456 * overlapping windows, possibly on both strands; if you
457 * want more freedom to move around in the sequence
458 * grabbing windows in another order, you can use the
459 * <FetchSubseq()> interface.
460 *
461 * Reading the reverse complement strand requires file
462 * repositioning, so it will not work on non-repositionable
463 * streams like gzipped files or a stdin pipe. Moreover,
464 * for reverse complement input to be efficient, the
465 * sequence file should have consistent line lengths,
466 * suitable for SSI's fast subsequence indexing.
467 *
468 * Returns: <eslOK> on success; <sq> now contains next window of
469 * sequence, with at least 1 new residue. The number
470 * of new residues is <sq->W>; <sq->C> residues are
471 * saved from the previous window. Caller may now
472 * process residues <sq->dsq[sq->C+1]..sq->dsq[sq->n]>.
473 *
474 * <eslEOD> if no new residues were read for this sequence
475 * and strand, and <sq> now contains an empty info-only
476 * structure (annotation and <L> are valid). Before calling
477 * <esl_sqio_ReadWindow()> again, caller will either want
478 * to make <W> negative (to start reading the Crick strand
479 * of the current sequence), or it will want to reset the
480 * <sq> (with <esl_sq_Reuse()>) to go on the next sequence.
481 *
482 * <eslEOF> if we've already returned <eslEOD> before to
483 * signal the end of the previous seq record, and moreover,
484 * there's no more sequence records in the file.
485 *
486 * <eslEINVAL> if an invalid residue is found in the
487 * sequence, or if you attempt to take the reverse
488 * complement of a sequence that can't be reverse
489 * complemented.
490 *
491 * Throws: <eslESYNTAX> if you try to read a reverse window before
492 * you've read forward strand.
493 *
494 * <eslECORRUPT> if something goes awry internally in the
495 * coordinate system.
496 *
497 * <eslEMEM> on allocation error.
498 */
499 int
500 esl_sqio_ReadWindow(ESL_SQFILE *sqfp, int C, int W, ESL_SQ *sq)
501 {
502 return sqfp->read_window(sqfp, C, W, sq);
503 }
504
505 /* Function: esl_sqio_ReadBlock()
506 * Synopsis: Read the next block of sequences from a file.
507 *
508 * Purpose: Reads a block of sequences from open sequence file <sqfp> into
509 * <sqBlock>.
510 *
511 * Returns: <eslOK> on success; the new sequence is stored in <sqBlock>.
512 *
513 * Returns <eslEOF> when there is no sequence left in the
514 * file (including first attempt to read an empty file).
515 *
516 * Returns <eslEFORMAT> if a parse error is encountered.
517 * Call <esl_sqfile_GetErrorBuf()> to get a ptr to a
518 * user-directed error message describing the problem,
519 * including the line number on which it was found.
520 *
521 * Throws: <eslEMEM> on allocation failure;
522 * <eslEINCONCEIVABLE> on internal error.
523 */
524 int
525 esl_sqio_ReadBlock(ESL_SQFILE *sqfp, ESL_SQ_BLOCK *sqBlock, int max_residues, int max_sequences, int max_init_window, int long_target)
526 {
527 return sqfp->read_block(sqfp, sqBlock, max_residues, max_sequences, max_init_window, long_target);
528 }
529
530 /* Function: esl_sqio_Parse()
531 * Synopsis: Parse a sequence already read into a buffer.
532 *
533 * Purpose: Parse the buffer <buf> for a sequence <s> of type
534 * <format>. The buffer must contain the entire sequence.
535 *
536 * Returns: <eslOK> on success.
537 *
538 * Throws: <eslEMEM> on allocation error.
539 * <eslEFORMAT> on parsing error.
540 * <eslEINVAL> on unsupported format.
541 */
542 int
543 esl_sqio_Parse(char *buf, int size, ESL_SQ *s, int format)
544 {
545 int status;
546
547 switch (format) {
548 case eslSQFILE_EMBL:
549 case eslSQFILE_UNIPROT:
550 case eslSQFILE_GENBANK:
551 case eslSQFILE_DDBJ:
552 case eslSQFILE_FASTA:
553 case eslSQFILE_DAEMON:
554 status = esl_sqascii_Parse(buf, size, s, format);
555
556 break;
557 default:
558 ESL_EXCEPTION(eslEINVAL, "can't parse that format");
559 }
560 return status;
561 }
562 /*------------------ end, sequential sequence input -------------*/
563
564
565
566 /*****************************************************************
567 *# 4. Writing sequences.
568 *****************************************************************/
569
570 /* Function: esl_sqio_Write()
571 * Synopsis: Write a sequence to a file.
572 *
573 * Purpose: Write sequence <s> to an open FILE <fp> in file format
574 * <format>.
575 *
576 * If <update> is <TRUE>, set the offsets for sequence <s>.
577 *
578 * Returns: <eslOK> on success.
579 *
580 * Throws: <eslEMEM> on allocation error.
581 * <eslEWRITE> on system write error, such as filled disk.
582 */
583 int
584 esl_sqio_Write(FILE *fp, ESL_SQ *s, int format, int update)
585 {
586 ESL_MSA *msa;
587 int status;
588
589 if (esl_sqio_IsAlignment(format))
590 {
591 if ((status = convert_sq_to_msa(s, &msa)) != eslOK) return status;
592 status = esl_msafile_Write(fp, msa, format);
593 esl_msa_Destroy(msa);
594 return status;
595 }
596
597 switch (format) {
598 case eslSQFILE_FASTA:
599 case eslSQFILE_HMMPGMD:
600 status = esl_sqascii_WriteFasta(fp, s, update);
601 break;
602 default:
603 ESL_EXCEPTION(eslEINCONCEIVABLE, "can't write that format");
604 }
605 return status;
606 }
607
608 /* Function: esl_sqio_Echo()
609 * Synopsis: Echo a sequence's record onto output stream.
610 *
611 * Purpose: Given a complete <sq> that we have read by some means
612 * from an open <sqfp>; echo that sequence's record
613 * onto the output stream <ofp>.
614 *
615 * This allows records to be regurgitated exactly as they
616 * appear, rather than writing the subset of information
617 * stored in an <ESL_SQ>. <esl-sfetch> in the miniapps uses
618 * this, for example.
619 *
620 * Because this relies on repositioning the <sqfp>, it
621 * cannot be called on non-positionable streams (stdin or
622 * gzipped files). Because it relies on the sequence lying
623 * in a contiguous sequence of bytes in the file, it cannot
624 * be called on a sequence in a multiple alignment file.
625 * Trying to do so throws an <eslEINVAL> exception.
626 *
627 * Returns: <eslOK> on success.
628 *
629 * Throws: <eslEINVAL> if <sqfp> isn't a repositionable sequence file.
630 * <eslECORRUPT> if we run out of data, probably from bad offsets
631 * <eslEMEM> on allocation failure.
632 * <eslESYS> on system call failures.
633 *
634 *
635 */
636 int
637 esl_sqio_Echo(ESL_SQFILE *sqfp, const ESL_SQ *sq, FILE *ofp)
638 {
639 return sqfp->echo(sqfp, sq, ofp);
640 }
641 /*----------------- end, writing sequences ---------------------*/
642
643
644
645 /*****************************************************************
646 *# 5. Miscellaneous routines
647 *****************************************************************/
648
649 /* Function: esl_sqfile_GetErrorBuf()
650 * Synopsis: Return the error buffer
651 *
652 * Purpose: Returns the pointer to the error buffer.
653 * Each parser is responsible for formatting
654 * a zero terminated string describing the
655 * error condition.
656 *
657 * Returns: A pointer the error message.
658 */
659 const char *
660 esl_sqfile_GetErrorBuf(const ESL_SQFILE *sqfp)
661 {
662 return sqfp->get_error(sqfp);
663 }
664
665
666 /* Function: esl_sqfile_IsRewindable()
667 * Synopsis: Return <TRUE> if <sqfp> can be rewound.
668 *
669 * Purpose: Returns <TRUE> if <sqfp> can be rewound (positioned
670 * to an offset of zero), in order to read it a second
671 * time.
672 */
673 int
674 esl_sqfile_IsRewindable(const ESL_SQFILE *sqfp)
675 {
676 return sqfp->is_rewindable(sqfp);
677 }
678
679 /* Function: esl_sqio_IsAlignment()
680 * Synopsis: Return TRUE for alignment file format codes.
681 *
682 * Purpose: Returns TRUE if <fmt> is an alignment file
683 * format code; else returns FALSE.
684 *
685 * This function only checks the convention
686 * that <fmt> codes $<$100 are unaligned formats,
687 * and $\geq$100 are aligned formats. It does
688 * not check that <fmt> is a recognized format
689 * code.
690 */
691 int
692 esl_sqio_IsAlignment(int fmt)
693 {
694 return (fmt >= 100 ? TRUE : FALSE);
695 }
696
697
698 /* Function: esl_sqio_EncodeFormat()
699 * Synopsis: Convert a string to an internal format code.
700 *
701 * Purpose: Given <fmtstring>, return format code. For example, if
702 * <fmtstring> is "fasta", returns <eslSQFILE_FASTA>. Returns
703 * <eslSQFILE_UNKNOWN> if <fmtstring> doesn't exactly match a
704 * known format.
705 *
706 * Matching is case insensitive; fasta, FASTA, and FastA
707 * all return <eslSQFILE_FASTA>, for example.
708 */
709 int
710 esl_sqio_EncodeFormat(char *fmtstring)
711 {
712 if (strcasecmp(fmtstring, "fasta") == 0) return eslSQFILE_FASTA;
713 if (strcasecmp(fmtstring, "embl") == 0) return eslSQFILE_EMBL;
714 if (strcasecmp(fmtstring, "genbank") == 0) return eslSQFILE_GENBANK;
715 if (strcasecmp(fmtstring, "ddbj") == 0) return eslSQFILE_DDBJ;
716 if (strcasecmp(fmtstring, "uniprot") == 0) return eslSQFILE_UNIPROT;
717 if (strcasecmp(fmtstring, "ncbi") == 0) return eslSQFILE_NCBI;
718 if (strcasecmp(fmtstring, "daemon") == 0) return eslSQFILE_DAEMON;
719 if (strcasecmp(fmtstring, "hmmpgmd") == 0) return eslSQFILE_HMMPGMD;
720 if (strcasecmp(fmtstring, "fmindex") == 0) return eslSQFILE_FMINDEX;
721 return esl_msafile_EncodeFormat(fmtstring);
722 }
723
724 /* Function: esl_sqio_DecodeFormat()
725 * Synopsis: Returns descriptive string for file format code.
726 *
727 * Purpose: Given a format code <fmt>, returns a string label for
728 * that format. For example, if <fmt> is <eslSQFILE_FASTA>,
729 * returns "FASTA".
730 */
731 char *
732 esl_sqio_DecodeFormat(int fmt)
733 {
734 if (esl_sqio_IsAlignment(fmt)) return esl_msafile_DecodeFormat(fmt);
735
736 switch (fmt) {
737 case eslSQFILE_UNKNOWN: return "unknown";
738 case eslSQFILE_FASTA: return "FASTA";
739 case eslSQFILE_EMBL: return "EMBL";
740 case eslSQFILE_GENBANK: return "GenBank";
741 case eslSQFILE_DDBJ: return "DDBJ";
742 case eslSQFILE_UNIPROT: return "UniProt";
743 case eslSQFILE_NCBI: return "NCBI";
744 case eslSQFILE_DAEMON: return "daemon";
745 case eslSQFILE_HMMPGMD: return "hmmpgmd";
746 case eslSQFILE_FMINDEX: return "fmindex";
747 default: break;
748 }
749 esl_exception(eslEINVAL, FALSE, __FILE__, __LINE__, "no such sqio format code %d", fmt);
750 return NULL;
751 }
752
753
754 /* Function: esl_sqfile_Position()
755 * Synopsis: Reposition an open sequence file to an offset.
756 *
757 * Purpose: Reposition an open <sqfp> to offset <offset>.
758 * <offset> would usually be the first byte of a
759 * desired sequence record.
760 *
761 * Only normal sequence files can be positioned to a
762 * nonzero offset. If <sqfp> corresponds to a standard
763 * input stream or gzip -dc stream, it may not be
764 * repositioned. If <sqfp> corresponds to a multiple
765 * sequence alignment file, the only legal <offset>
766 * is 0, to rewind the file to the beginning and
767 * be able to read the entire thing again.
768 *
769 * After <esl_sqfile_Position()> is called on a nonzero
770 * <offset>, other bookkeeping information is unknown.
771 * If caller knows it, it should set it explicitly.
772 *
773 * See the SSI module for manipulating offsets and indices.
774 *
775 * Returns: <eslOK> on success;
776 * <eslEOF> if no data can be read from this position.
777 *
778 * Throws: <eslESYS> if the fseeko() or fread() call fails.
779 * <eslEMEM> on (re-)allocation failure.
780 * <eslEINVAL> if the <sqfp> is not positionable.
781 * <eslENOTFOUND> if in trying to rewind an alignment file
782 * by closing and reopening it, the open fails.
783 * On errors, the state of <sqfp> is indeterminate, and
784 * it should not be used again.
785 */
786 int
787 esl_sqfile_Position(ESL_SQFILE *sqfp, off_t offset)
788 {
789 return sqfp->position(sqfp, offset);
790 }
791
792 /* Function: esl_sqio_Ignore()
793 * Synopsis: Sets the input map to ignore one or more input characters.
794 *
795 * Purpose: Set the input map of the open <sqfp> to allow
796 * the characters in the string <ignoredchars> to appear
797 * in input sequences. These characters will be ignored.
798 *
799 * For example, an application might want to ignore '*'
800 * characters in its sequence input, because some translated
801 * peptide files use '*' to indicate stop codons.
802 *
803 * Returns: <eslOK> on success.
804 */
805 int
806 esl_sqio_Ignore(ESL_SQFILE *sqfp, const char *ignoredchars)
807 {
808 int i;
809 for (i = 0; ignoredchars[i] != '\0'; i++)
810 sqfp->inmap[(int) ignoredchars[i]] = eslDSQ_IGNORED;
811 return eslOK;
812 }
813
814 /* Function: esl_sqio_AcceptAs()
815 * Synopsis: Map a list of additional characters.
816 *
817 * Purpose: Set the input map of the open <sqfp> to allow the
818 * characters in the string <xchars> to appear in
819 * input sequences. These characters will all be
820 * mapped to the character <readas> (or, for digital
821 * sequence input, to the digitized representation
822 * of the text character <readas> in the <sqfp>'s
823 * digital alphabet).
824 *
825 * For example, an application might want to read
826 * '*' as 'X' when reading translated peptide files
827 * that use '*' to indicate a stop codon.
828 *
829 * Returns: <eslOK> on success.
830 */
831 int
832 esl_sqio_AcceptAs(ESL_SQFILE *sqfp, char *xchars, char readas)
833 {
834 int i;
835
836 if (sqfp->do_digital)
837 {
838 for (i = 0; xchars[i] != '\0'; i++)
839 sqfp->inmap[(int) xchars[i]] = esl_abc_DigitizeSymbol(sqfp->abc, readas);
840 }
841
842 if (! sqfp->do_digital)
843 {
844 for (i = 0; xchars[i] != '\0'; i++)
845 sqfp->inmap[(int) xchars[i]] = readas;
846 }
847 return eslOK;
848
849 }
850 /*--------------- end, miscellaneous routines -------------------*/
851
852
853
854 /*****************************************************************
855 *# 6. Sequence/subsequence fetching, random access [with <ssi>]
856 *****************************************************************/
857
858
859 /* Function: esl_sqfile_OpenSSI()
860 * Synopsis: Opens an SSI index associated with a sequence file.
861 *
862 * Purpose: Opens an SSI index file associated with the already open
863 * sequence file <sqfp>. If successful, the necessary
864 * information about the open SSI file is stored internally
865 * in <sqfp>.
866 *
867 * The SSI index file name is determined in one of two
868 * ways, depending on whether a non-<NULL> <ssifile_hint>
869 * is provided.
870 *
871 * If <ssifile_hint> is <NULL>, the default for
872 * constructing the SSI filename from the sequence
873 * filename, by using exactly the same path (if any) for
874 * the sequence filename, and appending the suffix <.ssi>.
875 * For example, the SSI index for <foo> is <foo.ssi>, for
876 * <./foo.fa> is <./foo.fa.ssi>, and for
877 * </my/path/to/foo.1.fa> is </my/path/to/foo.1.fa.ssi>.
878 *
879 * If <ssifile_hint> is <non-NULL>, this exact fully
880 * qualified path is used as the SSI file name.
881 *
882 * Returns: <eslOK> on success, and <sqfp->ssi> is now internally
883 * valid.
884 *
885 * <eslENOTFOUND> if no SSI index file is found;
886 * <eslEFORMAT> if it's found, but appears to be in incorrect format;
887 * <eslERANGE> if the SSI file uses 64-bit offsets but we're on
888 * a system that doesn't support 64-bit file offsets.
889 *
890 * Throws: <eslEINVAL> if the open sequence file <sqfp> doesn't
891 * correspond to a normal sequence flatfile -- we can't
892 * random access in .gz compressed files, standard input,
893 * or multiple alignment files that we're reading
894 * sequentially.
895 *
896 * Throws <eslEMEM> on allocation error.
897 */
898 int
899 esl_sqfile_OpenSSI(ESL_SQFILE *sqfp, const char *ssifile_hint)
900 {
901 return sqfp->open_ssi(sqfp, ssifile_hint);
902 }
903
904
905
906 /* Function: esl_sqfile_PositionByKey()
907 * Synopsis: Use SSI to reposition seq file to a particular sequence.
908 *
909 * Purpose: Reposition <sqfp> so that the next sequence we read will
910 * be the one named (or accessioned) <key>.
911 *
912 * <sqfp->linenumber> is reset to be relative to the start
913 * of the record named <key>, rather than the start of the
914 * file.
915 *
916 * Returns: <eslOK> on success, and the file <sqfp> is repositioned
917 * so that the next <esl_sqio_Read()> call will read the
918 * sequence named <key>.
919 *
920 * Returns <eslENOTFOUND> if <key> isn't found in the
921 * index; in this case, the position of <sqfp> in the file
922 * is unchanged.
923 *
924 * Returns <eslEFORMAT> if something goes wrong trying to
925 * read the index, almost certainly indicating a format
926 * problem in the SSI file.
927 *
928 * Returns <eslEOF> if, after repositioning, we fail to
929 * load the next line or buffer from the sequence file;
930 * this probably also indicates a format problem in the SSI
931 * file.
932 *
933 * Throws: <eslEMEM> on allocation error;
934 * <eslEINVAL> if there's no open SSI index in <sqfp>;
935 * <eslESYS> if the <fseek()> fails.
936 *
937 * In all these cases, the state of <sqfp> becomes
938 * undefined, and the caller should not use it again.
939 */
940 int
941 esl_sqfile_PositionByKey(ESL_SQFILE *sqfp, const char *key)
942 {
943 return sqfp->pos_by_key(sqfp, key);
944 }
945
946
947 /* Function: esl_sqfile_PositionByNumber()
948 * Synopsis: Use SSI to reposition by sequence number
949 *
950 * Purpose: Reposition <sqfp> so that the next sequence we
951 * read will be the <which>'th sequence, where <which>
952 * is <0..sqfp->ssi->nprimary-1>.
953 *
954 * <sqfp->linenumber> is reset to be relative to the start
955 * of the record named <key>, rather than the start of the
956 * file.
957 *
958 * Returns: <eslOK> on success, and the file <sqfp> is repositioned.
959 *
960 * Returns <eslENOTFOUND> if there is no sequence number
961 * <which> in the index; in this case, the position of
962 * <sqfp> in the file is unchanged.
963 *
964 * Returns <eslEFORMAT> if something goes wrong trying to
965 * read the index, almost certainly indicating a format
966 * problem in the SSI file.
967 *
968 * Returns <eslEOF> if, after repositioning, we fail to
969 * load the next line or buffer from the sequence file;
970 * this probably also indicates a format problem in the SSI
971 * file.
972 *
973 * Throws: <eslEMEM> on allocation error;
974 * <eslEINVAL> if there's no open SSI index in <sqfp>;
975 * <eslESYS> if the <fseek()> fails.
976 *
977 * In all these cases, the state of <sqfp> becomes
978 * undefined, and the caller should not use it again.
979 */
980 int
981 esl_sqfile_PositionByNumber(ESL_SQFILE *sqfp, int which)
982 {
983 return sqfp->pos_by_number(sqfp, which);
984 }
985
986
987 /* Function: esl_sqio_Fetch()
988 * Synopsis: Fetch a complete sequence, using SSI indexing.
989 *
990 * Purpose: Fetch a sequence named (or accessioned) <key> from
991 * the repositionable, open sequence file <sqfp>.
992 * The open <sqfp> must have an open SSI index.
993 * The sequence is returned in <sq>.
994 *
995 * Returns: <eslOK> on soccess.
996 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
997 * be repositioned.
998 * <eslENOTFOUND> if <source> isn't found in the file.
999 * <eslEFORMAT> if either the index file or the sequence file
1000 * can't be parsed, because of unexpected format issues.
1001 *
1002 * Throws: <eslEMEM> on allocation error.
1003 */
1004 int
1005 esl_sqio_Fetch(ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq)
1006 {
1007 return sqfp->fetch(sqfp, key, sq);
1008 }
1009
1010 /* Function: esl_sqio_FetchInfo()
1011 * Synopsis: Fetch a sequence's info, using SSI indexing.
1012 *
1013 * Purpose: Fetch a sequence named (or accessioned) <key> from
1014 * the repositionable, open sequence file <sqfp>, reading
1015 * all info except the sequence (and secondary structure).
1016 * The open <sqfp> must have an open SSI index.
1017 * The sequence info is returned in <sq>.
1018 *
1019 * Returns: <eslOK> on soccess.
1020 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
1021 * be repositioned.
1022 * <eslENOTFOUND> if <source> isn't found in the file.
1023 * <eslEFORMAT> if either the index file or the sequence file
1024 * can't be parsed, because of unexpected format issues.
1025 *
1026 * Throws: <eslEMEM> on allocation error.
1027 */
1028 int
1029 esl_sqio_FetchInfo(ESL_SQFILE *sqfp, const char *key, ESL_SQ *sq)
1030 {
1031 return sqfp->fetch_info(sqfp, key, sq);
1032 }
1033
1034
1035 /* Function: esl_sqio_FetchSubseq()
1036 * Synopsis: Fetch a subsequence, using SSI indexing.
1037 *
1038 * Purpose: Fetch subsequence <start..end> from a sequence named (or
1039 * accessioned) <source>, in the repositionable, open sequence file <sqfp>.
1040 * The open <sqfp> must have an SSI index. Put the
1041 * subsequence in <sq>.
1042 *
1043 * As a special case, if <end> is 0, the subsequence is
1044 * fetched all the way to the end, so you don't need to
1045 * look up the sequence length <L> to fetch a suffix.
1046 *
1047 * The caller may want to rename/reaccession/reannotate the
1048 * subsequence. Upon successful return, <sq->name> is set
1049 * to <source/start-end>, and <sq->source> is set to
1050 * <source> The accession and description <sq->acc> and
1051 * <sq->desc> are set to the accession and description of
1052 * the source sequence.
1053 *
1054 * Returns: <eslOK> on success.
1055 * <eslEINVAL> if no SSI index is present, or if <sqfp> can't
1056 * be repositioned.
1057 * <eslENOTFOUND> if <source> isn't found in the file.
1058 * <eslEFORMAT> if either the index file or the sequence file
1059 * can't be parsed, because of unexpected format issues.
1060 * <eslERANGE> if the <start..end> coords don't lie entirely
1061 * within the <source> sequence.
1062 *
1063 * Throws: <eslEMEM> on allocation errors.
1064 */
1065 int
1066 esl_sqio_FetchSubseq(ESL_SQFILE *sqfp, const char *source, int64_t start, int64_t end, ESL_SQ *sq)
1067 {
1068 return sqfp->fetch_subseq(sqfp, source, start, end, sq);
1069 }
1070 /*------------- end, random sequence access with SSI -------------------*/
1071
1072
1073 /*****************************************************************
1074 *# 7. Sequence database caching.
1075 *****************************************************************/
1076
1077 /* Function: esl_sqfile_Cache()
1078 * Synopsis: Read a database into memory.
1079 *
1080 * Purpose: Read an entire database into memory building a cached
1081 * structure <ESL_SQCACHE>. The cache structure has basic
1082 * information about the database, ie number of sequences
1083 * number of residues, etc.
1084 *
1085 * All sequences <ESL_SQ> are in a memory array <sq_list>.
1086 * The number of elements in the list is <seq_count>. The
1087 * header pointers, ie name, acc and desc are pointers into
1088 * the <header_mem> buffer. All digitized sequences are pointers
1089 * into the <residue_mem> buffer.
1090 *
1091 * Returns: <eslOK> on success.
1092 *
1093 * Returns <eslEFORMAT> if a parse error is encountered in
1094 * trying to read the sequence file.
1095 *
1096 * Returns <eslENODATA> if the file appears to be empty.
1097 *
1098 * Throws: <eslEMEM> on allocation error;
1099 */
1100 int
1101 esl_sqfile_Cache(const ESL_ALPHABET *abc, const char *seqfile, int fmt, const char *env, ESL_SQCACHE **ret_sqcache)
1102 {
1103 int status;
1104
1105 int n;
1106
1107 uint32_t len;
1108 uint32_t max;
1109 uint32_t count;
1110
1111 uint64_t res_size = 1;
1112 uint64_t hdr_size = 1;
1113
1114 ESL_SQFILE *sqfp = NULL;
1115
1116 ESL_SQ *c = NULL;
1117 ESL_SQ *sq = NULL;
1118 ESL_SQCACHE *cache = NULL;
1119
1120 ESL_DSQ *res_ptr = NULL;
1121 char *hdr_ptr = NULL;
1122
1123 /* open the database */
1124 status = esl_sqfile_OpenDigital(abc, seqfile, fmt, env, &sqfp);
1125 if (status != eslOK) return status;
1126
1127 /* if we can't rewind the database, stop now. */
1128 if (!esl_sqfile_IsRewindable(sqfp)) return eslFAIL;
1129
1130 /* loop through the database reading all the sequnces */
1131 max = 0;
1132 count = 0;
1133 sq = esl_sq_CreateDigital(abc);
1134 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK) {
1135 ++count;
1136
1137 res_size += sq->n + 1;
1138 if (sq->n > max) max = sq->n;
1139
1140 len = strlen(sq->name);
1141 if (len > 0) ++len;
1142 hdr_size += len;
1143
1144 len = strlen(sq->acc);
1145 if (len > 0) ++len;
1146 hdr_size += len;
1147
1148 len = strlen(sq->desc);
1149 if (len > 0) ++len;
1150 hdr_size += len;
1151
1152 esl_sq_Reuse(sq);
1153 }
1154 if (status != eslEOF) goto ERROR;
1155
1156 /* now that the database information is know, allocate the memory to
1157 * hold the data. different memory blocks will be used to hold the
1158 * redisues and header info. the idea is that since the header info,
1159 * ie, name, acc, etc is used infrenquently (only when there is a hit)
1160 * if some pages need to be swapped out, hopefully it will be the
1161 * header pages first leaving the sequences in memory.
1162 */
1163 ESL_ALLOC(cache, sizeof(ESL_SQCACHE));
1164
1165 cache->filename = NULL;
1166 cache->sq_list = NULL;
1167 cache->residue_mem = NULL;
1168 cache->header_mem = NULL;
1169
1170 cache->abc = abc;
1171 cache->format = fmt;
1172 cache->seq_count = count;
1173 cache->res_count = res_size;
1174 cache->max_seq = max;
1175
1176 cache->res_size = res_size + 2;
1177 cache->hdr_size = hdr_size;
1178
1179 ESL_ALLOC(cache->filename, strlen(seqfile) + 1);
1180 strcpy(cache->filename, seqfile);
1181
1182 ESL_ALLOC(cache->sq_list, sizeof(ESL_SQ) * (count + 1));
1183
1184 /* different memory blocks will be used to hold the residues and header
1185 * info. the idea is that since the header info, ie, name, acc, etc.
1186 * is used infrenquently (only when there is a hit) if some pages need
1187 * to be swapped out, hopefully it will be the header pages first
1188 * leaving the sequences in memory.
1189 */
1190 ESL_ALLOC(cache->residue_mem, res_size + 2);
1191 ESL_ALLOC(cache->header_mem, hdr_size);
1192
1193 hdr_ptr = cache->header_mem;
1194 *hdr_ptr = 0;
1195
1196 res_ptr = cache->residue_mem;
1197 *res_ptr = eslDSQ_SENTINEL;
1198
1199 /* loop through the database filling in the cache */
1200 n = 0;
1201 esl_sqfile_Position(sqfp, 0);
1202 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK) {
1203 c = cache->sq_list + n;
1204
1205 /* if header fields have been defined, copy them to the cache */
1206 c->name = hdr_ptr;
1207 if (sq->name[0] != 0) {
1208 c->name = hdr_ptr + 1;
1209 strcpy(c->name, sq->name);
1210 hdr_ptr += strlen(sq->name) + 1;
1211 }
1212
1213 c->acc = hdr_ptr;
1214 if (sq->acc[0] != 0) {
1215 c->acc = hdr_ptr + 1;
1216 strcpy(c->acc, sq->acc);
1217 hdr_ptr += strlen(sq->acc) + 1;
1218 }
1219
1220 c->desc = hdr_ptr;
1221 if (sq->desc[0] != 0) {
1222 c->desc = hdr_ptr + 1;
1223 strcpy(c->desc, sq->desc);
1224 hdr_ptr += strlen(sq->desc) + 1;
1225 }
1226
1227 c->tax_id = sq->tax_id;
1228 c->seq = NULL;
1229 c->ss = NULL;
1230 c->nxr = 0;
1231 c->xr_tag = NULL;
1232 c->xr = NULL;
1233
1234 /* copy the digitized sequence */
1235 memcpy(res_ptr + 1, sq->dsq + 1, sq->n + 1);
1236 c->dsq = res_ptr;
1237 c->n = sq->n;
1238 res_ptr += sq->n + 1;
1239
1240 /* Coordinate info */
1241 c->start = sq->start;
1242 c->end = sq->end;
1243 c->C = sq->C;
1244 c->W = sq->W;
1245 c->L = sq->L;
1246
1247 c->source = NULL;
1248
1249 /* allocated lengths */
1250 c->nalloc = -1;
1251 c->aalloc = -1;
1252 c->dalloc = -1;
1253 c->salloc = -1;
1254 c->srcalloc = -1;
1255
1256 /* Disk offset bookkeeping */
1257 c->idx = n;
1258 c->roff = sq->roff;
1259 c->hoff = sq->hoff;
1260 c->doff = sq->doff;
1261 c->eoff = sq->eoff;
1262
1263 c->abc = abc;
1264
1265 esl_sq_Reuse(sq);
1266 ++n;
1267 }
1268 if (status != eslEOF) goto ERROR;
1269
1270 /* add on last empty sequence */
1271 c = cache->sq_list + count;
1272 *(res_ptr + 1) = eslDSQ_SENTINEL;
1273
1274 c->name = hdr_ptr;
1275 c->acc = hdr_ptr;
1276 c->desc = hdr_ptr;
1277
1278 c->tax_id = -1;
1279 c->seq = NULL;
1280 c->ss = NULL;
1281 c->nxr = 0;
1282 c->xr_tag = NULL;
1283 c->xr = NULL;
1284
1285 c->dsq = res_ptr;
1286 c->n = 0;
1287
1288 c->start = 0;
1289 c->end = 0;
1290 c->C = 0;
1291 c->W = 0;
1292 c->L = -1;
1293
1294 c->source = NULL;
1295
1296 c->nalloc = -1;
1297 c->aalloc = -1;
1298 c->dalloc = -1;
1299 c->salloc = -1;
1300 c->srcalloc = -1;
1301
1302 c->idx = count;
1303 c->roff = -1;
1304 c->hoff = -1;
1305 c->doff = -1;
1306 c->eoff = -1;
1307
1308 c->abc = NULL;
1309
1310 if (sq != NULL) esl_sq_Destroy(sq);
1311 esl_sqfile_Close(sqfp);
1312
1313 *ret_sqcache = cache;
1314
1315 return eslOK;
1316
1317 ERROR:
1318 if (sq != NULL) esl_sq_Destroy(sq);
1319 esl_sqfile_Close(sqfp);
1320
1321 esl_sqfile_Free(cache);
1322
1323 return status;
1324 }
1325
1326 /* Function: esl_sqfile_Free()
1327 * Synopsis: Free a cached database <ESL_SQCACHE>.
1328 *
1329 * Purpose: Frees all the memory used to cache the sequence database.
1330 *
1331 * Returns: none.
1332 */
1333 void
1334 esl_sqfile_Free(ESL_SQCACHE *sqcache)
1335 {
1336 if (sqcache == NULL) return;
1337
1338 if (sqcache->filename != NULL) free(sqcache->filename);
1339 if (sqcache->sq_list != NULL) free(sqcache->sq_list);
1340 if (sqcache->residue_mem != NULL) free(sqcache->residue_mem);
1341 if (sqcache->header_mem != NULL) free(sqcache->header_mem);
1342
1343 sqcache->abc = NULL;
1344 sqcache->filename = NULL;
1345 sqcache->sq_list = NULL;
1346 sqcache->residue_mem = NULL;
1347 sqcache->header_mem = NULL;
1348
1349 free(sqcache);
1350 }
1351 /*---------------- end, sequence database caching ---------------*/
1352
1353
1354
1355
1356
1357 /*****************************************************************
1358 * 8. Functions specific to sqio <-> msa interoperation [with <msa>]
1359 *****************************************************************/
1360
1361 /* convert_sq_to_msa()
1362 *
1363 * Given a <sq>, create and return an "MSA" through <ret_msa>, which
1364 * contains only the single unaligned sequence. <sq> is
1365 * not affected in any way. This is only to convert from the SQ
1366 * object to an MSA object for the purpose of writing SQ in an MSA format
1367 * file format.
1368 *
1369 * Returns <eslOK> on success, and <*ret_msa> points to
1370 * a new "alignment".
1371 *
1372 * Throws <eslEMEM> on allocation error, and <*ret_msa> is NULL.
1373 */
1374 static int
1375 convert_sq_to_msa(ESL_SQ *sq, ESL_MSA **ret_msa)
1376 {
1377 ESL_MSA *msa;
1378 int x; /* counter for extra-residue markups */
1379 int status;
1380
1381 if (sq->dsq != NULL)
1382 {
1383 if ((msa = esl_msa_CreateDigital(sq->abc, 1, sq->n)) == NULL) { status = eslEMEM; goto ERROR; }
1384 }
1385 else if ((msa = esl_msa_Create(1, sq->n)) == NULL) { status = eslEMEM; goto ERROR; }
1386
1387 if ((status = esl_strdup(sq->name, -1, &(msa->sqname[0]))) != eslOK) goto ERROR;
1388
1389 if (*sq->acc != '\0')
1390 {
1391 ESL_ALLOC(msa->sqacc, sizeof(char *) * 1);
1392 if ((status = esl_strdup(sq->acc, -1, &(msa->sqacc[0]))) != eslOK) goto ERROR;
1393 }
1394 if (*sq->desc != '\0')
1395 {
1396 ESL_ALLOC(msa->sqdesc, sizeof(char *) * 1);
1397 if ((status = esl_strdup(sq->desc, -1, &(msa->sqdesc[0]))) != eslOK) goto ERROR;
1398 }
1399
1400 if (sq->dsq != NULL) esl_abc_dsqcpy(sq->dsq, sq->n, msa->ax[0]);
1401 else strcpy(msa->aseq[0], sq->seq);
1402
1403 if (sq->ss != NULL)
1404 {
1405 ESL_ALLOC(msa->ss, sizeof(char *) * 1);
1406
1407 if (sq->dsq != NULL) { /* sq->ss is 1..L in digital mode; but msa->ss is always 0..L-1 */
1408 if ((status = esl_strdup(sq->ss+1, -1, &(msa->ss[0]))) != eslOK) goto ERROR;
1409 } else if ((status = esl_strdup(sq->ss, -1, &(msa->ss[0]))) != eslOK) goto ERROR;
1410 }
1411
1412 if (sq->nxr > 0) {
1413 msa->ngr = sq->nxr;
1414 ESL_ALLOC(msa->gr, sizeof(char **) * msa->ngr);
1415 ESL_ALLOC(msa->gr_tag, sizeof(char *) * msa->ngr);
1416
1417 for (x = 0; x < msa->ngr; x ++) {
1418 ESL_ALLOC(msa->gr[x], sizeof(char *));
1419 ESL_ALLOC(msa->gr_tag[x], sizeof(char));
1420
1421 if (sq->dsq != NULL) { /* sq->xr is 1..L in digital mode; but msa->gr is always 0..L-1 */
1422 if ((status = esl_strdup(sq->xr[x]+1, -1, &(msa->gr[x][0]))) != eslOK) goto ERROR;
1423 } else if ((status = esl_strdup(sq->xr[x], -1, &(msa->gr[x][0]))) != eslOK) goto ERROR;
1424
1425 if ((status = esl_strdup(sq->xr_tag[x], -1, &(msa->gr_tag[x]))) != eslOK) goto ERROR;
1426 }
1427 }
1428
1429 msa->alen = sq->n;
1430 msa->nseq = 1;
1431 *ret_msa = msa;
1432 return eslOK;
1433
1434 ERROR:
1435 esl_msa_Destroy(msa);
1436 *ret_msa = NULL;
1437 return status;
1438 }
1439 /*---------- end of msa <-> sqio module interop -----------------*/
1440
1441
1442
1443 /*****************************************************************
1444 *# 9. Benchmark driver
1445 *****************************************************************/
1446 /* Some current results:
1447 *
1448 * ./benchmark /misc/data0/genomes/c.elegans/genome/allWS120
1449 * CPU Time: 0.90u 0.06s 00:00:00.96 Elapsed: 00:00:01
1450 *
1451 * /benchmark -i /misc/data0/genomes/c.elegans/genome/allWS120
1452 * CPU Time: 0.41u 0.04s 00:00:00.44 Elapsed: 00:00:00
1453 *
1454 * ./benchmark -w /misc/data0/genomes/c.elegans/genome/allWS120
1455 * CPU Time: 0.83u 0.05s 00:00:00.88 Elapsed: 00:00:01
1456 *
1457 * ./benchmark -2w /misc/data0/genomes/c.elegans/genome/allWS120
1458 * CPU Time: 3.55u 0.26s 00:00:03.80 Elapsed: 00:00:04
1459 *
1460 * Digital times are comparable (maybe a titch faster), except
1461 * for -d2w, which runs much faster, because rev complementation is
1462 * more efficient:
1463 *
1464 * ./benchmark -d2w /misc/data0/genomes/c.elegans/genome/allWS120
1465 * CPU Time: 2.16u 0.31s 00:00:02.47 Elapsed: 00:00:03
1466 */
1467 #ifdef eslSQIO_BENCHMARK
1468 #include <stdlib.h>
1469 #include <stdio.h>
1470 #include <unistd.h>
1471 #include <sys/types.h>
1472 #include <sys/stat.h>
1473 #include <sys/mman.h>
1474 #include <fcntl.h>
1475
1476 #include "easel.h"
1477 #include "esl_getopts.h"
1478 #include "esl_sq.h"
1479 #include "esl_sqio.h"
1480 #include "esl_stopwatch.h"
1481
1482 static ESL_OPTIONS options[] = {
1483 /* name type default env range toggles reqs incomp help docgroup*/
1484 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1485 { "-d", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use digital sequence input mode", 0 },
1486 { "-i", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark ReadInfo() input", 0 },
1487 { "-s", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark ReadSequence() input", 0 },
1488 { "-w", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark ReadWindow() input", 0 },
1489 { "-B", eslARG_INT, "4096", NULL, NULL, NULL, NULL, NULL, "buffer size for read, fread tests", 0 },
1490 { "-C", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "context size for ReadWindow()", 0 },
1491 { "-W", eslARG_INT, "1000", NULL, NULL, NULL, NULL, NULL, "window size for ReadWindow()", 0 },
1492 { "-2", eslARG_NONE, FALSE, NULL, NULL, NULL, "-w", NULL, "with ReadWindow(), do both strands", 0 },
1493 { "--format", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "assert <seqfile> is in format <s>", 0 },
1494 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use protein alphabet, not DNA", 0 },
1495 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1496 };
1497 static char usage[] = "[-options] <DNA FASTA file>";
1498 static char banner[] = "benchmark driver for sqio module";
1499
1500 static int benchmark_read (char *filename, int bufsize, int64_t *ret_magic);
1501 static int benchmark_fread(char *filename, int bufsize, int64_t *ret_magic);
1502 static int benchmark_fgets(char *filename, int bufsize, int64_t *ret_magic);
1503 /*static int benchmark_mmap (char *filename, int bufsize, int64_t *ret_magic);*/
1504
1505 int
1506 main(int argc, char **argv)
1507 {
1508 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
1509 ESL_STOPWATCH *w = esl_stopwatch_Create();
1510 ESL_ALPHABET *abc = NULL;
1511 ESL_SQ *sq = NULL;
1512 ESL_SQFILE *sqfp = NULL;
1513 char *filename = esl_opt_GetArg(go, 1);
1514 int format = eslSQFILE_UNKNOWN;
1515 int bufsize = esl_opt_GetInteger(go, "-B");
1516 int C = esl_opt_GetInteger(go, "-C");
1517 int W = esl_opt_GetInteger(go, "-W");
1518 int do_crick = esl_opt_GetBoolean(go, "-2");
1519 int n = 0;
1520 int64_t magic = 0;
1521 int64_t nr = 0;
1522
1523 if (esl_opt_IsOn(go, "--format")) {
1524 format = esl_sqio_EncodeFormat(esl_opt_GetString(go, "--format"));
1525 if (format == eslSQFILE_UNKNOWN) esl_fatal("unrecognized database format %s\n", esl_opt_GetString(go, "--format"));
1526 }
1527
1528 if (esl_opt_GetBoolean(go, "-d"))
1529 {
1530 if (esl_opt_GetBoolean(go, "--amino")) abc = esl_alphabet_Create(eslAMINO);
1531 else abc = esl_alphabet_Create(eslDNA);
1532 sq = esl_sq_CreateDigital(abc);
1533 if (esl_sqfile_OpenDigital(abc, filename, format, NULL, &sqfp) != eslOK) esl_fatal("failed to open %s", filename);
1534 }
1535 else
1536 {
1537 sq = esl_sq_Create();
1538 if (esl_sqfile_Open(filename, format, NULL, &sqfp) != eslOK) esl_fatal("failed to open %s", filename);
1539 }
1540
1541
1542 /* It's useful to have some baselines of just reading the file without parsing;
1543 * POSIX read(); C fread(); C fgets(); and POSIX mmap().
1544 * Counting a's (<na>) is just to keep the optimizer from optimizing the
1545 * benchmark away.
1546 */
1547 esl_stopwatch_Start(w); benchmark_read (filename, bufsize, &magic); esl_stopwatch_Stop(w); printf("magic=%" PRId64 "; ", magic); esl_stopwatch_Display(stdout, w, "read(): ");
1548 esl_stopwatch_Start(w); benchmark_fread(filename, bufsize, &magic); esl_stopwatch_Stop(w); printf("magic=%" PRId64 "; ", magic); esl_stopwatch_Display(stdout, w, "fread(): ");
1549 esl_stopwatch_Start(w); benchmark_fgets(filename, bufsize, &magic); esl_stopwatch_Stop(w); printf("magic=%" PRId64 "; ", magic); esl_stopwatch_Display(stdout, w, "fgets(): ");
1550 /* esl_stopwatch_Start(w); benchmark_mmap (filename, bufsize, &magic); esl_stopwatch_Stop(w); printf("magic=%" PRId64 "; ", magic); esl_stopwatch_Display(stdout, w, "mmap(): "); */
1551
1552 esl_stopwatch_Start(w);
1553 if (esl_opt_GetBoolean(go, "-i"))
1554 {
1555 while (esl_sqio_ReadInfo(sqfp, sq) == eslOK) { n++; nr += sq->L; esl_sq_Reuse(sq); }
1556 }
1557 else if (esl_opt_GetBoolean(go, "-s"))
1558 {
1559 while (esl_sqio_ReadSequence(sqfp, sq) == eslOK) { n++; nr += sq->L; esl_sq_Reuse(sq); }
1560 }
1561 else if (esl_opt_GetBoolean(go, "-w"))
1562 {
1563 int wstatus;
1564 while ((wstatus = esl_sqio_ReadWindow(sqfp, C, W, sq)) != eslEOF)
1565 {
1566 if (wstatus == eslEOD) {
1567 if (!do_crick || W < 0) { n++; esl_sq_Reuse(sq); }
1568 if (do_crick) { W = -W; }
1569 continue;
1570 } else if (wstatus != eslOK) esl_fatal("Error: %s", esl_sqfile_GetErrorBuf(sqfp));
1571 nr += sq->W;
1572 }
1573 }
1574 else
1575 {
1576 while (esl_sqio_Read(sqfp, sq) == eslOK) { n++; nr += sq->L; esl_sq_Reuse(sq); }
1577 }
1578 esl_stopwatch_Stop(w);
1579 esl_stopwatch_Display(stdout, w, "sqio: ");
1580 printf("Read %d sequences; %lld residues.\n", n, (long long int) nr);
1581
1582 if (sqfp->format == eslSQFILE_NCBI)
1583 printf(" DB %d sequences; %lld residues.\n", sqfp->data.ncbi.num_seq, (long long int) sqfp->data.ncbi.total_res);
1584
1585 esl_sqfile_Close(sqfp);
1586 esl_sq_Destroy(sq);
1587 esl_stopwatch_Destroy(w);
1588 esl_alphabet_Destroy(abc);
1589 esl_getopts_Destroy(go);
1590 return 0;
1591 }
1592
1593 static int
1594 benchmark_read(char *filename, int bufsize, int64_t *ret_magic)
1595 {
1596 char *buf = malloc(sizeof(char) * bufsize);
1597 int fd = open(filename, O_RDONLY);
1598 int n;
1599 int64_t magic = 0;
1600 int pos;
1601
1602 if (fd != -1)
1603 {
1604 while ( (n = read(fd, buf, bufsize)) > 0)
1605 {
1606 for (pos = 0; pos < n; pos++) magic += buf[pos];
1607 }
1608 close(fd);
1609 }
1610
1611 free(buf);
1612 *ret_magic = magic;
1613 return eslOK;
1614 }
1615
1616 static int
1617 benchmark_fread(char *filename, int bufsize, int64_t *ret_magic)
1618 {
1619 FILE *fp = fopen(filename, "r");
1620 char *buf = malloc(sizeof(char) * bufsize);
1621 int64_t magic = 0;
1622 int pos;
1623 int n;
1624
1625 if (fp != NULL)
1626 {
1627 while ( (n = fread(buf, sizeof(char), bufsize, fp)) > 0)
1628 {
1629 for (pos = 0; pos < n; pos++) magic += buf[pos];
1630 }
1631 fclose(fp);
1632 }
1633
1634 free(buf);
1635 *ret_magic = magic;
1636 return eslOK;
1637 }
1638
1639
1640 static int
1641 benchmark_fgets(char *filename, int bufsize, int64_t *ret_magic)
1642 {
1643 FILE *fp = fopen(filename, "r");
1644 char *buf = malloc(sizeof(char) * bufsize);
1645 int64_t magic = 0;
1646 char *s;
1647
1648 if (fp != NULL)
1649 {
1650 while ( fgets(buf, bufsize, fp) != NULL)
1651 {
1652 for (s = buf; *s; s++) magic += *s;
1653 }
1654 fclose(fp);
1655 }
1656
1657 free(buf);
1658 *ret_magic = magic;
1659 return eslOK;
1660 }
1661
1662
1663 #if 0
1664 /* we can't use mmap anyway; we have to be able to read from streams
1665 * and pipes.
1666 */
1667 static int
1668 benchmark_mmap(char *filename, int bufsize, int64_t *ret_magic)
1669 {
1670 int fd = open(filename, O_RDONLY);
1671 struct stat statbuf;
1672 char *p;
1673 uint64_t pos;
1674 uint64_t magic = 0;
1675
1676 fstat(fd, &statbuf);
1677 p = mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
1678 for (pos = 0; pos < statbuf.st_size; pos++)
1679 magic += p[pos];
1680
1681 close(fd);
1682 *ret_magic = magic;
1683 return eslOK;
1684 }
1685 #endif
1686
1687
1688 #endif /*eslSQIO_BENCHMARK*/
1689 /*------------------ end of benchmark ---------------------------*/
1690
1691
1692
1693 /*****************************************************************
1694 *# 10. Unit tests
1695 *****************************************************************/
1696 #ifdef eslSQIO_TESTDRIVE
1697 #include "esl_keyhash.h"
1698 #include "esl_random.h"
1699 #include "esl_randomseq.h"
1700 #include "esl_vectorops.h"
1701
1702 static void
1703 synthesize_testseqs(ESL_RANDOMNESS *r, ESL_ALPHABET *abc, int maxL, int N, ESL_SQ ***ret_sqarr)
1704 {
1705 ESL_SQ **sqarr = malloc(sizeof(ESL_SQ *) * N);
1706 ESL_KEYHASH *kh = esl_keyhash_Create();
1707 float *fq = malloc(sizeof(float) * abc->Kp);
1708 char *buf = NULL;
1709 int maxn = eslSQ_NAMECHUNK*2;
1710 int maxa = eslSQ_ACCCHUNK*2;
1711 int maxd = eslSQ_DESCCHUNK*2;
1712 char ascii[128];
1713 float af[128];
1714 int i, pos;
1715 int n;
1716 int x;
1717
1718 n = ESL_MAX( maxn, ESL_MAX(maxa, maxd));
1719 buf = malloc(sizeof(char) * (n+1));
1720
1721 /* Set a residue frequency vector that's going to sample degenerate residues too */
1722 esl_vec_FSet(fq, abc->Kp, 0.0);
1723 esl_vec_FSet(fq, abc->K, 0.9 / (float) abc->K);
1724 esl_vec_FSet(fq + abc->K + 1, abc->Kp - abc->K - 2, 0.1 / (float) (abc->Kp - abc->K - 2));
1725
1726 /* Set an ASCII frequency vector that'll sample all nonspace chars */
1727 for (x = 0; x < 128; x++) {
1728 ascii[x] = (char) x;
1729 if (isalpha(x)) af[x] = 3.0;
1730 else if (isdigit(x)) af[x] = 2.0;
1731 else if (ispunct(x) && x != '%') af[x] = 1.0; /* disallow %; it'll screw up printf()-like Set calls */
1732 else af[x] = 0.0;
1733 }
1734 esl_vec_FNorm(af, 128);
1735
1736 for (i = 0; i < N; i++)
1737 {
1738 if ((sqarr[i] = esl_sq_CreateDigital(abc)) == NULL) esl_fatal("failed to allocate seq %d", i);
1739
1740 do {
1741 n = esl_rnd_Roll(r, maxn) + 1; /* 1..maxn */
1742 esl_rsq_fIID(r, ascii, af, 128, n, buf);
1743 buf[n] = '\0';
1744 } while (ispunct(buf[0]) || // #, // are bad things for names to start with, in Stockholm format
1745 esl_keyhash_Store(kh, buf, n, NULL) == eslEDUP); // Make sure names are unique.
1746 esl_sq_SetName(sqarr[i], buf);
1747
1748 if (esl_rnd_Roll(r, 2) == 0) { /* 50% chance of an accession */
1749 n = esl_rnd_Roll(r, maxa) + 1;
1750 esl_rsq_fIID(r, ascii, af, 128, n, buf);
1751 buf[n] = '\0';
1752 esl_sq_SetAccession(sqarr[i], buf);
1753 }
1754
1755 if (esl_rnd_Roll(r, 2) == 0) { /* 50% chance of a description */
1756 n = esl_rnd_Roll(r, maxd) + 1;
1757 esl_rsq_fIID(r, ascii, af, 128, n, buf);
1758 buf[n] = '\0';
1759 for (pos = 1; pos < n-1; pos++) { /* avoid first, last char, and... */
1760 if (esl_rnd_Roll(r, 10) == 0) buf[pos] = ' '; /* ...sprinkle with spaces... */
1761 if (esl_rnd_Roll(r, 100) == 0) buf[pos] = '\t'; /* ...and tabs. */
1762 }
1763 esl_sq_SetDesc(sqarr[i], buf);
1764 }
1765
1766 n = esl_rnd_Roll(r, (maxL+1)); /* choose seqlen = 0..maxL; 0 length seqs occur in real dbs */
1767 esl_sq_GrowTo(sqarr[i], n);
1768 esl_rsq_xfIID(r, fq, abc->Kp, n, sqarr[i]->dsq);
1769
1770 esl_sq_SetCoordComplete(sqarr[i], n);
1771 }
1772
1773 *ret_sqarr = sqarr;
1774 free(buf);
1775 free(fq);
1776 esl_keyhash_Destroy(kh);
1777 return;
1778 }
1779
1780 /* Write an uglified FASTA file to a stream.
1781 * Also, remember where the start of the descline and first
1782 * seq line are, in sq->{roff,doff}. We'll compare against
1783 * what the input function thinks these locations are.
1784 */
1785 static void
1786 write_ugly_fasta(ESL_RANDOMNESS *r, FILE *fp, ESL_SQ *sq)
1787 {
1788 char buf[61];
1789 int pos;
1790
1791 sq->roff = ftello(fp);
1792 fputc('>', fp);
1793 while (esl_rnd_Roll(r, 10) == 0) fputc(' ', fp);
1794 fprintf(fp, "%s", sq->name);
1795 while (esl_rnd_Roll(r, 10) == 0) fputc(' ', fp);
1796 if (sq->desc[0] != 0) fprintf(fp, " %s", sq->desc);
1797 fputc('\n', fp);
1798
1799 sq->doff = ftello(fp);
1800 buf[60] = '\0';
1801 for (pos = 1; pos <= sq->n; pos+=60)
1802 {
1803 while (esl_rnd_Roll(r, 10) == 0) fputc(' ', fp);
1804 esl_abc_TextizeN(sq->abc, sq->dsq+pos, 60, buf);
1805 fputs(buf, fp);
1806 fputc('\n', fp);
1807 }
1808 while (esl_rnd_Roll(r, 10) == 0) fputc('\n', fp);
1809
1810 sq->eoff = ftello(fp) - 1;
1811 if (sq->n == 0) sq->doff = sq->eoff+1; // Deals with an edge case, an L=0 seq with multiple newlines.
1812 }
1813
1814 static void
1815 write_spaced_fasta(FILE *fp, ESL_SQ *sq)
1816 {
1817 char buf[64];
1818 int pos;
1819
1820 sq->roff = ftello(fp);
1821 fprintf(fp, ">%s", sq->name);
1822 if (sq->desc[0] != 0) fprintf(fp, " %s", sq->desc);
1823 fputc('\n', fp);
1824
1825 sq->doff = ftello(fp);
1826 buf[10] = '\0';
1827 for (pos = 1; pos <= sq->n; pos += 10)
1828 {
1829 esl_abc_TextizeN(sq->abc, sq->dsq+pos, 10, buf);
1830 fputs(buf, fp);
1831 if (pos+9 >= sq->n || (pos+9) % 60 == 0) fputc('\n', fp);
1832 else fputc(' ', fp);
1833 }
1834 sq->eoff = ftello(fp) - 1;
1835 }
1836
1837
1838 static void
1839 make_ssi_index(ESL_ALPHABET *abc, const char *tmpfile, int format, char *ssifile, int mode)
1840 {
1841 char *msg = "sqio unit testing: failed to make SSI index";
1842 ESL_NEWSSI *ns = NULL;
1843 ESL_SQFILE *sqfp = NULL;
1844 ESL_SQ *sq = esl_sq_CreateDigital(abc);
1845 uint16_t fh = 0;
1846 int status;
1847
1848 int bpl, rpl;
1849
1850 snprintf(ssifile, 32, "%s.ssi", tmpfile); // 32 is the allocation size of ssifile, from main()
1851 if (esl_newssi_Open(ssifile, TRUE, &ns) != eslOK) esl_fatal(msg);
1852 if (esl_newssi_AddFile(ns, tmpfile, format, &fh) != eslOK) esl_fatal(msg);
1853 if (esl_sqfile_OpenDigital(abc, tmpfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
1854 while ((status = esl_sqio_ReadInfo(sqfp, sq)) == eslOK)
1855 {
1856 if (esl_newssi_AddKey(ns, sq->name, fh, sq->roff, sq->doff, sq->L) != eslOK) esl_fatal(msg);
1857 if (sq->acc[0] != '\0' && esl_newssi_AddAlias(ns, sq->acc, sq->name) != eslOK) esl_fatal(msg);
1858 esl_sq_Reuse(sq);
1859 }
1860 if (status != eslEOF) esl_fatal(msg);
1861
1862 bpl = sqfp->data.ascii.bpl;
1863 rpl = sqfp->data.ascii.rpl;
1864 if (bpl > 0 && rpl > 0)
1865 if ((status = esl_newssi_SetSubseq(ns, fh, bpl, rpl)) != eslOK) esl_fatal(msg);
1866
1867 if (esl_newssi_Write(ns) != eslOK) esl_fatal(msg);
1868
1869 bpl = sqfp->data.ascii.bpl;
1870 rpl = sqfp->data.ascii.rpl;
1871
1872 switch (mode) {
1873 case 0: if (bpl != 0) esl_fatal(msg); break; /* uglified: bpl should be invalid (rpl might not be) */
1874 case 1: if (rpl != 60 || bpl == 0) esl_fatal(msg); break; /* spaced: bpl, rpl should be valid */
1875 case 2: if (rpl != 60 || bpl != 61) esl_fatal(msg); break; /* normal: bpl, rpl should be valid, w/ bpl=rpl+1 */
1876 }
1877
1878 esl_sqfile_Close(sqfp);
1879 esl_newssi_Close(ns);
1880 esl_sq_Destroy(sq);
1881 }
1882
1883 static void
1884 utest_read(ESL_ALPHABET *abc, ESL_SQ **sqarr, int N, char *seqfile, int format, int mode)
1885 {
1886 char *msg = "sqio complete read unit test failed";
1887 ESL_SQ *sq = esl_sq_CreateDigital(abc);
1888 ESL_SQFILE *sqfp = NULL;
1889 int nseq = 0;
1890 int status;
1891
1892 int bpl, rpl;
1893
1894 if (esl_sqfile_OpenDigital(abc, seqfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
1895 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
1896 {
1897 /* FASTA doesn't preserve accessions. Copy it, as a hack, so Compare test succeeds*/
1898 if (sq->acc[0] == '\0' && esl_sq_SetAccession(sq, sqarr[nseq]->acc) != eslOK) esl_fatal(msg);
1899 if (esl_sq_Compare(sq, sqarr[nseq]) != eslOK) esl_fatal(msg);
1900 nseq++;
1901 esl_sq_Reuse(sq);
1902 }
1903 if (status != eslEOF) esl_fatal(msg);
1904 if (nseq != N) esl_fatal(msg);
1905
1906 bpl = sqfp->data.ascii.bpl;
1907 rpl = sqfp->data.ascii.rpl;
1908
1909 switch (mode) {
1910 case 0: if (bpl != 0) esl_fatal(msg); break; /* uglified: bpl should be invalid (rpl might not be) */
1911 case 1: if (rpl != 60 || bpl == 0) esl_fatal(msg); break; /* spaced: bpl, rpl should be valid */
1912 case 2: if (rpl != 60 || bpl != 61) esl_fatal(msg); break; /* normal: bpl, rpl should be valid, w/ bpl=rpl+1 */
1913 }
1914
1915 esl_sqfile_Close(sqfp);
1916 esl_sq_Destroy(sq);
1917 }
1918
1919 static void
1920 utest_read_info(ESL_ALPHABET *abc, ESL_SQ **sqarr, int N, char *seqfile, int format, int mode)
1921 {
1922 char *msg = "sqio info read unit test failed";
1923 ESL_SQ *sq = esl_sq_CreateDigital(abc);
1924 ESL_SQFILE *sqfp = NULL;
1925 int nseq = 0;
1926 int status;
1927
1928 int bpl, rpl;
1929
1930 if (esl_sqfile_OpenDigital(abc, seqfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
1931 while ((status = esl_sqio_ReadInfo(sqfp, sq)) == eslOK)
1932 {
1933 if (strcmp(sq->name, sqarr[nseq]->name) != 0) esl_fatal(msg);
1934 if (format != eslSQFILE_FASTA &&
1935 strcmp(sq->acc, sqarr[nseq]->acc) != 0) esl_fatal(msg);
1936 if (strcmp(sq->desc, sqarr[nseq]->desc) != 0) esl_fatal(msg);
1937 if (strcmp(sq->source, sqarr[nseq]->source) != 0) esl_fatal(msg);
1938 if (sq->n != 0) esl_fatal(msg);
1939 if (sq->start != 0) esl_fatal(msg);
1940 if (sq->end != 0) esl_fatal(msg);
1941 if (sq->C != 0) esl_fatal(msg);
1942 if (sq->W != 0) esl_fatal(msg);
1943 if (sq->L != sqarr[nseq]->L) esl_fatal(msg);
1944 if (sq->roff != -1 && sqarr[nseq]->roff != -1 && sq->roff != sqarr[nseq]->roff) esl_fatal(msg);
1945 if (sq->doff != -1 && sqarr[nseq]->doff != -1 && sq->doff != sqarr[nseq]->doff) esl_fatal(msg);
1946
1947 nseq++;
1948 esl_sq_Reuse(sq);
1949 }
1950 if (status != eslEOF) esl_fatal(msg);
1951 if (nseq != N) esl_fatal(msg);
1952
1953 bpl = sqfp->data.ascii.bpl;
1954 rpl = sqfp->data.ascii.rpl;
1955
1956 switch (mode) {
1957 case 0: if (bpl != 0) esl_fatal(msg); break; /* uglified: bpl should be invalid (rpl might not be) */
1958 case 1: if (rpl != 60 || bpl == 0) esl_fatal(msg); break; /* spaced: bpl, rpl should be valid */
1959 case 2: if (rpl != 60 || bpl != 61) esl_fatal(msg); break; /* normal: bpl, rpl should be valid, w/ bpl=rpl+1 */
1960 }
1961
1962 esl_sqfile_Close(sqfp);
1963 esl_sq_Destroy(sq);
1964 }
1965
1966 static void
1967 utest_read_window(ESL_ALPHABET *abc, ESL_SQ **sqarr, int N, char *seqfile, int format, int mode)
1968 {
1969 char *msg = "sqio window read unit test failed";
1970 ESL_SQ *sq = esl_sq_CreateDigital(abc);
1971 ESL_SQ *rev = esl_sq_CreateDigital(abc);
1972 ESL_SQFILE *sqfp = NULL;
1973 int nseq = 0;
1974 int C = 10;
1975 int W = 50;
1976 int nres = 0;
1977 int wstatus;
1978
1979 int bpl, rpl, L;
1980
1981 if (esl_sqfile_OpenDigital(abc, seqfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
1982 while ((wstatus = esl_sqio_ReadWindow(sqfp, C, W, sq)) == eslOK || wstatus == eslEOD)
1983 {
1984 if (wstatus == eslEOD) {
1985 if (W < 0) {
1986 nseq++;
1987 nres = 0;
1988 W = -W;
1989 esl_sq_Reuse(sq);
1990 esl_sq_Reuse(rev);
1991 } else {
1992 /* reverse complement */
1993 nres = 0;
1994 W = -W;
1995 esl_sq_Copy(sqarr[nseq], rev);
1996 esl_sq_ReverseComplement(rev);
1997 }
1998 continue;
1999 }
2000
2001 nres += sq->W;
2002 if (strcmp(sq->name, sqarr[nseq]->name) != 0) esl_fatal(msg);
2003 if (format != eslSQFILE_FASTA &&
2004 strcmp(sq->acc, sqarr[nseq]->acc) != 0) esl_fatal(msg);
2005 if (strcmp(sq->desc, sqarr[nseq]->desc) != 0) esl_fatal(msg);
2006
2007 L = sqfp->data.ascii.L;
2008
2009 if (W > 0) {
2010 /* Forward strand coord checks */
2011 if (L != nres) esl_fatal(msg);
2012 if (sq->start != nres - sq->n + 1) esl_fatal(msg);
2013 if (sq->end != nres) esl_fatal(msg);
2014 if (sq->C != 0 && sq->C != C) esl_fatal(msg);
2015 if (sq->n != sq->C+sq->W) esl_fatal(msg);
2016 if (sq->start+sq->n-1 > sqarr[nseq]->L) esl_fatal(msg);
2017 if (wstatus == eslEOD && sq->L != L) esl_fatal(msg);
2018 if (memcmp(sq->dsq + 1, sqarr[nseq]->dsq + sq->start, sq->C+sq->W) != 0) esl_fatal(msg);
2019 } else {
2020 /* Reverse strand coord checks */
2021 if (L != -1) esl_fatal(msg);
2022 if (sq->start != sq->L - nres + sq->W + sq->C) esl_fatal(msg);
2023 if (sq->end != sq->L - nres + 1) esl_fatal(msg);
2024 if (sq->C != 0 && sq->C != C) esl_fatal(msg);
2025 if (sq->start-sq->n+1 < 1) esl_fatal(msg);
2026 if (wstatus == eslEOD && sq->end != 1) esl_fatal(msg);
2027 if (memcmp(sq->dsq + 1, rev->dsq + (sq->L - sq->start + 1), sq->C+sq->W) != 0) esl_fatal(msg);
2028 }
2029 }
2030
2031 bpl = sqfp->data.ascii.bpl;
2032 rpl = sqfp->data.ascii.rpl;
2033
2034 switch (mode) {
2035 case 0: if (bpl != 0) esl_fatal(msg); break; /* uglified: bpl should be invalid (rpl might not be) */
2036 case 1: if (rpl != 60 || bpl == 0) esl_fatal(msg); break; /* spaced: bpl, rpl should be valid */
2037 case 2: if (rpl != 60 || bpl != 61) esl_fatal(msg); break; /* normal: bpl, rpl should be valid, w/ bpl=rpl+1 */
2038 }
2039
2040 if (wstatus != eslEOF) esl_fatal(msg);
2041 if (nseq != N) esl_fatal(msg);
2042 esl_sqfile_Close(sqfp);
2043 esl_sq_Destroy(rev);
2044 esl_sq_Destroy(sq);
2045 }
2046
2047 static void
2048 utest_fetch_subseq(ESL_RANDOMNESS *r, ESL_ALPHABET *abc, ESL_SQ **sqarr, int N, char *seqfile, char *ssifile, int format)
2049 {
2050 char *msg = "sqio subseq read unit test failure";
2051 ESL_SQ *sq = esl_sq_CreateDigital(abc);
2052 ESL_SQFILE *sqfp = NULL;
2053 int i;
2054 int ntest = 32;
2055 char *source;
2056 int start;
2057 int end;
2058
2059 if (esl_sqfile_OpenDigital(abc, seqfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
2060 if (esl_sqfile_OpenSSI(sqfp, ssifile) != eslOK) esl_fatal(msg);
2061 while (ntest--)
2062 {
2063 i = esl_rnd_Roll(r, N);
2064 source = sqarr[i]->name;
2065 if (sqarr[i]->L == 0) continue; // Don't try to fetch from empty sequences.
2066
2067 do {
2068 start = esl_rnd_Roll(r, sqarr[i]->n) + 1;
2069 end = esl_rnd_Roll(r, sqarr[i]->n) + 1;
2070 } while (start > end);
2071
2072 if (esl_sqio_FetchSubseq(sqfp, source, start, end, sq) != eslOK) esl_fatal(msg);
2073 if (memcmp(&(sqarr[i]->dsq[start]), &sq->dsq[1], end-start+1) != 0) esl_fatal(msg);
2074
2075 esl_sq_Reuse(sq);
2076 }
2077
2078 esl_sqfile_Close(sqfp);
2079 esl_sq_Destroy(sq);
2080 }
2081
2082
2083 /* Write the sequences out to a tmpfile in chosen <format>;
2084 * read them back and make sure they're the same.
2085 * reposition to beginning, read and check again.
2086 *
2087 * The sequences in <sqarr> are in digital mode.
2088 */
2089 static void
2090 utest_write(ESL_ALPHABET *abc, ESL_SQ **sqarr, int N, int format)
2091 {
2092 char *msg = "sqio write unit test failure";
2093 char tmpfile[32] = "esltmpXXXXXX";
2094 ESL_SQFILE *sqfp = NULL;
2095 ESL_SQ *sq = esl_sq_CreateDigital(abc);
2096 FILE *fp = NULL;
2097 int iterations = 2; /* 2: reposition and read again */
2098 int i;
2099 int require_nonzero_length = FALSE;
2100
2101 if (esl_sqio_IsAlignment(format)) require_nonzero_length = TRUE;
2102
2103 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2104 for (i = 0; i < N; i++)
2105 if (! require_nonzero_length || sqarr[i]->L > 0)
2106 esl_sqio_Write(fp, sqarr[i], format, FALSE);
2107 fclose(fp);
2108
2109 if (esl_sqfile_OpenDigital(abc, tmpfile, format, NULL, &sqfp) != eslOK) esl_fatal(msg);
2110 while (iterations--)
2111 {
2112 for (i = 0; i < N; i++)
2113 {
2114 if (require_nonzero_length && sqarr[i]->L == 0) continue;
2115 if (esl_sqio_Read(sqfp, sq) != eslOK) esl_fatal(msg);
2116 if (strcmp(sqarr[i]->name, sq->name) != 0) esl_fatal(msg);
2117 if (sqarr[i]->L != sq->L) esl_fatal(msg);
2118 if (memcmp(sqarr[i]->dsq, sq->dsq, sizeof(ESL_DSQ) * (sq->L+2)) != 0) esl_fatal(msg);
2119 esl_sq_Reuse(sq);
2120 }
2121 esl_sqfile_Position(sqfp, 0); /* rewind and make sure we get same reads again */
2122 }
2123 esl_sqfile_Close(sqfp);
2124 esl_sq_Destroy(sq);
2125 remove(tmpfile);
2126 }
2127
2128
2129 /* utest_guess_mechanics()
2130 * SRE H3/70, 8 Apr 17
2131 *
2132 * Related to EPN bugfix a61ee23: esl_sqfile_GuessAlphabet() segfaults
2133 * when file contains 1 seq, file is >4096 bytes, seq is <4000
2134 * residues, because of a fault in the mechanics of sqio with
2135 * is_recording TRUE and is_linebased FALSE.
2136 *
2137 * This unit test exercises those mechanics, the original bug and
2138 * more. It is *not* testing GuessAlphabet() itself. The DNA sequences
2139 * in <sqarr> are so dirty, their alphabet cannot be reliably
2140 * detected. This unit test is hunting segfaults, not even looking at
2141 * the return status of _GuessAlphabet().
2142 */
2143 static void
2144 utest_guess_mechanics(ESL_ALPHABET *abc, ESL_SQ **sqarr, int N)
2145 {
2146 char *msg = "sqio guess_mechanics unit test failure";
2147 char tmpfile[32];
2148 FILE *fp;
2149 ESL_SQFILE *sqfp;
2150 int i;
2151 int alphatype;
2152
2153 for (i = 0; i < N; i++) // for each individual sequence in <sqarr>, one at a time:
2154 {
2155 strcpy(tmpfile, "esltmpXXXXXX");
2156 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2157 if (esl_sqio_Write(fp, sqarr[i], eslSQFILE_FASTA, FALSE) != eslOK) esl_fatal(msg);
2158 fclose(fp);
2159
2160 if (esl_sqfile_Open(tmpfile, eslSQFILE_FASTA, NULL, &sqfp) != eslOK) esl_fatal(msg);
2161
2162 esl_sqfile_GuessAlphabet(sqfp, &alphatype);
2163 // generally, the sequences are so dirty, GuessAlphabet() won't make a guess.
2164 // we're hunting segfaults in this utest.
2165
2166 esl_sqfile_Close(sqfp);
2167 remove(tmpfile);
2168 }
2169 }
2170
2171 /* utest_guess_empty_seq()
2172 * ML, 9 Oct 21
2173 *
2174 * Make sure that esl_sqfile_GuessAlphabet() returns eslNOALPHABET when
2175 * it tries to guess the alphabet on files containing only empty sequences.
2176 *
2177 * Related to bugfix 441a4d3: sqascii_GuessAlphabet() did not handle
2178 * the case where sqascii_ReadWindow() would return eslEOD on empty
2179 * sequences, and returned an error instead of eslENOALPHABET.
2180 */
2181 static void
2182 utest_guess_empty_seq()
2183 {
2184 char *msg = "sqio guess_empty_seq unit test failure";
2185 char tmpfile[32];
2186 ESL_SQ* seqs[2];
2187 FILE *fp;
2188 ESL_SQFILE *sqfp;
2189 int alphatype;
2190
2191 if ((seqs[0] = esl_sq_CreateFrom("seqs0", "", NULL, NULL, NULL)) == NULL) esl_fatal(msg);
2192 if ((seqs[1] = esl_sq_CreateFrom("seqs1", "", NULL, NULL, NULL)) == NULL) esl_fatal(msg);
2193
2194 strcpy(tmpfile, "esltmpXXXXXX");
2195 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal(msg);
2196 if (esl_sqio_Write(fp, seqs[0], eslSQFILE_FASTA, FALSE) != eslOK) esl_fatal(msg);
2197 if (esl_sqio_Write(fp, seqs[1], eslSQFILE_FASTA, FALSE) != eslOK) esl_fatal(msg);
2198 fclose(fp);
2199
2200 if (esl_sqfile_Open(tmpfile, eslSQFILE_FASTA, NULL, &sqfp) != eslOK) esl_fatal(msg);
2201 if (esl_sqfile_GuessAlphabet(sqfp, &alphatype) != eslENOALPHABET) esl_fatal(msg);
2202 esl_sqfile_Close(sqfp);
2203 remove(tmpfile);
2204
2205 esl_sq_Destroy(seqs[0]);
2206 esl_sq_Destroy(seqs[1]);
2207 }
2208
2209 #endif /*eslSQIO_TESTDRIVE*/
2210 /*------------------ end, unit tests ----------------------------*/
2211
2212
2213
2214 /*****************************************************************
2215 *# 11. Test driver.
2216 *****************************************************************/
2217
2218 /* gcc -g -Wall -I. -L. -o sqio_utest -DeslSQIO_TESTDRIVE esl_sqio.c -leasel -lm
2219 * ./sqio_utest
2220 */
2221 #ifdef eslSQIO_TESTDRIVE
2222 #include <esl_config.h>
2223
2224 #include <stdlib.h>
2225 #include <stdio.h>
2226 #include <string.h>
2227
2228 #include "easel.h"
2229 #include "esl_getopts.h"
2230 #include "esl_random.h"
2231 #include "esl_randomseq.h"
2232 #include "esl_sq.h"
2233 #include "esl_sqio.h"
2234
2235 static ESL_OPTIONS options[] = {
2236 /* name type default env range toggles reqs incomp help docgroup*/
2237 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
2238 { "-L", eslARG_INT, "8000", NULL, NULL, NULL, NULL, NULL, "max length of test sequences", 0 },
2239 { "-N", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "number of test sequences", 0 },
2240 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
2241 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2242 };
2243 static char usage[] = "[-options]";
2244 static char banner[] = "test driver for sqio module";
2245
2246 int
2247 main(int argc, char **argv)
2248 {
2249 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
2250 ESL_ALPHABET *abc = esl_alphabet_Create(eslDNA); /* DNA because some chars aren't legal in IUPAC DNA */
2251 ESL_RANDOMNESS *r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
2252 ESL_SQ **sqarr = NULL;
2253 int maxL = esl_opt_GetInteger(go, "-L");
2254 int N = esl_opt_GetInteger(go, "-N");
2255 int i;
2256 int mode;
2257 char tmpfile[32];
2258 char ssifile[32];
2259 FILE *fp = NULL;
2260 char c;
2261
2262 fprintf(stderr, "## %s\n", argv[0]);
2263 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(r));
2264
2265 /* Create an array of sequences we'll use for all the tests */
2266 synthesize_testseqs(r, abc, maxL, N, &sqarr);
2267
2268 for (mode = 0; mode < 3; mode++) /* 0=ugly 1=spaced 2=normal*/
2269 {
2270 /* Write FASTA file to disk, and SSI index it */
2271 strcpy(tmpfile, "esltmpXXXXXX");
2272 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal("failed to make tmpfile");
2273 switch (mode) {
2274 case 0: for (i = 0; i < N; i++) write_ugly_fasta(r, fp, sqarr[i]); break;
2275 case 1: for (i = 0; i < N; i++) write_spaced_fasta(fp, sqarr[i]); break;
2276 case 2:
2277 for (i = 0; i < N; i++) {
2278 c = sqarr[i]->acc[0]; /* hack: hide the accession, so digital writer doesn't write it. */
2279 sqarr[i]->acc[0] = '\0';
2280 esl_sqio_Write(fp, sqarr[i], eslSQFILE_FASTA, TRUE);
2281 sqarr[i]->acc[0] = c;
2282 }
2283 break;
2284 }
2285 fclose(fp);
2286 make_ssi_index(abc, tmpfile, eslSQFILE_FASTA, ssifile, mode);
2287
2288 utest_read (abc, sqarr, N, tmpfile, eslSQFILE_FASTA, mode);
2289 utest_read_info (abc, sqarr, N, tmpfile, eslSQFILE_FASTA, mode);
2290 utest_read_window (abc, sqarr, N, tmpfile, eslSQFILE_FASTA, mode);
2291 utest_fetch_subseq(r, abc, sqarr, N, tmpfile, ssifile, eslSQFILE_FASTA);
2292
2293 remove(tmpfile);
2294 remove(ssifile);
2295 }
2296
2297 utest_guess_mechanics(abc, sqarr, N);
2298 utest_write (abc, sqarr, N, eslMSAFILE_STOCKHOLM);
2299 utest_guess_empty_seq();
2300
2301 for (i = 0; i < N; i++) esl_sq_Destroy(sqarr[i]);
2302 free(sqarr);
2303 esl_randomness_Destroy(r);
2304 esl_alphabet_Destroy(abc);
2305 esl_getopts_Destroy(go);
2306
2307 fprintf(stderr, "# status = ok\n");
2308 return 0;
2309 }
2310 #endif /*eslSQIO_TESTDRIVE*/
2311 /*------------------ end, test driver ---------------------------*/
2312
2313
2314
2315 /*****************************************************************
2316 *# 12. Examples
2317 *****************************************************************/
2318 /* The last example in a file is always the most useful example;
2319 * so you can M-> to it immediately.
2320 * example3 = using esl_sqio_Parse()
2321 * example2 = simplest, text mode
2322 * example = standard idiom for digital seqfile reading
2323 */
2324
2325
2326 #ifdef eslSQIO_EXAMPLE3
2327 /*::cexcerpt::sqio_example_parse::begin::*/
2328 /* Example of using esl_sqio_Parse() to parse a buffer
2329 * cc -g -Wall -I. -L. -o esl_sqio_example3 -DeslSQIO_EXAMPLE3 esl_sqio.c -leasel -lm
2330 * ./esl_sqio_example3
2331 */
2332 #include "easel.h"
2333 #include "esl_alphabet.h"
2334 #include "esl_sq.h"
2335 #include "esl_sqio.h"
2336
2337 int
2338 main(void)
2339 {
2340 ESL_ALPHABET *abc = NULL;
2341 ESL_SQ *sq = NULL;
2342 int format = eslSQFILE_FASTA;
2343 int alphatype = eslAMINO;
2344 int status;
2345
2346 char *test = ">12345 TEST Test fasta buffer\n"
2347 "ARVAPVALPSACAPAGTQCLISGWGNTLSNGVNNPDLLQCVDAPVLSQADCEAAYPGEIT\n"
2348 "SSMICVGFLEGGKDSCQGDSGGPVVCNGQLQGIVSWGYGCALPDNPGVYTKVCNFVGWIQ\n"
2349 "DTIAAN";
2350
2351 abc = esl_alphabet_Create(alphatype);
2352 sq = esl_sq_CreateDigital(abc);
2353
2354 status = esl_sqio_Parse(test, strlen(test), sq, format);
2355 if (status == eslEFORMAT) esl_fatal("Parse failed, invalid format");
2356 else if (status != eslOK) esl_fatal("Unexpected error %d", status);
2357
2358 esl_sq_Destroy(sq);
2359 esl_alphabet_Destroy(abc);
2360 return 0;
2361 }
2362 /*::cexcerpt::sqio_example_parse::end::*/
2363 #endif /*eslSQIO_EXAMPLE3*/
2364
2365
2366 #ifdef eslSQIO_EXAMPLE2
2367 /*::cexcerpt::sqio_example_text::begin::*/
2368 /* cc -g -Wall -I. -L. -o esl_sqio_example2 -DeslSQIO_EXAMPLE2 esl_sqio.c -leasel -lm
2369 * ./esl_sqio_example2 <FASTA file>
2370 */
2371 #include "easel.h"
2372 #include "esl_sq.h"
2373 #include "esl_sqio.h"
2374
2375 int
2376 main(int argc, char **argv)
2377 {
2378 ESL_SQ *sq = esl_sq_Create();
2379 ESL_SQFILE *sqfp;
2380 int format = eslSQFILE_FASTA;
2381 char *seqfile = argv[1];
2382 int status;
2383
2384 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
2385 if (status == eslENOTFOUND) esl_fatal("No such file.");
2386 else if (status == eslEFORMAT) esl_fatal("Format unrecognized.");
2387 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
2388
2389 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
2390 { /* use each sequence for whatever you want */
2391 printf("%-40s length: %8ld desclen: %lu\n", sq->name, (long) sq->L, (unsigned long) strlen(sq->desc));
2392 esl_sq_Reuse(sq);
2393 }
2394 if (status == eslEFORMAT) esl_fatal("Parse failed\n %s", esl_sqfile_GetErrorBuf(sqfp));
2395 else if (status != eslEOF) esl_fatal("Unexpected read error %d", status);
2396
2397 esl_sq_Destroy(sq);
2398 esl_sqfile_Close(sqfp);
2399 return 0;
2400 }
2401 /*::cexcerpt::sqio_example_text::end::*/
2402 #endif /*eslSQIO_EXAMPLE2*/
2403
2404
2405
2406
2407 #ifdef eslSQIO_EXAMPLE
2408 /*::cexcerpt::sqio_example_digital::begin::*/
2409 /* Example showing standard idiom for opening sequence file, digital mode.
2410 * cc -g -Wall -I. -L. -o esl_sqio_example -DeslSQIO_EXAMPLE esl_sqio.c -leasel -lm
2411 * ./esl_sqio_example <sequence file>
2412 */
2413 #include "easel.h"
2414 #include "esl_alphabet.h"
2415 #include "esl_getopts.h"
2416 #include "esl_sq.h"
2417 #include "esl_sqio.h"
2418
2419 static ESL_OPTIONS options[] = {
2420 /* name type default env range toggles reqs incomp help docgroup */
2421 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help", 0 },
2422 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use DNA alphabet", 0 },
2423 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use RNA alphabet", 0 },
2424 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use amino alphabet", 0 },
2425 { "--informat", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "set input format", 0 },
2426 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
2427 };
2428 static char usage[] = "[-options] <seqfile>";
2429 static char banner[] = "example of reading in standard sqio idiom, digital mode";
2430
2431 int
2432 main(int argc, char **argv)
2433 {
2434 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
2435 char *seqfile = esl_opt_GetArg(go, 1);
2436 ESL_ALPHABET *abc = NULL;
2437 ESL_SQ *sq = NULL;
2438 ESL_SQFILE *sqfp = NULL;
2439 int infmt = eslSQFILE_UNKNOWN;
2440 int alphatype = eslUNKNOWN;
2441 int status;
2442
2443 if (esl_opt_IsOn(go, "--informat")) {
2444 if ((infmt = esl_sqio_EncodeFormat(esl_opt_GetString(go, "--informat")))==eslSQFILE_UNKNOWN)
2445 esl_fatal("%s is not a valid input sequence file format for --informat");
2446 }
2447
2448 status = esl_sqfile_Open(seqfile, infmt, NULL, &sqfp);
2449 if (status == eslENOTFOUND) esl_fatal("No such file.");
2450 else if (status == eslEFORMAT) esl_fatal("Format couldn't be determined.");
2451 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
2452
2453 if (esl_opt_GetBoolean(go, "--rna")) alphatype = eslRNA;
2454 else if (esl_opt_GetBoolean(go, "--dna")) alphatype = eslDNA;
2455 else if (esl_opt_GetBoolean(go, "--amino")) alphatype = eslAMINO;
2456 else {
2457 status = esl_sqfile_GuessAlphabet(sqfp, &alphatype);
2458 if (status == eslENOALPHABET) esl_fatal("Couldn't guess alphabet");
2459 else if (status == eslEFORMAT) esl_fatal("Parse failed\n %s",
2460 esl_sqfile_GetErrorBuf(sqfp));
2461 else if (status == eslENODATA) esl_fatal("Sequence file empty?");
2462 else if (status != eslOK) esl_fatal("Unexpected error guessing alphabet");
2463 }
2464 abc = esl_alphabet_Create(alphatype);
2465 sq = esl_sq_CreateDigital(abc);
2466 esl_sqfile_SetDigital(sqfp, abc);
2467
2468 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
2469 {
2470 esl_sqio_Write(stdout, sq, eslSQFILE_FASTA, /*update=*/FALSE);
2471 esl_sq_Reuse(sq);
2472 }
2473 if (status == eslEFORMAT) esl_fatal("Parse failed\n %s", esl_sqfile_GetErrorBuf(sqfp));
2474 else if (status != eslEOF) esl_fatal("Unexpected error %d in reading", status);
2475
2476 esl_sqfile_Close(sqfp);
2477 esl_sq_Destroy(sq);
2478 esl_alphabet_Destroy(abc);
2479 esl_getopts_Destroy(go);
2480 return 0;
2481 }
2482 /*::cexcerpt::sqio_example_digital::end::*/
2483 #endif /*eslSQIO_EXAMPLE*/
2484
2485