Debian Codegraph @

hmmer/easel/esl_dsqdata.c

raw symbols SCIP
1 /* esl_dsqdata : faster sequence input
2 *
3 * Implements a predigitized binary file format for biological
4 * sequences. Sequence data are packed bitwise into 32-bit packets,
5 * where each packet contains either six 5-bit residues or fifteen
6 * 2-bit residues, plus two control bits. Input is asynchronous,
7 * using POSIX threads, with a "loader" thread doing disk reads and
8 * "unpacker" thread(s) preparing chunks of sequences for
9 * analysis. Sequence data and metadata are stored in separate files,
10 * which may allow further input acceleration by deferring
11 * metadata accesses until they're actually needed.
12 *
13 * All thread synchronization is handled internally. A caller does not
14 * need to worry about the internal parallelism; it just calls
15 * <esl_dsqdata_Read()>. Caller can create multiple threads, each
16 * calling <esl_dsqdata_Read()>.
17 *
18 * A DSQDATA database <basename> is stored in four files:
19 * - basename : a human-readable stub
20 * - basename.dsqi : index file, enabling random access & parallel chunking
21 * - basename.dsqm : metadata including names, accessions, descs, taxonomy
22 * - basename.dsqs : sequences, in a packed binary format
23 *
24 * Contents:
25 * 1. ESL_DSQDATA: reading dsqdata format
26 * 2. Creating dsqdata format from a sequence file
27 * 3. ESL_DSQDATA_CHUNK, a chunk of input sequence data
28 * 4. Loader and unpacker, the input threads
29 * 5. Packing sequences and unpacking chunks
30 * 6. Notes and references
31 * 7. Unit tests
32 * 8. Test driver
33 * 9. Examples
34 */
35 #include <esl_config.h>
36
37 #include <stdio.h>
38 #include <string.h>
39 #include <stdint.h>
40 #include <pthread.h>
41
42 #include "easel.h"
43 #include "esl_alphabet.h"
44 #include "esl_random.h"
45 #include "esl_sq.h"
46 #include "esl_sqio.h"
47
48 #include "esl_dsqdata.h"
49
50 static ESL_DSQDATA_CHUNK *dsqdata_chunk_Create (ESL_DSQDATA *dd);
51 static void dsqdata_chunk_Destroy(ESL_DSQDATA_CHUNK *chu);
52
53 static void *dsqdata_loader_thread (void *p);
54 static void *dsqdata_unpacker_thread(void *p);
55
56 static int dsqdata_unpack_chunk(ESL_DSQDATA_CHUNK *chu, int do_pack5);
57 static int dsqdata_unpack5(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P);
58 static int dsqdata_unpack2(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P);
59 static int dsqdata_pack5 (ESL_DSQ *dsq, int L, uint32_t *psq, int *ret_P);
60 static int dsqdata_pack2 (ESL_DSQ *dsq, int L, uint32_t *psq, int *ret_P);
61
62
63 /* Embedded magic numbers allow us to validate the correct binary
64 * format, with version (if needed in the future), and to detect
65 * byteswapping.
66 */
67 static uint32_t eslDSQDATA_MAGIC_V1 = 0xc4d3d1b1; // "dsq1" + 0x80808080
68 static uint32_t eslDSQDATA_MAGIC_V1SWAP = 0xb1d1d3c4; // ... as above, but byteswapped.
69
70 /*****************************************************************
71 *# 1. <ESL_DSQDATA>: reading dsqdata format
72 *****************************************************************/
73
74 /* Function: esl_dsqdata_Open()
75 * Synopsis: Open a digital sequence database for reading
76 * Incept: SRE, Wed Jan 20 09:50:00 2016 [Amtrak 2150, NYP-BOS]
77 *
78 * Purpose: Open dsqdata database <basename> for reading. The file
79 * <basename> is a stub describing the database. The bulk
80 * of the data are in three accompanying binary files: the
81 * index file <basename>.dsqi, the metadata file
82 * <basename>.dsqm, and the sequence file <basename>.dsqs.
83 *
84 * <nconsumers> is an upper bound on the number of threads
85 * in which the caller plans to be calling
86 * <esl_dsqdata_Read()> -- or, more precisely, the maximum
87 * number of data chunks that the caller could be working
88 * on at any given instant. This is a hint, not a
89 * commitment. The dsqdata loader uses it to determine the
90 * maximum number of data chunks that can be in play at
91 * once (including chunks it is juggling internally, plus
92 * if all the caller's reader threads are busy on
93 * theirs). If <nconsumers> is set too small, the loader
94 * may stall waiting for chunks to come back for recycling.
95 *
96 * Reading digital sequence data requires a digital
97 * alphabet. You can either provide one (in which case we
98 * validate that it matches the alphabet used by the
99 * dsqdata) or, as a convenience, <esl_dsqdata_Open()> can
100 * create one for you. Either way, you pass a pointer to an
101 * <ESL_ALPHABET> structure <abc>, in <byp_abc>. <byp_abc>
102 * uses a partial Easel "bypass" idiom: if <*byp_abc> is
103 * NULL, we allocate and return a new alphabet; if
104 * <*byp_abc> is a ptr to an existing alphabet, we use it
105 * for validation. That is, you have two choices:
106 *
107 * ```
108 * ESL_ALPHABET *abc = NULL;
109 * esl_dsqdata_Open(&abc, basename...)
110 * // <abc> is now the alphabet of <basename>;
111 * // now you're responsible for Destroy'ing it
112 * ```
113 *
114 * or:
115 *
116 * ```
117 * ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
118 * status = esl_dsqdata_Open(&abc, basename);
119 * // if status == eslEINCOMPAT, alphabet in basename
120 * // doesn't match caller's expectation
121 * ```
122 *
123 * Args: byp_abc : expected or created alphabet; pass &abc, abc=NULL or abc=expected alphabet
124 * basename : data are in files <basename> and <basename.dsq[ism]>
125 * nconsumers : upper bound on number of consumer threads caller is going to Read() with
126 * ret_dd : RETURN : the new ESL_DSQDATA object.
127 *
128 * Returns: <eslOK> on success.
129 *
130 * <eslENOTFOUND> if one or more of the expected datafiles
131 * aren't there or can't be opened.
132 *
133 * <eslEFORMAT> if something looks wrong in parsing file
134 * formats. Includes problems in headers, and also the
135 * case where caller provides a digital alphabet in
136 * <*byp_abc> and it doesn't match the database's alphabet.
137 *
138 * On any normal error, <*ret_dd> is still returned, but in
139 * an error state, and <dd->errbuf> is a user-directed
140 * error message that the caller can relay to the user. Other
141 * than the <errbuf>, the rest of the contents are undefined.
142 *
143 * Caller is responsible for destroying <*byp_abc>.
144 *
145 * Throws: <eslEMEM> on allocation error.
146 * <eslESYS> on system call failure.
147 * <eslEUNIMPLEMENTED> if data are byteswapped
148 * TODO: handle byteswapping
149 *
150 * On any thrown exception, <*ret_dd> is returned NULL.
151 *
152 * On <eslESYS> exceptions, some thread resources may
153 * not be fully freed, leading to some memory leakage.
154 */
155 int
156 esl_dsqdata_Open(ESL_ALPHABET **byp_abc, char *basename, int nconsumers, ESL_DSQDATA **ret_dd)
157 {
158 ESL_DSQDATA *dd = NULL;
159 int bufsize = 4096;
160 uint32_t magic = 0;
161 uint32_t tag = 0;
162 uint32_t alphatype = eslUNKNOWN;
163 int ndd;
164 char *p; // used for strtok() parsing of fields on a line
165 char buf[4096];
166 int u;
167 int status;
168
169 ESL_DASSERT1(( nconsumers > 0 ));
170 ESL_DASSERT1(( byp_abc != NULL )); // either *byp_abc == NULL or *byp_abc = the caller's expected alphabet.
171
172 ESL_ALLOC(dd, sizeof(ESL_DSQDATA));
173 dd->stubfp = NULL;
174 dd->ifp = NULL;
175 dd->sfp = NULL;
176 dd->mfp = NULL;
177 dd->abc_r = *byp_abc; // This may be NULL; if so, we create it later.
178
179 dd->magic = 0;
180 dd->uniquetag = 0;
181 dd->flags = 0;
182 dd->max_namelen = 0;
183 dd->max_acclen = 0;
184 dd->max_desclen = 0;
185 dd->max_seqlen = 0;
186 dd->nseq = 0;
187 dd->nres = 0;
188
189 dd->chunk_maxseq = eslDSQDATA_CHUNK_MAXSEQ; // someday we may want to allow tuning these
190 dd->chunk_maxpacket = eslDSQDATA_CHUNK_MAXPACKET;
191 dd->do_byteswap = FALSE;
192 dd->pack5 = FALSE;
193
194 dd->nconsumers = nconsumers;
195 dd->n_unpackers = eslDSQDATA_UNPACKERS; // we'll want to allow tuning this too
196 dd->errbuf[0] = '\0';
197
198 /* Open the four files.
199 */
200 ndd = strlen(basename) + 6; // +5 for .dsqx; +1 for \0
201 ESL_ALLOC( dd->basename, ndd);
202 if ( snprintf(dd->basename, ndd, "%s.dsqi", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
203 if (( dd->ifp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open index file %s\n", dd->basename);
204
205 if ( snprintf(dd->basename, ndd, "%s.dsqm", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
206 if (( dd->mfp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open metadata file %s\n", dd->basename);
207
208 if ( snprintf(dd->basename, ndd, "%s.dsqs", basename) <= 0) ESL_XEXCEPTION_SYS(eslESYS, "sprintf() failure");
209 if (( dd->sfp = fopen(dd->basename, "rb")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open sequence file %s\n", dd->basename);
210
211 strcpy(dd->basename, basename);
212 if (( dd->stubfp = fopen(dd->basename, "r")) == NULL) ESL_XFAIL(eslENOTFOUND, dd->errbuf, "Failed to find or open stub file %s\n", dd->basename);
213
214 /* The stub file is unparsed, intended to be human readable, with one exception:
215 * The first line contains the unique tag that we use to validate linkage of the 4 files.
216 * The format of that first line is:
217 * Easel dsqdata v123 x0000000000
218 */
219 if ( fgets(buf, bufsize, dd->stubfp) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file is empty - no tag line found");
220 if (( p = strtok(buf, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: tag line has no data");
221 if ( strcmp(p, "Easel") != 0) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
222 if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
223 if ( strcmp(p, "dsqdata") != 0) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
224 if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
225 if ( *p != 'v') ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: no v on version");
226 if ( ! esl_str_IsInteger(p+1)) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file had bad format: no version number");
227 // version number is currently unused: there's only 1
228 if (( p = strtok(NULL, " \t\n\r")) == NULL) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format in tag line");
229 if ( *p != 'x') ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file has bad format: no x on tag");
230 if ( ! esl_str_IsInteger(p+1)) ESL_XFAIL(eslEFORMAT, dd->errbuf, "stub file had bad format: no integer tag");
231 dd->uniquetag = strtoul(p+1, NULL, 10);
232
233 /* Index file has a header of 7 uint32's, 3 uint64's */
234 if ( fread(&(dd->magic), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has no header - is empty?");
235 if ( fread(&tag, sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no tag");
236 if ( fread(&alphatype, sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no alphatype");
237 if ( fread(&(dd->flags), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no flags");
238 if ( fread(&(dd->max_namelen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max name len");
239 if ( fread(&(dd->max_acclen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max accession len");
240 if ( fread(&(dd->max_desclen), sizeof(uint32_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max description len");
241
242 if ( fread(&(dd->max_seqlen), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no max seq len");
243 if ( fread(&(dd->nseq), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no nseq");
244 if ( fread(&(dd->nres), sizeof(uint64_t), 1, dd->ifp) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file header truncated, no nres");
245
246 /* Check the magic and the tag */
247 if (tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has bad tag, doesn't go with stub file");
248 // Eventually we would set dd->do_byteswap = TRUE; below.
249 if (dd->magic == eslDSQDATA_MAGIC_V1SWAP) ESL_XEXCEPTION(eslEUNIMPLEMENTED, "dsqdata cannot yet read data in different byte orders");
250 else if (dd->magic != eslDSQDATA_MAGIC_V1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has bad magic");
251
252 /* Either validate, or create the alphabet */
253 if (dd->abc_r)
254 {
255 if (alphatype != dd->abc_r->type)
256 ESL_XFAIL(eslEFORMAT, dd->errbuf, "data files use %s alphabet; expected %s alphabet",
257 esl_abc_DecodeType(alphatype),
258 esl_abc_DecodeType(dd->abc_r->type));
259 }
260 else
261 {
262 if ( esl_abc_ValidateType(alphatype) != eslOK) ESL_XFAIL(eslEFORMAT, dd->errbuf, "index file has invalid alphabet type %d", alphatype);
263 if (( dd->abc_r = esl_alphabet_Create(alphatype)) == NULL) ESL_XEXCEPTION(eslEMEM, "alphabet creation failed");
264 }
265
266 /* If it's protein, flip the switch to expect all 5-bit packing */
267 if (dd->abc_r->type == eslAMINO) dd->pack5 = TRUE;
268
269 /* Metadata file has a header of 2 uint32's, magic and uniquetag */
270 if (( fread(&magic, sizeof(uint32_t), 1, dd->mfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has no header - is empty?");
271 if (( fread(&tag, sizeof(uint32_t), 1, dd->mfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file header truncated - no tag?");
272 if ( magic != dd->magic) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has bad magic");
273 if ( tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "metadata file has bad tag, doesn't match stub");
274
275 /* Sequence file also has a header of 2 uint32's, magic and uniquetag */
276 if (( fread(&magic, sizeof(uint32_t), 1, dd->sfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has no header - is empty?");
277 if (( fread(&tag, sizeof(uint32_t), 1, dd->sfp)) != 1) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file header truncated - no tag?");
278 if ( magic != dd->magic) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has bad magic");
279 if ( tag != dd->uniquetag) ESL_XFAIL(eslEFORMAT, dd->errbuf, "sequence file has bad tag, doesn't match stub");
280
281 /* unpacker inboxes and outboxes */
282 for (u = 0; u < dd->n_unpackers; u++)
283 {
284 dd->inbox[u] = NULL;
285 if ( pthread_mutex_init(&(dd->inbox_mutex[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
286 if ( pthread_cond_init (&(dd->inbox_cv[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
287 dd->inbox_eod[u] = FALSE;
288
289 dd->outbox[u] = NULL;
290 if ( pthread_mutex_init(&(dd->outbox_mutex[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
291 if ( pthread_cond_init (&(dd->outbox_cv[u]), NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
292 dd->outbox_eod[u] = FALSE;
293 }
294
295 /* consumers share access to <nchunk> counter */
296 dd->nchunk = 0;
297 if ( pthread_mutex_init(&dd->nchunk_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
298
299 /* chunk recycling stack */
300 dd->recycling = NULL;
301 if ( pthread_mutex_init(&dd->recycling_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed");
302 if ( pthread_cond_init(&dd->recycling_cv, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed");
303
304 /* Create the "initialization is complete" signaling mechanism
305 * before creating any threads, and lock the initialization mutex
306 * while we're creating them. The issue here is that unpackers
307 * identify their [u] index by comparing their self thread id to the
308 * master list of thread ids, so make sure that master list actually
309 * exists.
310 */
311 dd->go = FALSE;
312 if ( pthread_mutex_init(&dd->go_mutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_init() failed on go_mutex");
313 if ( pthread_cond_init( &dd->go_cv, NULL) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_init() failed on go_cv");
314 if ( pthread_mutex_lock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock() failed on go_mutex");
315
316 /* Create the loader and the unpackers.
317 * They will wait to start until we signal through go->cv.
318 */
319 if ( pthread_create(&dd->loader_t, NULL, dsqdata_loader_thread, dd) != 0) ESL_XEXCEPTION(eslESYS, "pthread_create() failed");
320 for (u = 0; u < dd->n_unpackers; u++)
321 if ( pthread_create(&(dd->unpacker_t[u]), NULL, dsqdata_unpacker_thread, dd) != 0) ESL_XEXCEPTION(eslESYS, "pthread_create() failed");
322
323 /* All threads started, initialization complete - broadcast "go" signal to all threads */
324 dd->go = TRUE;
325 if ( pthread_mutex_unlock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_unlock() failed on go_mutex");
326 if ( pthread_cond_broadcast(&dd->go_cv) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_broadcast() failed on go_cv");
327
328 *ret_dd = dd;
329 *byp_abc = dd->abc_r; // If caller provided <*byp_abc> this is a no-op, because we set abc_r = *byp_abc.
330 return eslOK; // .. otherwise we're passing the created <abc> back to caller, caller's
331 // responsibility, we just keep the reference to it.
332 ERROR:
333 if (status == eslENOTFOUND || status == eslEFORMAT || status == eslEINCOMPAT)
334 { /* on normal errors, we return <dd> with its <errbuf>, don't change *byp_abc */
335 *ret_dd = dd;
336 if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
337 return status;
338 }
339 else if (status != eslESYS)
340 { /* on most exceptions, we free <dd>, return it NULL, don't change *byp_abc */
341 esl_dsqdata_Close(dd);
342 *ret_dd = NULL;
343 if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
344 return status;
345 }
346 else
347 { /* on eslESYS exceptions - pthread initializations failing - we can't assume we can _Close() correctly. */
348 *ret_dd = NULL;
349 if (*byp_abc == NULL && dd->abc_r) esl_alphabet_Destroy(dd->abc_r);
350 return status;
351 }
352 }
353
354
355
356 /* Function: esl_dsqdata_Read()
357 * Synopsis: Read next chunk of sequence data.
358 * Incept: SRE, Thu Jan 21 11:21:38 2016 [Harvard]
359 *
360 * Purpose: Read the next chunk from <dd>, return a pointer to it in
361 * <*ret_chu>, and return <eslOK>. When data are exhausted,
362 * return <eslEOF>, and <*ret_chu> is <NULL>.
363 *
364 * Threadsafe. All thread operations in the dsqdata reader
365 * are handled internally. Caller does not have to worry
366 * about wrapping this in a mutex. Multiple caller threads
367 * can call <esl_dsqdata_Read()>.
368 *
369 * All chunk allocation and deallocation is handled
370 * internally. After using a chunk, caller gives it back to
371 * the reader using <esl_dsqdata_Recycle()>.
372 *
373 * Args: dd : open dsqdata object to read from
374 * ret_chu : RETURN : next chunk of seq data
375 *
376 * Returns: <eslOK> on success. <*ret_chu> is a chunk of seq data.
377 * Caller must call <esl_dsqdata_Recycle()> on each chunk
378 * that it Read()'s.
379 *
380 * <eslEOF> if we've reached the end of the input file;
381 * <*ret_chu> is NULL.
382 *
383 * Throws: <eslESYS> if a pthread call fails.
384 * Caller should treat this as disastrous. Without correctly
385 * working pthread calls, we cannot read, and we may not be able
386 * to correctly clean up and close the reader. Caller should
387 * treat <dd> as toxic, clean up whatever else it may need to,
388 * and exit.
389 */
390 int
391 esl_dsqdata_Read(ESL_DSQDATA *dd, ESL_DSQDATA_CHUNK **ret_chu)
392 {
393 ESL_DSQDATA_CHUNK *chu = NULL;
394 int u;
395
396 /* First, determine which slot the next chunk is in, using the consumer-shared <nchunk> counter */
397 if ( pthread_mutex_lock(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "failed to lock reader mutex");
398 u = (int) (dd->nchunk % dd->n_unpackers);
399
400 /* Acquire a lock that outbox, wait for it to be in full or EOD state */
401 if ( pthread_mutex_lock(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to lock outbox[u] mutex");
402 while (! dd->outbox_eod[u] && dd->outbox[u] == NULL) {
403 if ( pthread_cond_wait(&(dd->outbox_cv[u]), &(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to wait on outbox[u] signal");
404 }
405
406 /* Get the chunk from outbox. */
407 chu = dd->outbox[u];
408 dd->outbox[u] = NULL;
409 if (chu) dd->nchunk++; // chu==NULL if we're EOD. (and eod flag is up too, but we already know that by getting here)
410
411 /* Release the outbox lock and signal back to unpacker (skip signalling if we're EOD; unpacker[u] is done) */
412 if ( pthread_mutex_unlock(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to unlock outbox[u] mutex");
413 if ( chu && pthread_cond_signal (&(dd->outbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "failed to signal outbox[u] is empty");
414
415 /* Release the reader lock that protects dd->nchunk counter */
416 if ( pthread_mutex_unlock(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "failed to unlock reader mutex");
417
418 *ret_chu = chu;
419 return (chu ? eslOK : eslEOF);
420 }
421
422
423 /* Function: esl_dsqdata_Recycle()
424 * Synopsis: Give a chunk back to the reader.
425 * Incept: SRE, Thu Feb 11 19:24:33 2016
426 *
427 * Purpose: Recycle chunk <chu> back to the reader <dd>. The reader
428 * is responsible for all allocation and deallocation of
429 * chunks. The reader will either reuse the chunk's memory
430 * if more chunks remain to be read, or it will free it.
431 *
432 * Args: dd : dsqdata reader
433 * chu : chunk to recycle
434 *
435 * Returns: <eslOK> on success.
436 *
437 * Throws: <eslESYS> on a pthread call failure. Caller should regard
438 * such an error as disastrous; if pthread calls are
439 * failing, you cannot depend on the reader to be working
440 * at all, and you should treat <dd> as toxic. Do whatever
441 * desperate things you need to do and exit.
442 */
443 int
444 esl_dsqdata_Recycle(ESL_DSQDATA *dd, ESL_DSQDATA_CHUNK *chu)
445 {
446 if (chu)
447 {
448 if ( pthread_mutex_lock(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex lock failed");
449 chu->nxt = dd->recycling; // Push chunk onto head of recycling stack
450 dd->recycling = chu;
451 if ( pthread_mutex_unlock(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex unlock failed");
452 if ( pthread_cond_signal(&dd->recycling_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond signal failed"); // loader may wait for this signal
453 }
454 return eslOK;
455 }
456
457
458
459 /* Function: esl_dsqdata_Close()
460 * Synopsis: Close a dsqdata reader.
461 * Incept: SRE, Thu Feb 11 19:32:54 2016
462 *
463 * Purpose: Close a dsqdata reader.
464 *
465 * Returns: <eslOK> on success.
466
467 * Throws: <eslESYS> on a system call failure, including pthread
468 * calls and fclose(). Caller should regard such a failure
469 * as disastrous: treat <dd> as toxic and exit as soon as
470 * possible without making any other system calls, if possible.
471 *
472 * Note: Normally Easel would call _Close() not only on a correctly
473 * opened object (after the Open returns) but also from
474 * within the Open call to clean up on failure. This relies
475 * on being able to tell which parts of an incomplete
476 * object have been initialized; this is why Easel sets
477 * ptrs to NULL before allocating them, for example. POSIX
478 * threads doesn't seem to give us a way to check whether a
479 * mutex, condition variable, or thread has been
480 * initialized; and destroying an uninitialized mutex or CV
481 * results in undefined behavior. We could include a
482 * boolean flag for each pthreads component -- or one for
483 * all of them -- but instead, we simply say that a failure
484 * of pthreads initialization in the Open function is so
485 * catastrophic and unexpected that we exit that function
486 * without cleaning up the incomplete ESL_DSQDATA
487 * structure. We expect that the caller is simply going to
488 * have to quit anyway, so we don't need to worry about
489 * memory leakage.
490 */
491 int
492 esl_dsqdata_Close(ESL_DSQDATA *dd)
493 {
494 int u;
495
496 if (dd)
497 {
498 /* out of abundance of caution - wait for threads to join before breaking down <dd> */
499 if ( pthread_join(dd->loader_t, NULL) != 0) ESL_EXCEPTION(eslESYS, "pthread join failed");
500 for (u = 0; u < dd->n_unpackers; u++)
501 if ( pthread_join(dd->unpacker_t[u], NULL) != 0) ESL_EXCEPTION(eslESYS, "pthread join failed");
502
503 if (dd->basename) free(dd->basename);
504 if (dd->stubfp) { if ( fclose(dd->stubfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
505 if (dd->ifp) { if ( fclose(dd->ifp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
506 if (dd->sfp) { if ( fclose(dd->sfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
507 if (dd->mfp) { if ( fclose(dd->mfp) != 0) ESL_EXCEPTION(eslESYS, "fclose failed"); }
508
509 for (u = 0; u < dd->n_unpackers; u++)
510 {
511 if ( pthread_mutex_destroy(&(dd->inbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
512 if ( pthread_cond_destroy(&(dd->inbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
513 if ( pthread_mutex_destroy(&(dd->outbox_mutex[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
514 if ( pthread_cond_destroy(&(dd->outbox_cv[u])) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
515 }
516 if ( pthread_mutex_destroy(&dd->nchunk_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
517 if ( pthread_mutex_destroy(&dd->recycling_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
518 if ( pthread_cond_destroy(&dd->recycling_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
519 if ( pthread_mutex_destroy(&dd->go_mutex) != 0) ESL_EXCEPTION(eslESYS, "pthread mutex destroy failed");
520 if ( pthread_cond_destroy(&dd->go_cv) != 0) ESL_EXCEPTION(eslESYS, "pthread cond destroy failed");
521
522 /* Loader thread is responsible for freeing all chunks it created, even on error. */
523 #if (eslDEBUGLEVEL >= 1)
524 for (u = 0; u < dd->n_unpackers; u++) {
525 assert( dd->inbox[u] == NULL );
526 assert( dd->outbox[u] == NULL );
527 }
528 assert(dd->recycling == NULL );
529 #endif
530 free(dd);
531 }
532 return eslOK;
533 }
534
535
536 /*****************************************************************
537 *# 2. Creating dsqdata format from a sequence file
538 *****************************************************************/
539
540 /* Function: esl_dsqdata_Write()
541 * Synopsis: Create a dsqdata database
542 * Incept: SRE, Sat Feb 13 07:33:30 2016 [AGBT 2016, Orlando]
543 *
544 * Purpose: Caller has just opened <sqfp>, in digital mode.
545 * Create a dsqdata database <basename> from the sequence
546 * data in <sqfp>.
547 *
548 * <sqfp> must be protein, DNA, or RNA sequence data. It
549 * must be rewindable (i.e. a file), because we have to
550 * read it twice. It must be newly opened (i.e. positioned
551 * at the start).
552 *
553 * Args: sqfp - newly opened sequence data file
554 * basename - base name of dsqdata files to create
555 * errbuf - user-directed error message on normal errors
556 *
557 * Returns: <eslOK> on success.
558 *
559 * <eslEWRITE> if an output file can't be opened. <errbuf>
560 * contains user-directed error message.
561 *
562 * <eslEFORMAT> if a parse error is encountered while
563 * reading <sqfp>.
564 *
565 *
566 * Throws: <eslESYS> A system call failed, such as fwrite().
567 * <eslEINVAL> Sequence handle <sqfp> isn't digital and rewindable.
568 * <eslEMEM> Allocation failure
569 * <eslEUNIMPLEMENTED> Sequence is too long to be encoded.
570 * (TODO: chromosome-scale DNA sequences)
571 */
572 int
573 esl_dsqdata_Write(ESL_SQFILE *sqfp, char *basename, char *errbuf)
574 {
575 ESL_RANDOMNESS *rng = NULL;
576 ESL_SQ *sq = NULL;
577 FILE *stubfp = NULL;
578 FILE *ifp = NULL;
579 FILE *mfp = NULL;
580 FILE *sfp = NULL;
581 char *outfile = NULL;
582 uint32_t magic = eslDSQDATA_MAGIC_V1;
583 uint32_t uniquetag;
584 uint32_t alphatype;
585 uint32_t flags = 0;
586 uint32_t max_namelen = 0;
587 uint32_t max_acclen = 0;
588 uint32_t max_desclen = 0;
589 uint64_t max_seqlen = 0;
590 uint64_t nseq = 0;
591 uint64_t nres = 0;
592 int do_pack5 = FALSE;
593 uint32_t *psq;
594 ESL_DSQDATA_RECORD idx; // one index record to write
595 int plen;
596 int64_t spos = 0;
597 int64_t mpos = 0;
598 int n;
599 int na;
600 int status;
601
602 if (! esl_sqfile_IsRewindable(sqfp)) ESL_EXCEPTION(eslEINVAL, "sqfp must be rewindable (e.g. an open file)");
603 if (! sqfp->abc) ESL_EXCEPTION(eslEINVAL, "sqfp must be digital");
604 // Could also check that it's positioned at the start.
605 if ( (sq = esl_sq_CreateDigital(sqfp->abc)) == NULL) { status = eslEMEM; goto ERROR; }
606
607 /* First pass over the sequence file, to get statistics.
608 * Read it now, before opening any files, in case we find any parse errors.
609 */
610 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
611 {
612 if (sq->n >= 6 * eslDSQDATA_CHUNK_MAXPACKET) // guaranteed limit
613 ESL_EXCEPTION(eslEUNIMPLEMENTED, "dsqdata cannot currently deal with large sequences");
614
615 nseq++;
616 nres += sq->n;
617 if (sq->n > max_seqlen) max_seqlen = sq->n;
618 n = strlen(sq->name); if (n > max_namelen) max_namelen = n;
619 n = strlen(sq->acc); if (n > max_acclen) max_acclen = n;
620 n = strlen(sq->desc); if (n > max_desclen) max_desclen = n;
621 esl_sq_Reuse(sq);
622 }
623 if (status == eslEFORMAT) ESL_XFAIL(eslEFORMAT, errbuf, sqfp->get_error(sqfp));
624 else if (status != eslEOF) return status;
625
626 if ((status = esl_sqfile_Position(sqfp, 0)) != eslOK) return status;
627
628
629 if (( rng = esl_randomness_Create(0) ) == NULL) { status = eslEMEM; goto ERROR; }
630 uniquetag = esl_random_uint32(rng);
631 alphatype = sqfp->abc->type;
632
633 if (alphatype == eslAMINO) do_pack5 = TRUE;
634 else if (alphatype != eslDNA && alphatype != eslRNA) ESL_EXCEPTION(eslEINVAL, "alphabet must be protein or nucleic");
635
636 na = strlen(basename) + 6; // '.dsq?' + '\0'
637 ESL_ALLOC(outfile, na);
638 if ( snprintf(outfile, na, "%s.dsqi", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
639 if (( ifp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata index file %s for writing", outfile);
640 if ( snprintf(outfile, na, "%s.dsqm", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
641 if (( mfp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata metadata file %s for writing", outfile);
642 if ( snprintf(outfile, na, "%s.dsqs", basename) < 0) ESL_EXCEPTION(eslESYS, "sprintf failed");
643 if (( sfp = fopen(outfile, "wb")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata sequence file %s for writing", outfile);
644 if (( stubfp = fopen(basename, "w")) == NULL) ESL_XFAIL(eslEWRITE, errbuf, "failed to open dsqdata stub file %s for writing", basename);
645
646 /* Header: index file */
647 if (fwrite(&magic, sizeof(uint32_t), 1, ifp) != 1 ||
648 fwrite(&uniquetag, sizeof(uint32_t), 1, ifp) != 1 ||
649 fwrite(&alphatype, sizeof(uint32_t), 1, ifp) != 1 ||
650 fwrite(&flags, sizeof(uint32_t), 1, ifp) != 1 ||
651 fwrite(&max_namelen, sizeof(uint32_t), 1, ifp) != 1 ||
652 fwrite(&max_acclen, sizeof(uint32_t), 1, ifp) != 1 ||
653 fwrite(&max_desclen, sizeof(uint32_t), 1, ifp) != 1 ||
654 fwrite(&max_seqlen, sizeof(uint64_t), 1, ifp) != 1 ||
655 fwrite(&nseq, sizeof(uint64_t), 1, ifp) != 1 ||
656 fwrite(&nres, sizeof(uint64_t), 1, ifp) != 1)
657 ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, index file header");
658
659 /* Header: metadata file */
660 if (fwrite(&magic, sizeof(uint32_t), 1, mfp) != 1 ||
661 fwrite(&uniquetag, sizeof(uint32_t), 1, mfp) != 1)
662 ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, metadata file header");
663
664 /* Header: sequence file */
665 if (fwrite(&magic, sizeof(uint32_t), 1, sfp) != 1 ||
666 fwrite(&uniquetag, sizeof(uint32_t), 1, sfp) != 1)
667 ESL_XEXCEPTION_SYS(eslESYS, "fwrite() failed, metadata file header");
668
669 /* Second pass: index, metadata, and sequence files */
670 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
671 {
672 /* Packed sequence */
673 psq = (uint32_t *) sq->dsq; // pack-in-place
674 ESL_DASSERT1(( sq->salloc >= 4 )); // required min space for pack-in-place
675 if (do_pack5) dsqdata_pack5(sq->dsq, sq->n, psq, &plen);
676 else dsqdata_pack2(sq->dsq, sq->n, psq, &plen);
677 if ( fwrite(psq, sizeof(uint32_t), plen, sfp) != plen)
678 ESL_XEXCEPTION(eslESYS, "fwrite() failed, packed seq");
679 spos += plen;
680
681 /* Metadata */
682 n = strlen(sq->name);
683 if ( fwrite(sq->name, sizeof(char), n+1, mfp) != n+1)
684 ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, name");
685 mpos += n+1;
686
687 n = strlen(sq->acc);
688 if ( fwrite(sq->acc, sizeof(char), n+1, mfp) != n+1)
689 ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, accession");
690 mpos += n+1;
691
692 n = strlen(sq->desc);
693 if ( fwrite(sq->desc, sizeof(char), n+1, mfp) != n+1)
694 ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, description");
695 mpos += n+1;
696
697 if ( fwrite( &(sq->tax_id), sizeof(int32_t), 1, mfp) != 1)
698 ESL_XEXCEPTION(eslESYS, "fwrite () failed, metadata, taxonomy id");
699 mpos += sizeof(int32_t);
700
701 /* Index file */
702 idx.psq_end = spos-1; // could be -1, on 1st seq, if 1st seq L=0.
703 idx.metadata_end = mpos-1;
704 if ( fwrite(&idx, sizeof(ESL_DSQDATA_RECORD), 1, ifp) != 1)
705 ESL_XEXCEPTION(eslESYS, "fwrite () failed, index file");
706
707 esl_sq_Reuse(sq);
708 }
709
710 /* Stub file */
711 fprintf(stubfp, "Easel dsqdata v1 x%" PRIu32 "\n", uniquetag);
712 fprintf(stubfp, "\n");
713 fprintf(stubfp, "Original file: %s\n", sqfp->filename);
714 fprintf(stubfp, "Original format: %s\n", esl_sqio_DecodeFormat(sqfp->format));
715 fprintf(stubfp, "Type: %s\n", esl_abc_DecodeType(sqfp->abc->type));
716 fprintf(stubfp, "Sequences: %" PRIu64 "\n", nseq);
717 fprintf(stubfp, "Residues: %" PRIu64 "\n", nres);
718
719 esl_sq_Destroy(sq);
720 esl_randomness_Destroy(rng);
721 free(outfile);
722 fclose(stubfp);
723 fclose(ifp);
724 fclose(mfp);
725 fclose(sfp);
726 return eslOK;
727
728 ERROR:
729 if (sq) esl_sq_Destroy(sq);
730 if (rng) esl_randomness_Destroy(rng);
731 if (outfile) free(outfile);
732 if (stubfp) fclose(stubfp);
733 if (ifp) fclose(ifp);
734 if (mfp) fclose(mfp);
735 if (sfp) fclose(sfp);
736 return status;
737 }
738
739
740
741 /*****************************************************************
742 * 3. ESL_DSQDATA_CHUNK: a chunk of input sequence data
743 *****************************************************************/
744
745 static ESL_DSQDATA_CHUNK *
746 dsqdata_chunk_Create(ESL_DSQDATA *dd)
747 {
748 ESL_DSQDATA_CHUNK *chu = NULL;
749 int U; // max size of unpacked seq data, in bytes (smem allocation)
750 int status;
751
752 ESL_ALLOC(chu, sizeof(ESL_DSQDATA_CHUNK));
753 chu->i0 = 0;
754 chu->N = 0;
755 chu->pn = 0;
756 chu->dsq = NULL;
757 chu->name = NULL;
758 chu->acc = NULL;
759 chu->desc = NULL;
760 chu->taxid = NULL;
761 chu->L = NULL;
762 chu->metadata = NULL;
763 chu->smem = NULL;
764 chu->nxt = NULL;
765
766 /* dsq, name, acc, desc are arrays of pointers into smem, metadata.
767 * taxid is cast to int, from the metadata.
768 * L is figured out by the unpacker.
769 * All of these are set by the unpacker.
770 */
771 ESL_ALLOC(chu->dsq, dd->chunk_maxseq * sizeof(ESL_DSQ *));
772 ESL_ALLOC(chu->name, dd->chunk_maxseq * sizeof(char *));
773 ESL_ALLOC(chu->acc, dd->chunk_maxseq * sizeof(char *));
774 ESL_ALLOC(chu->desc, dd->chunk_maxseq * sizeof(char *));
775 ESL_ALLOC(chu->taxid, dd->chunk_maxseq * sizeof(int));
776 ESL_ALLOC(chu->L, dd->chunk_maxseq * sizeof(int64_t));
777
778 /* On the <smem> allocation, and the <dsq> and <psq> pointers into it:
779 *
780 * <maxpacket> (in uint32's) sets the maximum single fread() size:
781 * one load of a new chunk of packed sequence, up to maxpacket*4
782 * bytes. <smem> needs to be able to hold both that and the fully
783 * unpacked sequence, because we unpack in place. Each packet
784 * unpacks to at most 6 or 15 residues (5-bit or 2-bit packing) We
785 * don't pack sentinels, so the maximum unpacked size includes
786 * <maxseq>+1 sentinels... because we concat the digital seqs so
787 * that the trailing sentinel of seq i is the leading sentinel of
788 * seq i+1.
789 *
790 * The packed seq (max of P bytes) loads overlap with the unpacked
791 * data (max of U bytes):
792 * psq
793 * v[ P bytes ]
794 * smem: 0........0........0..........0
795 * ^[ U bytes ]
796 * ^dsq[0] ^dsq[1] ^dsq[2]
797 *
798 * and as long as we unpack psq left to right -- and as long as we
799 * read the last packet before we write the last unpacked residues
800 * to smem - we're guaranteed that the unpacking works without
801 * overwriting any unpacked data.
802 */
803 U = (dd->pack5 ? 6 * dd->chunk_maxpacket : 15 * dd->chunk_maxpacket);
804 U += dd->chunk_maxseq + 1;
805 ESL_ALLOC(chu->smem, sizeof(ESL_DSQ) * U);
806 chu->psq = (uint32_t *) (chu->smem + U - 4*dd->chunk_maxpacket);
807
808 /* We don't have any guarantees about the amount of metadata
809 * associated with the N sequences, so <metadata> has to be a
810 * reallocatable space. We make a lowball guess for the initial
811 * alloc, on the off chance that the metadata size is small (names
812 * only, no acc/desc): minimally, say 12 bytes of name, 3 \0's, and
813 * 4 bytes for the taxid integer: call it 20.
814 */
815 chu->mdalloc = 20 * dd->chunk_maxseq;
816 ESL_ALLOC(chu->metadata, sizeof(char) * chu->mdalloc);
817
818 return chu;
819
820 ERROR:
821 dsqdata_chunk_Destroy(chu);
822 return NULL;
823 }
824
825
826 static void
827 dsqdata_chunk_Destroy(ESL_DSQDATA_CHUNK *chu)
828 {
829 if (chu)
830 {
831 if (chu->metadata) free(chu->metadata);
832 if (chu->smem) free(chu->smem);
833 if (chu->L) free(chu->L);
834 if (chu->taxid) free(chu->taxid);
835 if (chu->desc) free(chu->desc);
836 if (chu->acc) free(chu->acc);
837 if (chu->name) free(chu->name);
838 if (chu->dsq) free(chu->dsq);
839 free(chu);
840 }
841 }
842
843
844 /*****************************************************************
845 * 4. Loader and unpacker, the input threads
846 *****************************************************************/
847
848 static void *
849 dsqdata_loader_thread(void *p)
850 {
851 ESL_DSQDATA *dd = (ESL_DSQDATA *) p;
852 ESL_DSQDATA_RECORD *idx = NULL;
853 ESL_DSQDATA_CHUNK *chu = NULL;
854 int64_t nchunk = 0; // total number of chunks loaded (including empty EOF)
855 int nalloc = 0; // number of chunks we create, and need to destroy.
856 int nidx = 0; // how many records in <idx>: usually MAXSEQ, until end
857 int nload = 0; // how many sequences we load: >=1, <=nidx
858 int ncarried = 0; // how many records carry over to next iteration: nidx-nload
859 int nread = 0; // fread()'s return value
860 int nmeta = 0; // how many bytes of metadata we want to read for this chunk
861 int i0 = 0; // absolute index of first record in <idx>, 0-offset
862 int64_t psq_last = -1; // psq_end for record i0-1
863 int64_t meta_last = -1; // metadata_end for record i0-1
864 int u; // which unpacker outbox we put this chunk in
865 int status;
866
867 /* Don't use <dd> until we get the structure-is-ready signal */
868 if ( pthread_mutex_lock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
869 while (! dd->go) {
870 if ( pthread_cond_wait(&dd->go_cv, &dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_wait failed on go_cv");
871 }
872 if ( pthread_mutex_unlock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
873
874 /* We can begin. */
875 ESL_ALLOC(idx, sizeof(ESL_DSQDATA_RECORD) * dd->chunk_maxseq);
876 while (1)
877 {
878 //printf("loader: working on chunk %d\n", (int) nchunk+1);
879
880 /* Get a chunk structure we can use - either by creating it, or recycling it.
881 * We probably don't benefit from having more than <nconsumers> + 3*<n_unpackers> + 2,
882 * which is enough to have all threads working, all in/outboxes full, and at least 1
883 * waiting in recycling.
884 * SRE TODO: test, how many is optimal, does it matter?
885 * the two limits below perform comparably in `esl_dsqdata_example -n`, but that
886 * doesn't have high-cpu reader threads.
887 */
888 //if (nalloc < dd->nconsumers + dd->n_unpackers + 1)
889 if (nalloc < dd->nconsumers + 3 * dd->n_unpackers + 2)
890 {
891 //printf("loader: creating a new chunk\n");
892
893 if ( (chu = dsqdata_chunk_Create(dd)) == NULL) { status = eslEMEM; goto ERROR; }
894 nalloc++;
895 }
896 else
897 {
898 //printf("loader: getting a new chunk from recycling...\n");
899
900 if ( pthread_mutex_lock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
901 while (dd->recycling == NULL) {
902 if ( pthread_cond_wait(&dd->recycling_cv, &dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
903 }
904 chu = dd->recycling; // pop one off recycling stack
905 dd->recycling = chu->nxt;
906 if ( pthread_mutex_unlock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
907 if ( pthread_cond_signal(&dd->recycling_cv) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed"); // signal *after* unlocking mutex
908
909 //printf("loader: ... done, have new chunk from recycling.\n");
910 }
911
912 /* Refill index. (The memmove is avoidable. Alt strategy: we could load in 2 frames)
913 * The previous loop loaded packed sequence for <nload'> of the <nidx'> entries,
914 * where the 's indicate the variable has carried over from prev iteration:
915 * |----- nload' ----||--- (ncarried) ---|
916 * |-------------- nidx' ----------------|
917 * Now we're going to shift the remainder ncarried = nidx-nload to the left, then refill:
918 * |---- ncarried ----||--- (MAXSEQ-ncarried) ---|
919 * |-------------- MAXSEQ -----------------------|
920 * while watching out for the terminal case where we run out of
921 * data, loading less than (MAXSEQ-ncarried) records:
922 * |---- ncarried ----||--- nidx* ---|
923 * |------------- nidx --------------|
924 * where the <nidx*> is what fread() returns to us.
925 */
926 i0 += nload; // this chunk starts with seq #<i0>
927 ncarried = (nidx - nload);
928 memmove(idx, idx + nload, sizeof(ESL_DSQDATA_RECORD) * ncarried);
929 nidx = fread(idx + ncarried, sizeof(ESL_DSQDATA_RECORD), dd->chunk_maxseq - ncarried, dd->ifp);
930 nidx += ncarried; // usually, this'll be MAXSEQ, unless we're near EOF.
931
932 if (nidx == 0) // then we're EOD.
933 {
934 //printf("loader: reached EOD.\n");
935 dsqdata_chunk_Destroy(chu);
936 nalloc--; // we'd counted that chunk towards <nalloc>.
937 break; // this is the only way out of loader's main loop
938 }
939
940
941 /* Figure out how many sequences we're going to load: <nload>
942 * nload = max i : i <= MAXSEQ && idx[i].psq_end - psq_last <= CHUNK_MAX
943 */
944 ESL_DASSERT1(( idx[0].psq_end - psq_last <= dd->chunk_maxpacket ));
945 if (idx[nidx-1].psq_end - psq_last <= dd->chunk_maxpacket)
946 nload = nidx;
947 else
948 { // Binary search for nload = max_i idx[i-1].psq_end - lastend <= MAX
949 int righti = nidx;
950 int mid;
951 nload = 1;
952 while (righti - nload > 1)
953 {
954 mid = nload + (righti - nload) / 2;
955 if (idx[mid-1].psq_end - psq_last <= dd->chunk_maxpacket) nload = mid;
956 else righti = mid;
957 }
958 }
959
960 /* Read packed sequence. */
961 //printf("loader: loading chunk %d from disk.\n", (int) nchunk+1);
962
963 chu->pn = idx[nload-1].psq_end - psq_last;
964 nread = fread(chu->psq, sizeof(uint32_t), chu->pn, dd->sfp);
965 //printf("Read %d packed ints from seq file\n", nread);
966 if ( nread != chu->pn ) ESL_XEXCEPTION(eslEOD, "dsqdata packet loader: expected %d, got %d", chu->pn, nread);
967
968
969 /* Read metadata, reallocating if needed */
970 nmeta = idx[nload-1].metadata_end - meta_last;
971 if (nmeta > chu->mdalloc) {
972 ESL_REALLOC(chu->metadata, sizeof(char) * nmeta); // should be realloc by doubling instead?
973 chu->mdalloc = nmeta;
974 }
975 nread = fread(chu->metadata, sizeof(char), nmeta, dd->mfp);
976 if ( nread != nmeta ) ESL_XEXCEPTION(eslEOD, "dsqdata metadata loader: expected %d, got %d", nmeta, nread);
977
978 chu->i0 = i0;
979 chu->N = nload;
980 psq_last = idx[nload-1].psq_end;
981 meta_last = idx[nload-1].metadata_end;
982
983 /* Put chunk in appropriate outbox.
984 */
985 u = nchunk % dd->n_unpackers; // note this is the loader's own private <nchunk> counter, not the consumer-shared one in <dd>
986 //printf("loader: about to put chunk %d into inbox %d\n", (int) nchunk+1, u);
987 if ( pthread_mutex_lock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
988 while (dd->inbox[u] != NULL) {
989 if (pthread_cond_wait(&(dd->inbox_cv[u]), &(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
990 }
991 dd->inbox[u] = chu;
992 if ( pthread_mutex_unlock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
993 if ( pthread_cond_signal(&(dd->inbox_cv[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed");
994 //printf("loader: finished putting chunk %d into inbox %d\n", (int) nchunk+1, u);
995
996 nchunk++;
997 }
998
999 /* Cleanup time. First, set all unpacker inboxes to EOD state. (We overwrite <u> here.)
1000 */
1001 for (u = 0; u < dd->n_unpackers; u++)
1002 {
1003 //printf("loader: setting EOD on inbox %d\n", u);
1004 if ( pthread_mutex_lock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
1005 while (dd->inbox[u] != NULL) {
1006 if (pthread_cond_wait(&(dd->inbox_cv[u]), &(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
1007 }
1008 dd->inbox_eod[u] = TRUE; // we know inbox[u] is already NULL
1009 if ( pthread_mutex_unlock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
1010 if ( pthread_cond_signal(&(dd->inbox_cv[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed");
1011 }
1012
1013
1014 /* Then, wait to get all our chunks back through the recycling, so we
1015 * can free them and exit cleanly. We counted them as they went out,
1016 * in <nalloc>, so we know how many need to come home to roost.
1017 */
1018 while (nalloc)
1019 {
1020 //printf("loader: clearing recycling, %d chunks left to free\n", nalloc);
1021 if ( pthread_mutex_lock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
1022 while (dd->recycling == NULL) { // Readers may still be working, will Recycle() their chunks
1023 if ( pthread_cond_wait(&dd->recycling_cv, &dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
1024 }
1025 while (dd->recycling != NULL) { // Free entire stack, while we have the mutex locked.
1026 chu = dd->recycling;
1027 dd->recycling = chu->nxt;
1028 dsqdata_chunk_Destroy(chu);
1029 nalloc--;
1030 }
1031 if ( pthread_mutex_unlock(&dd->recycling_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
1032 /* Because the recycling is a stack, consumers never have to wait
1033 * on a condition to Recycle(), so we don't need to signal anything.
1034 */
1035 }
1036 //printf("loader: exiting\n");
1037 free(idx);
1038 pthread_exit(NULL);
1039
1040 ERROR:
1041 /* Defying Easel standards, we treat all exceptions as fatal, at
1042 * least for the moment. This isn't a problem in HMMER, Infernal
1043 * because they already use fatal exception handlers (i.e., we never
1044 * reach this code anyway, if the parent app is using default fatal
1045 * exception handling). It would become a problem if an Easel-based
1046 * app needs to assure no exits from within Easel. Because the other
1047 * threads will block waiting for chunks to come from the loader, if
1048 * the loader fails, we would need a back channel signal of some
1049 * sort to get the other threads to clean up and terminate.
1050 */
1051 if (idx) free(idx);
1052 esl_fatal(" ... dsqdata loader thread failed: unrecoverable");
1053 }
1054
1055
1056
1057 static void *
1058 dsqdata_unpacker_thread(void *p)
1059 {
1060 ESL_DSQDATA *dd = (ESL_DSQDATA *) p;
1061 ESL_DSQDATA_CHUNK *chu = NULL;
1062 pthread_t my_id = pthread_self();
1063 int u;
1064 int status;
1065
1066 /* Don't use <dd> until we get the structure-is-ready signal */
1067 if ( pthread_mutex_lock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
1068 while (! dd->go) {
1069 if ( pthread_cond_wait(&dd->go_cv, &dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_cond_wait failed on go_cv");
1070 }
1071 if ( pthread_mutex_unlock(&dd->go_mutex) != 0) ESL_XEXCEPTION(eslESYS, "pthread_mutex_lock failed on go_mutex");
1072
1073 /* There may be more than one unpacker. Figure out who we are, so we
1074 * know which slot is ours. (This is why it's especially important
1075 * for the unpacker threads to wait for <dd> to be fully
1076 * initialized.)
1077 */
1078 for (u = 0; u < dd->n_unpackers; u++)
1079 if ( pthread_equal(my_id, dd->unpacker_t[u] )) break;
1080 if (u >= dd->n_unpackers) esl_fatal("unpacker failed to figure out its identity");
1081
1082 //printf("unpacker thread %d: ready.\n", u);
1083
1084 /* Ready. Let's go. */
1085 do {
1086 //printf("unpacker thread %d: checking for next chunk.\n", u);
1087
1088 /* Get a chunk from loader in our inbox. Wait if necessary. */
1089 if ( pthread_mutex_lock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
1090 while (! dd->inbox_eod[u] && dd->inbox[u] == NULL) {
1091 if ( pthread_cond_wait(&(dd->inbox_cv[u]), &(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
1092 }
1093 chu = dd->inbox[u]; // NULL if we're EOD
1094 dd->inbox[u] = NULL;
1095 if ( pthread_mutex_unlock(&(dd->inbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
1096
1097 //if (chu) printf("unpacker thread %d: took encoded chunk from inbox\n", u);
1098 //else printf("unpacker thread %d: EOD\n", u);
1099
1100 if (chu) {
1101 /* only need to signal inbox change to the loader if we're not EOD */
1102 if ( pthread_cond_signal(&(dd->inbox_cv[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed");
1103 /* unpack it */
1104 if (( status = dsqdata_unpack_chunk(chu, dd->pack5)) != eslOK) goto ERROR;
1105 }
1106
1107 /* Put unpacked chunk into the unpacker's outbox, or set EOD status.
1108 * May need to wait for it to be empty/available.
1109 */
1110 if ( pthread_mutex_lock(&(dd->outbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex lock failed");
1111 while (dd->outbox[u] != NULL) {
1112 if ( pthread_cond_wait(&(dd->outbox_cv[u]), &(dd->outbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond wait failed");
1113 }
1114 dd->outbox[u] = chu; // that's NULL if we're EOD
1115 if (! chu) dd->outbox_eod[u] = TRUE;
1116 if ( pthread_mutex_unlock(&(dd->outbox_mutex[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread mutex unlock failed");
1117 if ( pthread_cond_signal(&(dd->outbox_cv[u])) != 0) ESL_XEXCEPTION(eslESYS, "pthread cond signal failed");
1118
1119 //if (chu) printf("unpacker thread %d: placed unpacked chunk on outbox\n", u);
1120 //else printf("unpacker thread %d: exiting EOD\n", u);
1121 } while (chu);
1122 pthread_exit(NULL);
1123
1124 ERROR:
1125 /* See comment in loader thread: for lack of a back channel mechanism
1126 * to tell other threads to clean up and terminate, we violate Easel standards
1127 * and turn nonfatal exceptions into fatal ones.
1128 */
1129 esl_fatal(" ... dsqdata unpacker thread failed: unrecoverable");
1130 }
1131
1132
1133 /*****************************************************************
1134 * 5. Packing sequences and unpacking chunks
1135 *****************************************************************/
1136
1137 /* dsqdata_unpack_chunk()
1138 *
1139 * <do_pack5> is a hint: if caller knows that all the packets in the
1140 * chunk are 5-bit encoded (i.e. amino acid sequence), it can pass
1141 * <TRUE>, enabling a small optimization. Otherwise the packed
1142 * sequences will be treated as mixed 2- and 5-bit encoding, as is
1143 * needed for DNA/RNA sequences; protein sequences also unpack fine
1144 * that way, but the 5-bit flag on every packet needs to be checked.
1145 *
1146 * Throws: <eslEFORMAT> if a problem is seen in the binary format
1147 */
1148 static int
1149 dsqdata_unpack_chunk(ESL_DSQDATA_CHUNK *chu, int do_pack5)
1150 {
1151 char *ptr = chu->metadata; // ptr will walk through metadata
1152 int r; // position in unpacked dsq array
1153 int i; // sequence index: 0..chu->N-1
1154 int pos; // position in packet array
1155 int L; // an unpacked sequence length
1156 int P; // number of packets unpacked
1157
1158 /* "Unpack" the metadata */
1159 for (i = 0; i < chu->N; i++)
1160 {
1161 /* The data are user input, so we cannot trust that it has \0's where we expect them. */
1162 if ( ptr >= chu->metadata + chu->mdalloc) ESL_EXCEPTION(eslEFORMAT, "metadata format error");
1163 chu->name[i] = ptr; ptr = 1 + strchr(ptr, '\0'); if ( ptr >= chu->metadata + chu->mdalloc) ESL_EXCEPTION(eslEFORMAT, "metadata format error");
1164 chu->acc[i] = ptr; ptr = 1 + strchr(ptr, '\0'); if ( ptr >= chu->metadata + chu->mdalloc) ESL_EXCEPTION(eslEFORMAT, "metadata format error");
1165 chu->desc[i] = ptr; ptr = 1 + strchr(ptr, '\0'); if ( ptr >= chu->metadata + chu->mdalloc) ESL_EXCEPTION(eslEFORMAT, "metadata format error");
1166 chu->taxid[i] = (int32_t) *((int32_t *) ptr); ptr += sizeof(int32_t);
1167 }
1168
1169 /* Unpack the sequence data */
1170 i = 0;
1171 r = 0;
1172 pos = 0;
1173 chu->smem[0] = eslDSQ_SENTINEL; // This initialization is why <smem> needs to be unsigned.
1174 while (pos < chu->pn)
1175 {
1176 chu->dsq[i] = (ESL_DSQ *) chu->smem + r;
1177 if (do_pack5) dsqdata_unpack5(chu->psq + pos, chu->dsq[i], &L, &P);
1178 else dsqdata_unpack2(chu->psq + pos, chu->dsq[i], &L, &P);
1179
1180 r += L+1; // L+1, not L+2, because we overlap start/end sentinels
1181 pos += P;
1182 chu->L[i] = L;
1183 i++;
1184 }
1185
1186 ESL_DASSERT1(( pos == chu->pn )); // we should've unpacked exactly pn packets,
1187 ESL_DASSERT1(( i == chu->N )); // .. and exactly N sequences.
1188 return eslOK;
1189 }
1190
1191
1192 /* Unpack 5-bit encoded sequence, starting at <psq>.
1193 * Important: dsq[0] is already initialized to eslDSQ_SENTINEL,
1194 * as a nitpicky optimization (the sequence data in a chunk are
1195 * concatenated so that they share end/start sentinels).
1196 */
1197 static int
1198 dsqdata_unpack5(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P)
1199 {
1200 int pos = 0; // position in psq[]
1201 int r = 1; // position in dsq[]. caller set dsq[0] to eslDSQ_SENTINEL.
1202 uint32_t v = psq[pos++];
1203 int b; // bit shift counter
1204
1205 while (! ESL_DSQDATA_EOD(v)) // we trust that we'll see a sentinel at the end
1206 {
1207 ESL_DASSERT1(( ESL_DSQDATA_5BIT(v) )); // All packets are 5-bit encoded
1208 dsq[r++] = (v >> 25) & 31; dsq[r++] = (v >> 20) & 31; dsq[r++] = (v >> 15) & 31;
1209 dsq[r++] = (v >> 10) & 31; dsq[r++] = (v >> 5) & 31; dsq[r++] = (v >> 0) & 31;
1210 v = psq[pos++];
1211 }
1212
1213 /* Unpack sentinel packet, which may be partial; it can even contain
1214 * zero residues in the edge case of an L=0 sequence.
1215 */
1216 ESL_DASSERT1(( ESL_DSQDATA_5BIT(v) ));
1217 for (b = 25; b >= 0 && ((v >> b) & 31) != 31; b -= 5)
1218 dsq[r++] = (v >> b) & 31;
1219 dsq[r++] = eslDSQ_SENTINEL;
1220 // r is now L+2: the raw sequence length + 2 sentinels
1221 // P = pos, because pos index advanced to next packet after sentinel
1222 *ret_L = r-2;
1223 *ret_P = pos;
1224 return eslOK;
1225 }
1226
1227 /* Unpack 2-bit (+ mixed 5-bit for noncanonicals) encoding.
1228 * Important: dsq[0] is already initialized to eslDSQ_SENTINEL
1229 *
1230 * This will work for protein sequences just fine; just a little
1231 * slower than calling dsqdata_unpack5(), because here we have
1232 * to check the 5-bit encoding bit on every packet.
1233 */
1234 static int
1235 dsqdata_unpack2(uint32_t *psq, ESL_DSQ *dsq, int *ret_L, int *ret_P)
1236 {
1237 int pos = 0;
1238 int r = 1;
1239 uint32_t v = psq[pos++];
1240 int b; // bit shift counter
1241
1242 while (! ESL_DSQDATA_EOD(v))
1243 {
1244 if ( ESL_DSQDATA_5BIT(v)) // 5-bit encoded, full. Don't need mask on bit 31 because we know it's down.
1245 {
1246 dsq[r++] = (v >> 25) & 31; dsq[r++] = (v >> 20) & 31; dsq[r++] = (v >> 15) & 31;
1247 dsq[r++] = (v >> 10) & 31; dsq[r++] = (v >> 5) & 31; dsq[r++] = (v >> 0) & 31;
1248 }
1249 else // 2-bit encoded, full
1250 {
1251 dsq[r++] = (v >> 28) & 3; dsq[r++] = (v >> 26) & 3; dsq[r++] = (v >> 24) & 3;
1252 dsq[r++] = (v >> 22) & 3; dsq[r++] = (v >> 20) & 3; dsq[r++] = (v >> 18) & 3;
1253 dsq[r++] = (v >> 16) & 3; dsq[r++] = (v >> 14) & 3; dsq[r++] = (v >> 12) & 3;
1254 dsq[r++] = (v >> 10) & 3; dsq[r++] = (v >> 8) & 3; dsq[r++] = (v >> 6) & 3;
1255 dsq[r++] = (v >> 4) & 3; dsq[r++] = (v >> 2) & 3; dsq[r++] = (v >> 0) & 3;
1256 }
1257 v = psq[pos++];
1258 }
1259
1260 /* Sentinel packet.
1261 * If 2-bit, it's full. If 5-bit, it's usually partial, and may even be 0-len.
1262 */
1263 if ( ESL_DSQDATA_5BIT(v)) // 5-bit, partial
1264 {
1265 for (b = 25; b >= 0 && ((v >> b) & 31) != 31; b -= 5)
1266 dsq[r++] = (v >> b) & 31;
1267 }
1268 else
1269 {
1270 dsq[r++] = (v >> 28) & 3; dsq[r++] = (v >> 26) & 3; dsq[r++] = (v >> 24) & 3;
1271 dsq[r++] = (v >> 22) & 3; dsq[r++] = (v >> 20) & 3; dsq[r++] = (v >> 18) & 3;
1272 dsq[r++] = (v >> 16) & 3; dsq[r++] = (v >> 14) & 3; dsq[r++] = (v >> 12) & 3;
1273 dsq[r++] = (v >> 10) & 3; dsq[r++] = (v >> 8) & 3; dsq[r++] = (v >> 6) & 3;
1274 dsq[r++] = (v >> 4) & 3; dsq[r++] = (v >> 2) & 3; dsq[r++] = (v >> 0) & 3;
1275 }
1276 dsq[r++] = eslDSQ_SENTINEL;
1277
1278 *ret_L = r-2;
1279 *ret_P = pos;
1280 return eslOK;
1281 }
1282
1283
1284 /* dsqdata_pack5()
1285 *
1286 * Pack a digital (protein) sequence <dsq> of length <n>, into <psq>
1287 * using 5-bit encoding; return the number of packets <*ret_P>.
1288 *
1289 * <psq> must be allocated for at least $MAX(1, (n+5)/6)$ packets.
1290 *
1291 * You can pack in place, by passing the same pointer <dsq> as <psq>,
1292 * provided that dsq is allocated for at least 1 packet (4 bytes). We
1293 * know that <psq> is either smaller than <dsq> ($4P <= n$) or that it
1294 * consists of one EOD packet (in the case n=0).
1295 */
1296 static int
1297 dsqdata_pack5(ESL_DSQ *dsq, int n, uint32_t *psq, int *ret_P)
1298 {
1299 int r = 1; // position in <dsq>
1300 int pos = 0; // position in <psq>.
1301 int b; // bitshift
1302 uint32_t v; // tmp var needed to guarantee pack-in-place works
1303
1304 while (r <= n)
1305 {
1306 v = eslDSQDATA_5BIT; // initialize packet with 5-bit flag
1307 for (b = 25; b >= 0 && r <= n; b -= 5) v |= (uint32_t) dsq[r++] << b;
1308 for ( ; b >= 0; b -= 5) v |= (uint32_t) 31 << b;
1309
1310 if (r > n) v |= eslDSQDATA_EOD; // EOD bit
1311 psq[pos++] = v; // we know we've already read all the dsq we need under psq[pos]
1312 }
1313
1314 /* Special case of n=0: we need an empty EOD sentinel packet. */
1315 if (pos == 0) { v = 0; psq[pos++] = ~v; } // all bits set: | EOD | 5BIT | all sentinels |
1316
1317 *ret_P = pos;
1318 return eslOK;
1319 }
1320
1321
1322 /* dsqdata_pack2()
1323 *
1324 * Pack a digital (nucleic) sequence <dsq> of total length
1325 * <n>, into <psq>; return the number of packets <*ret_P>.
1326 *
1327 * <psq> must be allocated for at least $MAX(1, (n+5)/6)$ packets.
1328 * (Yes, even in 2-bit packing, because worst case, the sequence
1329 * contains so many noncanonicals that it's entirely 5-bit encoded.)
1330 *
1331 * You can pack in place, by passing the same pointer <dsq> as <psq>,
1332 * provided that dsq is allocated for at least 1 packet (4 bytes). We
1333 * know that <psq> is either smaller than <dsq> ($4P <= n$) or that it
1334 * consists of one EOD packet (in the case n=0).
1335 */
1336 static int
1337 dsqdata_pack2(ESL_DSQ *dsq, int n, uint32_t *psq, int *ret_P)
1338 {
1339 int pos = 0; // position in <psq>
1340 int d = 0; // position of next degen residue, 1..n, n+1 if none
1341 int r = 1; // position in <dsq> 1..n
1342 int b; // bitshift
1343 uint32_t v; // tmp var needed to guarantee pack-in-place works
1344
1345 while (r <= n)
1346 {
1347 // Slide the "next degenerate residue" detector
1348 if (d < r)
1349 for (d = r; d <= n; d++)
1350 if (dsq[d] > 3) break;
1351
1352 // Can we 2-bit pack the next 15 residues, r..r+14?
1353 // n-r+1 = number of residues remaining to be packed.
1354 if (n-r+1 >= 15 && d > r+14)
1355 {
1356 v = 0;
1357 for (b = 28; b >= 0; b -=2) v |= (uint32_t) dsq[r++] << b;
1358 }
1359 else
1360 {
1361 v = eslDSQDATA_5BIT; // initialize v with 5-bit packing bit
1362 for (b = 25; b >= 0 && r <= n; b -= 5) v |= (uint32_t) dsq[r++] << b;
1363 for ( ; b >= 0; b -= 5) v |= (uint32_t) 31 << b;
1364 }
1365
1366 if (r > n) v |= eslDSQDATA_EOD; // EOD bit
1367 psq[pos++] = v; // we know we've already read all the dsq we need under psq[pos]
1368 }
1369
1370 /* Special case of n=0: we need an empty EOD sentinel packet.
1371 * Sentinel packets are 5-bit encoded, even in 2-bit coding scheme
1372 */
1373 if (pos == 0) { v = 0; psq[pos++] = ~v; } // all bits set: | EOD | 5BIT | all sentinels |
1374
1375 *ret_P = pos;
1376 return eslOK;
1377 }
1378
1379
1380 /*****************************************************************
1381 * 6. Notes
1382 *****************************************************************
1383 *
1384 * [1] Packed sequence data format.
1385 *
1386 * Format of a single packet:
1387 * [31] [30] [29..25] [24..20] [19..15] [14..10] [ 9..5 ] [ 4..0 ]
1388 * ^ ^ |------------ 6 5-bit packed residues ------------------|
1389 * | | [] [] [] [] [] [] [] [] [] [] [] [] [] [] []
1390 * | | |----------- or 15 2-bit packed residues ----------------|
1391 * | |
1392 * | "packtype" bit 30 = 0 if packet is 2-bit packed; 1 if 5-bit packed
1393 * "sentinel" bit 31 = 1 if last packet in packed sequence; else 0
1394 *
1395 * (packet & (1 << 31)) tests for end of sequence
1396 * (packet & (1 << 30)) tests for 5-bit packing vs. 2-bit
1397 * ((packet >> shift) && 31) decodes 5-bit, for shift=25..0 in steps of 5
1398 * ((packet >> shift) && 3) decodes 2-bit, for shift=28..0 in steps of 2
1399 *
1400 * Packets without the sentinel bit set are always full (unpack
1401 * to 15 or 6 residue codes).
1402 *
1403 * 5-bit EOD packets may be partial: they unpack to 0..6
1404 * residues. The remaining residue codes are set to 0x1f
1405 * (11111) to indicate EOD within a partial packet.
1406 *
1407 * A 0-length sequence is encoded by a 5-bit partial EOD packet
1408 * with 0 residues. This is the only case in which a partial
1409 * packet contains 0 residues. (Because we can end with an EOD
1410 * full packet, there is no other case where we end up with 0
1411 * leftover residues to encode.)
1412 *
1413 * 2-bit EOD packets must be full, because there is no way to
1414 * signal EOD locally within a 2-bit packet. Can't use 0x03 (11)
1415 * because that's T/U. Generally, then, the last packet of a
1416 * nucleic acid sequence must be 5-bit encoded, solely to be
1417 * able to encode EOD in a partial packet.
1418 *
1419 * A packed sequence consists of an integer number of packets,
1420 * P, which ends with an EOD packet that may contain a partial
1421 * number of residues. P packets are guaranteed to be able to
1422 * encode at least 6P residues in either scheme.
1423 *
1424 * A sequence of length L packs into P <= MAX(1, (N+5)/6)
1425 * packets. (1, because a 0-length sequence still requires an
1426 * EOD packet.) This is true even for nucleic sequences, because
1427 * noncanonical residues can force DNA/RNA sequence to pack
1428 * entirely in 5-bit coding.
1429 *
1430 * A packed amino acid sequence unpacks to 6P-5 <= L <= 6P
1431 * residues (for P>1; 0 <= L <= 6 for P=1) and all packets are
1432 * 5-bit encoded.
1433 *
1434 * A packed nucleic acid sequence unpacks to 6P-5 <= L <= 15P
1435 * residues (for P>1; 0 <= L <= 15 for P=1). The packets are a
1436 * mix of 2-bit and 5-bit. Degenerate residues must be 5-bit
1437 * packed, and the EOD packet usually is too. A 5-bit packet
1438 * does not have to contain degenerate residues, because it may
1439 * have been necessary to get "in frame" to pack a downstream
1440 * degenerate residue. For example, the sequence
1441 * ACGTACGTNNA... must be packed as [ACGTAC][CGTNNA]... to get
1442 * the N's packed correctly.
1443 *
1444 * [2] Compression: relative incompressibility of biological sequences.
1445 *
1446 * Considered using fast (de)compression algorithms that are fast
1447 * enough to keep up with disk read speed, including LZ4 and
1448 * Google's Snappy. However, lz4 only achieves 1.0-1.9x global
1449 * compression of protein sequence (compared to 1.5x for
1450 * packing), and 2.0x for DNA (compared to 3.75x for packing).
1451 * With local, blockwise compression, which we need for random
1452 * access and indexing, it gets worse. Packing is superior.
1453 *
1454 * Metadata compression is more feasible, but I still opted
1455 * against it. Although metadata are globally quite compressible
1456 * (3.2-6.9x in trials with lz4), locally in 64K blocks lz4 only
1457 * achieves 2x. [xref SRE:2016/0201-seqfile-compression]
1458 *
1459 * [3] Maybe getting more packing using run-length encoding.
1460 *
1461 * Genome assemblies typically have long runs of N's (human
1462 * GRCh38.p2 is about 5% N), and it's excruciating to have to
1463 * pack it into bulky 5-bit degenerate packets. I considered
1464 * run-length encoding (RLE). One possibility is to use a special
1465 * packet format akin to the 5-bit packet format:
1466 *
1467 * [0] [?] [11111] [.....] [....................]
1468 * ^ ^ ^ 20b number, <=2^20-1
1469 * | | 5-bit residue code
1470 * | sentinel residue 31 set
1471 * sentinel bit unset
1472 *
1473 * This is a uniquely detectable packet structure because a full
1474 * packet (with unset sentinel bit) would otherwise never contain
1475 * a sentinel residue (code 31).
1476 *
1477 * However, using RLE would make our unpacked data sizes too
1478 * unpredictable; we wouldn't have the <=6P or <=15P guarantee,
1479 * so we couldn't rely on fixed-length allocation of <smem> in
1480 * our chunk. Consumers wouldn't be getting predictable chunk
1481 * sizes, which could complicate load balancing. I decided
1482 * against it.
1483 */
1484
1485
1486 /*****************************************************************
1487 * 7. Unit tests
1488 *****************************************************************/
1489 #ifdef eslDSQDATA_TESTDRIVE
1490
1491 #include "esl_randomseq.h"
1492
1493 /* Exercise the packing and unpacking routines:
1494 * dsqdata_pack2, dsqdata_pack5, and dsqdata_unpack
1495 */
1496 static void
1497 utest_packing(ESL_RANDOMNESS *rng, ESL_ALPHABET *abc, int nsamples)
1498 {
1499 char msg[] = "esl_dsqdata :: packing unit test failed";
1500 ESL_DSQ *dsq = NULL; // We start with a dirty random sequence...
1501 uint32_t *psq = NULL; // ... pack it ...
1502 ESL_DSQ *dsq2 = NULL; // ... and unpack it. Then check that it's the same seq.
1503 int L_max = 46; // We'll sample L on 0..L_max. L_max doesn't need to be large to exercise well.
1504 int P_max = ESL_MAX(1, (L_max + 5) / 6); // So sayeth the docs, so let's test it.
1505 int L, P, L2, P2;
1506 int i;
1507
1508 if ((dsq = malloc(sizeof(ESL_DSQ) * (L_max + 2))) == NULL) esl_fatal(msg);
1509 if ((psq = malloc(sizeof(uint32_t) * P_max)) == NULL) esl_fatal(msg);
1510 if ((dsq2 = malloc(sizeof(ESL_DSQ) * (L_max + 2))) == NULL) esl_fatal(msg);
1511
1512 for (i = 0; i < nsamples; i++)
1513 {
1514 L = esl_rnd_Roll(rng, L_max+1); // 0..L_max
1515
1516 esl_rsq_SampleDirty(rng, abc, NULL, L, dsq);
1517
1518 if (abc->type == eslAMINO) { if ( dsqdata_pack5(dsq, L, psq, &P) != eslOK) esl_fatal(msg); }
1519 else { if ( dsqdata_pack2(dsq, L, psq, &P) != eslOK) esl_fatal(msg); }
1520
1521 dsq2[0] = eslDSQ_SENTINEL; // interface to _unpack functions requires caller to do this
1522 if (abc->type == eslAMINO) { if ( dsqdata_unpack5(psq, dsq2, &L2, &P2) != eslOK) esl_fatal(msg); }
1523 else { if ( dsqdata_unpack2(psq, dsq2, &L2, &P2) != eslOK) esl_fatal(msg); }
1524
1525 if (L2 != L) esl_fatal(msg);
1526 if (P2 != P) esl_fatal(msg);
1527 if (memcmp((void *) dsq, (void *) dsq2, L+2) != 0) esl_fatal(msg);
1528
1529 /* Write garbage into the buffers, so nobody's cheating on the test somehow */
1530 esl_rnd_mem(rng, (void *) dsq, L_max+2);
1531 esl_rnd_mem(rng, (void *) dsq2, L_max+2);
1532 esl_rnd_mem(rng, (void *) psq, (sizeof(uint32_t) * P_max));
1533 }
1534
1535 free(dsq);
1536 free(psq);
1537 free(dsq2);
1538 }
1539
1540
1541 static void
1542 utest_readwrite(ESL_RANDOMNESS *rng, ESL_ALPHABET *abc)
1543 {
1544 char msg[] = "esl_dsqdata :: readwrite unit test failed";
1545 char tmpfile[16] = "esltmpXXXXXX";
1546 char basename[32];
1547 ESL_SQ **sqarr = NULL;
1548 FILE *tmpfp = NULL;
1549 ESL_SQFILE *sqfp = NULL;
1550 ESL_DSQDATA *dd = NULL;
1551 ESL_DSQDATA_CHUNK *chu = NULL;
1552 int nseq = 1 + esl_rnd_Roll(rng, 20000); // 1..20000
1553 int maxL = 100;
1554 int i;
1555 int status;
1556
1557 /* 1. Sample <nseq> random dirty digital sequences, storing them for later comparison;
1558 * write them out to a tmp FASTA file. The Easel FASTA format writer writes <name> <acc>
1559 * <desc> on the descline, but the reader only reads <name> <desc> (as is standard
1560 * for FASTA format), so blank the accession to avoid confusion.
1561 */
1562 if (( status = esl_tmpfile_named(tmpfile, &tmpfp)) != eslOK) esl_fatal(msg);
1563 if (( sqarr = malloc(sizeof(ESL_SQ *) * nseq)) == NULL) esl_fatal(msg);
1564 for (i = 0; i < nseq; i++)
1565 {
1566 sqarr[i] = NULL;
1567 if (( status = esl_sq_Sample(rng, abc, maxL, &(sqarr[i]))) != eslOK) esl_fatal(msg);
1568 if (( status = esl_sq_SetAccession(sqarr[i], "")) != eslOK) esl_fatal(msg);
1569 if (( status = esl_sqio_Write(tmpfp, sqarr[i], eslSQFILE_FASTA, FALSE)) != eslOK) esl_fatal(msg);
1570 }
1571 fclose(tmpfp);
1572
1573 /* 2. Make a dsqdata database from the FASTA tmpfile.
1574 */
1575 if (( status = esl_sqfile_OpenDigital(abc, tmpfile, eslSQFILE_FASTA, NULL, &sqfp)) != eslOK) esl_fatal(msg);
1576 if (( snprintf(basename, 32, "%s-db", tmpfile)) <= 0) esl_fatal(msg);
1577 if (( status = esl_dsqdata_Write(sqfp, basename, NULL)) != eslOK) esl_fatal(msg);
1578 esl_sqfile_Close(sqfp);
1579
1580 /* 3. Open and read the dsqdata; compare to the original sequences.
1581 */
1582 if (( status = esl_dsqdata_Open(&abc, basename, 1, &dd)) != eslOK) esl_fatal(msg);
1583 while (( status = esl_dsqdata_Read(dd, &chu)) == eslOK)
1584 {
1585 for (i = 0; i < chu->N; i++)
1586 {
1587 if ( chu->L[i] != sqarr[i+chu->i0]->n ) esl_fatal(msg);
1588 if ( memcmp( chu->dsq[i], sqarr[i+chu->i0]->dsq, chu->L[i]) != 0) esl_fatal(msg);
1589 if ( strcmp( chu->name[i], sqarr[i+chu->i0]->name) != 0) esl_fatal(msg);
1590 // FASTA does not read accession - instead we get both accession/description as <desc>
1591 if ( strcmp( chu->desc[i], sqarr[i+chu->i0]->desc) != 0) esl_fatal(msg);
1592 // FASTA also does not store taxid - so don't test that either
1593 }
1594 esl_dsqdata_Recycle(dd, chu);
1595 }
1596 if (status != eslEOF) esl_fatal(msg);
1597 esl_dsqdata_Close(dd);
1598
1599 remove(tmpfile);
1600 remove(basename);
1601 snprintf(basename, 32, "%s-db.dsqi", tmpfile); remove(basename);
1602 snprintf(basename, 32, "%s-db.dsqm", tmpfile); remove(basename);
1603 snprintf(basename, 32, "%s-db.dsqs", tmpfile); remove(basename);
1604 for (i = 0; i < nseq; i++) esl_sq_Destroy(sqarr[i]);
1605 free(sqarr);
1606 }
1607 #endif /*eslDSQDATA_TESTDRIVE*/
1608
1609
1610
1611 /*****************************************************************
1612 * 8. Test driver
1613 *****************************************************************/
1614 #ifdef eslDSQDATA_TESTDRIVE
1615
1616 #include "easel.h"
1617 #include "esl_alphabet.h"
1618 #include "esl_dsqdata.h"
1619 #include "esl_getopts.h"
1620 #include "esl_random.h"
1621
1622 static ESL_OPTIONS options[] = {
1623 /* name type default env range toggles reqs incomp help docgroup*/
1624 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1625 { "-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1626 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1627 };
1628 static char usage[] = "[-options]";
1629 static char banner[] = "unit test driver for Easel dsqdata module";
1630
1631 int
1632 main(int argc, char **argv)
1633 {
1634 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1635 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1636 ESL_ALPHABET *amino = esl_alphabet_Create(eslAMINO);
1637 ESL_ALPHABET *nucleic = esl_alphabet_Create(eslRNA);
1638 int nsamples = 100;
1639
1640 fprintf(stderr, "## %s\n", argv[0]);
1641 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
1642
1643 utest_packing(rng, nucleic, nsamples);
1644 utest_packing(rng, amino, nsamples);
1645
1646 utest_readwrite(rng, nucleic);
1647 utest_readwrite(rng, amino);
1648
1649 fprintf(stderr, "# status = ok\n");
1650
1651 esl_alphabet_Destroy(amino);
1652 esl_alphabet_Destroy(nucleic);
1653 esl_randomness_Destroy(rng);
1654 esl_getopts_Destroy(go);
1655 exit(0);
1656 }
1657 #endif /*eslDSQDATA_TESTDRIVE*/
1658
1659 /*****************************************************************
1660 * 9. Examples
1661 *****************************************************************/
1662
1663 /* esl_dsqdata_example2
1664 * Example of creating a new dsqdata database from a sequence file.
1665 */
1666 #ifdef eslDSQDATA_EXAMPLE2
1667 #include "easel.h"
1668 #include "esl_alphabet.h"
1669 #include "esl_dsqdata.h"
1670 #include "esl_getopts.h"
1671
1672 static ESL_OPTIONS options[] = {
1673 /* name type default env range toggles reqs incomp help docgroup*/
1674 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1675 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use DNA alphabet", 0 },
1676 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use RNA alphabet", 0 },
1677 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use protein alphabet", 0 },
1678 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1679 };
1680 static char usage[] = "[-options] <seqfile_in> <binary seqfile_out>";
1681 static char banner[] = "experimental: create binary database for esl_dsqdata";
1682
1683 int
1684 main(int argc, char **argv)
1685 {
1686 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 2, argc, argv, banner, usage);
1687 ESL_ALPHABET *abc = NULL;
1688 char *infile = esl_opt_GetArg(go, 1);
1689 char *basename = esl_opt_GetArg(go, 2);
1690 int format = eslSQFILE_UNKNOWN;
1691 int alphatype = eslUNKNOWN;
1692 ESL_SQFILE *sqfp = NULL;
1693 char errbuf[eslERRBUFSIZE];
1694 int status;
1695
1696 status = esl_sqfile_Open(infile, format, NULL, &sqfp);
1697 if (status == eslENOTFOUND) esl_fatal("No such file.");
1698 else if (status == eslEFORMAT) esl_fatal("Format unrecognized.");
1699 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
1700
1701 if (esl_opt_GetBoolean(go, "--rna")) alphatype = eslRNA;
1702 else if (esl_opt_GetBoolean(go, "--dna")) alphatype = eslDNA;
1703 else if (esl_opt_GetBoolean(go, "--amino")) alphatype = eslAMINO;
1704 else {
1705 status = esl_sqfile_GuessAlphabet(sqfp, &alphatype);
1706 if (status == eslENOALPHABET) esl_fatal("Couldn't guess alphabet from first sequence in %s", infile);
1707 else if (status == eslEFORMAT) esl_fatal("Parse failed (sequence file %s)\n%s\n", infile, sqfp->get_error(sqfp));
1708 else if (status == eslENODATA) esl_fatal("Sequence file %s contains no data?", infile);
1709 else if (status != eslOK) esl_fatal("Failed to guess alphabet (error code %d)\n", status);
1710 }
1711 abc = esl_alphabet_Create(alphatype);
1712 esl_sqfile_SetDigital(sqfp, abc);
1713
1714 status = esl_dsqdata_Write(sqfp, basename, errbuf);
1715 if (status == eslEWRITE) esl_fatal("Failed to open dsqdata output files:\n %s", errbuf);
1716 else if (status == eslEFORMAT) esl_fatal("Parse failed (sequence file %s)\n %s", infile, sqfp->get_error(sqfp));
1717 else if (status != eslOK) esl_fatal("Unexpected error while creating dsqdata file (code %d)\n", status);
1718
1719 esl_sqfile_Close(sqfp);
1720 esl_alphabet_Destroy(abc);
1721 esl_getopts_Destroy(go);
1722 return eslOK;
1723 }
1724 #endif /*eslDSQDATA_EXAMPLE2*/
1725
1726
1727 /* esl_dsqdata_example
1728 * Example of opening and reading a dsqdata database.
1729 */
1730 #ifdef eslDSQDATA_EXAMPLE
1731 #include "easel.h"
1732 #include "esl_alphabet.h"
1733 #include "esl_dsqdata.h"
1734 #include "esl_getopts.h"
1735 #include "esl_vectorops.h"
1736
1737 static ESL_OPTIONS options[] = {
1738 /* name type default env range toggles reqs incomp help docgroup*/
1739 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1740 { "-c", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "report summary of chunk contents", 0 },
1741 { "-r", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "report summary of residue counts", 0 },
1742 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1743 };
1744
1745 static char usage[] = "[-options] <basename>";
1746 static char banner[] = "example of using ESL_DSQDATA to read sequence db";
1747
1748 int
1749 main(int argc, char **argv)
1750 {
1751 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
1752 ESL_ALPHABET *abc = NULL;
1753 char *basename = esl_opt_GetArg(go, 1);
1754 int do_summary = esl_opt_GetBoolean(go, "-c");
1755 int do_resct = esl_opt_GetBoolean(go, "-r");
1756 int ncpu = 1;
1757 ESL_DSQDATA *dd = NULL;
1758 ESL_DSQDATA_CHUNK *chu = NULL;
1759 int nchunk = 0;
1760 int i;
1761 int64_t pos;
1762 int64_t ct[128], total;
1763 int x;
1764 int status;
1765
1766 status = esl_dsqdata_Open(&abc, basename, ncpu, &dd);
1767 if (status == eslENOTFOUND) esl_fatal("Failed to open dsqdata files:\n %s", dd->errbuf);
1768 else if (status == eslEFORMAT) esl_fatal("Format problem in dsqdata files:\n %s", dd->errbuf);
1769 else if (status != eslOK) esl_fatal("Unexpected error in opening dsqdata (code %d)", status);
1770
1771 for (x = 0; x < 127; x++) ct[x] = 0;
1772
1773 if (do_summary) esl_dataheader(stdout, 8, "idx", 4, "nseq", 8, "nres", 7, "npacket", 0);
1774
1775 while ((status = esl_dsqdata_Read(dd, &chu)) == eslOK)
1776 {
1777 nchunk++;
1778
1779 if (do_resct)
1780 for (i = 0; i < chu->N; i++)
1781 for (pos = 1; pos <= chu->L[i]; pos++)
1782 ct[ chu->dsq[i][pos] ]++;
1783
1784 if (do_summary)
1785 printf("%-8d %4d %8" PRId64 " %7d\n", nchunk, chu->N, esl_vec_LSum(chu->L, chu->N), chu->pn);
1786
1787 esl_dsqdata_Recycle(dd, chu);
1788 }
1789 if (status != eslEOF) esl_fatal("unexpected error %d in reading dsqdata", status);
1790
1791 if (do_resct)
1792 {
1793 total = 0;
1794 for (x = 0; x < abc->Kp; x++)
1795 {
1796 printf("%c %" PRId64 "\n", abc->sym[x], ct[x]);
1797 total += ct[x];
1798 }
1799 printf("Total = %" PRId64 "\n", total);
1800 }
1801
1802 esl_alphabet_Destroy(abc);
1803 esl_dsqdata_Close(dd);
1804 esl_getopts_Destroy(go);
1805 return 0;
1806 }
1807 #endif /*eslDSQDATA_EXAMPLE*/
1808
1809
1810