Debian Codegraph @

hmmer/src/makehmmerdb.c

raw symbols SCIP
1 #include <p7_config.h>
2
3 #include "easel.h"
4 #include "esl_sq.h"
5 #include "esl_sqio.h"
6 #include "esl_mem.h"
7
8 #include <string.h>
9
10 #include "hmmer.h"
11 #include "divsufsort.h"
12
13
14 #define FM_BLOCK_COUNT 100000 //max number of SQ objects in a block
15 #define FM_BLOCK_OVERLAP 20000 //20 Kbases of overlap, at most, between adjascent FM-index blocks
16 #define ALPHOPTS "--amino,--dna,--rna" /* Exclusive options for alphabet choice */
17
18
19 static ESL_OPTIONS options[] = {
20 /* name type default env range toggles reqs incomp help docgroup*/
21 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
22
23 /* Selecting the alphabet rather than autoguessing it */
24 //TODO: when I make the FM method work for amino acids, re-enable this selection
25 { "--amino", eslARG_NONE, FALSE, NULL, NULL, ALPHOPTS, NULL, NULL, "input is protein sequence", 2 },
26 { "--dna", eslARG_NONE, FALSE, NULL, NULL, ALPHOPTS, NULL, NULL, "input is DNA sequence", 2 },
27 { "--rna", eslARG_NONE, FALSE, NULL, NULL, ALPHOPTS, NULL, NULL, "input is RNA sequence", 2 },
28
29 /* Other options */
30 { "--informat", eslARG_STRING, FALSE, NULL, NULL, NULL, NULL, NULL, "specify that input file is in format <s>", 3 },
31 { "--bin_length", eslARG_INT, "256", NULL, NULL, NULL, NULL, NULL, "bin length (power of 2; 32<=b<=4096)", 3 },
32 { "--sa_freq", eslARG_INT, "8", NULL, NULL, NULL, NULL, NULL, "suffix array sample rate (power of 2)", 3 },
33 { "--block_size", eslARG_INT, "50", NULL, NULL, NULL, NULL, NULL, "input sequence broken into blocks this size (Mbases)", 3 },
34
35 /* hidden*/
36 { "--fwd_only", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "build FM-index only for forward search (not for HMMER)", 9 },
37
38 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
39 };
40 static char usage[] = "[options] <seqfile> <binaryfile>";
41 static char banner[] = "build a HMMER binary-formatted database from an input sequence file";
42
43
44 static int
45 process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_seqfile, char **ret_fmfile)
46 {
47 ESL_GETOPTS *go = esl_getopts_Create(options);
48 int status;
49
50 if (esl_opt_ProcessEnvironment(go) != eslOK) { if (printf("Failed to process environment: %s\n", go->errbuf) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
51 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) { if (printf("Failed to parse command line: %s\n", go->errbuf) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
52 if (esl_opt_VerifyConfig(go) != eslOK) { if (printf("Failed to parse command line: %s\n", go->errbuf) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
53
54 /* help format: */
55 if (esl_opt_GetBoolean(go, "-h") == TRUE)
56 {
57 p7_banner(stdout, argv[0], banner);
58 esl_usage(stdout, argv[0], usage);
59
60 if (puts("\nBasic options:") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
61 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 120=textwidth*/
62
63 // if (puts("\nOptions for selecting alphabet rather than guessing it:") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
64 // esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
65
66 if (puts("\nSpecial options:") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
67 esl_opt_DisplayHelp(stdout, go, 3, 2, 80); /* 2= group; 2 = indentation; 120=textwidth*/
68
69 exit(0);
70 }
71
72 if (esl_opt_ArgNumber(go) != 2) { if (puts("Incorrect number of command line arguments.") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
73 if ((*ret_seqfile = esl_opt_GetArg(go, 1)) == NULL) { if (puts("Failed to get <seqfile> argument on command line") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
74 if ((*ret_fmfile = esl_opt_GetArg(go, 2)) == NULL) { if (puts("Failed to get <fmfile> argument on command line") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
75
76 /* Validate any attempted use of stdin streams */
77 if (esl_strcmp(*ret_seqfile, "-") == 0 && esl_strcmp(*ret_fmfile, "-") == 0)
78 { if (puts("Either <seqfile> or <fmfile> may be '-' (to read from stdin), but not both.") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
79
80 *ret_go = go;
81 return eslOK;
82
83 FAILURE: /* all errors handled here are user errors, so be polite. */
84 esl_usage(stdout, argv[0], usage);
85 puts("\nwhere basic options are:");
86 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
87 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
88 esl_getopts_Destroy(go);
89 exit(1);
90
91 ERROR:
92 if (go) esl_getopts_Destroy(go);
93 exit(status);
94 }
95
96 /* Function: output_header()
97 * Synopsis: Print details of FM-index construction
98 */
99 static int
100 output_header(FILE *ofp, const ESL_GETOPTS *go, char *seqfile, char *fmfile)
101 {
102 p7_banner(ofp, go->argv[0], banner);
103
104 if ( fprintf(ofp, "# input sequence file: %s\n", seqfile) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
105 if (fprintf(ofp, "# output binary-formatted HMMER database: %s\n", fmfile) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
106 if (fprintf(ofp, "# bin_length: %d\n", esl_opt_GetInteger(go, "--bin_length")) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
107 if (fprintf(ofp, "# suffix array sample rate: %d\n", esl_opt_GetInteger(go, "--sa_freq")) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
108 if (esl_opt_IsUsed(go, "--amino") && fprintf(ofp, "# input is asserted to be: protein\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
109 if (esl_opt_IsUsed(go, "--dna") && fprintf(ofp, "# input is asserted to be: DNA\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
110 if (esl_opt_IsUsed(go, "--rna") && fprintf(ofp, "# input is asserted to be: RNA\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
111 if (fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
112 return eslOK;
113 }
114
115
116 /* Function: allocateSeqdata()
117 * Synopsis: ensure that space is allocated for the seqdata object
118 * in the FM-index metadata.
119 */
120 int
121 allocateSeqdata (FM_METADATA *meta, ESL_SQ *sq, int numseqs, int *allocedseqs) {
122 int length;
123 int status = eslOK;
124
125
126 if (numseqs == *allocedseqs) { // either first allocation, or increase in size
127 *allocedseqs *= 4; // we've bumped up against allocation limit, double allocation.
128 ESL_REALLOC (meta->seq_data, *allocedseqs * sizeof(FM_SEQDATA));
129 if (meta->seq_data == NULL )
130 esl_fatal("unable to allocate memory to store FM meta data\n");
131 }
132
133 //allocate space for the name, source, acc, and desc of the sequence source for the block
134 length = strlen(sq->name);
135 meta->seq_data[numseqs].name_length = length;
136 ESL_ALLOC (meta->seq_data[numseqs].name, (1+length) * sizeof(char));
137
138 length = strlen(sq->acc);
139 meta->seq_data[numseqs].acc_length = length;
140 ESL_ALLOC (meta->seq_data[numseqs].acc, (1+length) * sizeof(char));
141
142 length = strlen(sq->source);
143 meta->seq_data[numseqs].source_length = length;
144 ESL_ALLOC (meta->seq_data[numseqs].source, (1+length) * sizeof(char));
145
146 length = strlen(sq->desc);
147 meta->seq_data[numseqs].desc_length = length;
148 ESL_ALLOC (meta->seq_data[numseqs].desc, (1+length) * sizeof(char));
149
150
151 if (meta->seq_data[numseqs].name == NULL || meta->seq_data[numseqs].acc == NULL || meta->seq_data[numseqs].source == NULL || meta->seq_data[numseqs].desc == NULL)
152 esl_fatal("unable to allocate memory to store FM meta data\n");
153
154 return eslOK;
155
156 ERROR:
157 return status;
158 }
159
160
161 /* Function: buildAndWriteFMIndex()
162 * Synopsis: Take text as input, along with several pre-allocated variables,
163 * and produce BWT and corresponding FM-index, then write it all
164 * to the output file.
165 *
166 * if SAsamp == NULL, don't store/write T or SAsamp
167 */
168 int buildAndWriteFMIndex (FM_METADATA *meta, uint32_t seq_offset, uint32_t ambig_offset,
169 uint32_t seq_cnt, uint32_t ambig_cnt, uint32_t overlap,
170 FM_DATA *fm_data, uint32_t *SAsamp,
171 uint32_t *cnts_sb, uint16_t *cnts_b,
172 uint64_t N, uint8_t **Tcompressed, FILE *fp
173 ) {
174
175
176 int status;
177 uint64_t i,j,c,joffset;
178 int chars_per_byte = 8/meta->charBits;
179 uint32_t compressed_bytes = ((chars_per_byte-1+N)/chars_per_byte);
180 uint32_t term_loc;
181
182 uint8_t *T = fm_data->T;
183 uint8_t *BWT = fm_data->BWT;
184 int *SA = (int*) fm_data->SA; //cast this way because libdivsufsort requires an int.
185 uint32_t *occCnts_sb = fm_data->occCnts_sb;
186 uint16_t *occCnts_b = fm_data->occCnts_b;
187
188
189 int num_freq_cnts_b = 1+ceil((double)N/(meta->freq_cnt_b));
190 int num_freq_cnts_sb = 1+ceil((double)N/meta->freq_cnt_sb);
191 int num_SA_samples = 1+floor((double)N/meta->freq_SA);
192
193 if (SAsamp != NULL) {
194 ESL_REALLOC ((*Tcompressed), compressed_bytes * sizeof(uint8_t));
195
196 // Reverse the text T, so the BWT will be on reversed T. Only used for the 1st pass
197 fm_reverseString ((char*)T, N-1);
198 }
199
200 // Construct the Suffix Array on text T
201 status = divsufsort(fm_data->T, SA, N);
202 if ( status < 0 )
203 esl_fatal("buildAndWriteFMIndex: Error building BWT.\n");
204
205 // Construct the BWT, SA landmarks, and FM-index
206 for (c=0; c<meta->alph_size; c++) {
207 cnts_sb[c] = 0;
208 cnts_b[c] = 0;
209 FM_OCC_CNT(sb, 0, c ) = 0;
210 FM_OCC_CNT(b, 0, c ) = 0;
211 }
212
213
214 for(j=0; j < N-1; ++j) {
215 T[j]--; //move values down so 'a'=0...'t'=3; store 'a' in place of '$'
216 }
217 T[N-1]=0;
218
219 BWT[0] = SA[0]==0 ? 0 /* '$' */ : T[ SA[0]-1] ;
220
221 cnts_sb[BWT[0]]++;
222 cnts_b[BWT[0]]++;
223
224 if (SAsamp != NULL) {
225 SAsamp[0] = 0; // not used, since indexing is base-1. Set for the sake of consistency of output.
226 SAsamp[num_SA_samples-1] = 0; //this may sometimes not be filled below; set to avoid valgrind error in fwrite
227 }
228
229 //Scan through SA to build the BWT and FM index structures
230 for(j=1; j < N; ++j) {
231 if (SA[j]==0) { //'$'
232 term_loc = j;
233 BWT[j] = 0; //store 'a' in place of '$'
234 } else {
235 BWT[j] = T[ SA[j]-1] ;
236 }
237
238
239 //sample the SA
240 if (SAsamp != NULL) {
241 if ( !(j % meta->freq_SA) )
242 SAsamp[ j/meta->freq_SA ] = ( SA[j] == N - 1 ? -1 : SA[j] ) ; // handle the wrap-around '$'
243 }
244
245 cnts_sb[BWT[j]]++;
246 cnts_b[BWT[j]]++;
247
248 joffset = j+1;
249 if ( !( joffset % meta->freq_cnt_b) ) { // (j+1)%freq_cnt_b==0 , i.e. every freq_cnt_bth position, noting that it's a zero-based count
250
251 for (c=0; c<meta->alph_size; c++)
252 FM_OCC_CNT(b, (joffset/meta->freq_cnt_b), c ) = cnts_b[c];
253
254 if ( !(joffset % meta->freq_cnt_sb) ) { // j%freq_cnt_sb==0
255 for (c=0; c<meta->alph_size; c++) {
256 FM_OCC_CNT(sb, (joffset/meta->freq_cnt_sb), c ) = cnts_sb[c];
257 cnts_b[c] = 0;
258 }
259 }
260 }
261 }
262
263 //wrap up the counting;
264 for (c=0; c<meta->alph_size; c++) {
265 FM_OCC_CNT(b, num_freq_cnts_b-1, c ) = cnts_b[c];
266 FM_OCC_CNT(sb, num_freq_cnts_sb-1, c ) = cnts_sb[c];
267 }
268
269
270
271 // Convert BWT and T to packed versions if appropriate.
272 if (meta->alph_type == fm_DNA) {
273 //4 chars per byte. Counting will be done based on quadruples 0..3; 4..7; 8..11; etc.
274 for(i=0; i < N-3; i+=4)
275 BWT[i/4] = BWT[i]<<6 | BWT[i+1]<<4 | BWT[i+2]<<2 | BWT[i+3];
276 if (i <= N-1)
277 BWT[i/4] = BWT[i]<<6;
278 if (i+1 <= N-1)
279 BWT[i/4] |= BWT[i+1]<<4;
280 if (i+2 <= N-1)
281 BWT[i/4] |= BWT[i+2]<<2;
282 }
283
284
285
286 //If this is the 1st (reversed text) BWT, de-reverse it, then compress it
287 if (SAsamp != NULL) {
288 fm_reverseString ((char*)T, N-1);
289 // Convert T to packed versions if appropriate.
290 if (meta->alph_type == fm_DNA ) {
291 //4 chars per byte. Counting will be done based on quadruples 0..3; 4..7; 8..11; etc.
292 for(i=0; i < N-3; i+=4)
293 (*Tcompressed)[i/4] = T[i]<<6 | T[i+1]<<4 | T[i+2]<<2 | T[i+3];
294
295 if (i <= N-1)
296 (*Tcompressed)[i/4] = T[i]<<6;
297 if (i+1 <= N-1)
298 (*Tcompressed)[i/4] |= T[i+1]<<4;
299 if (i+2 <= N-1)
300 (*Tcompressed)[i/4] |= T[i+2]<<2;
301 } else {
302 for(i=0; i <= N-1; i++)
303 (*Tcompressed)[i] = T[i];
304 }
305 }
306
307
308 for(j=0; j < N-1; ++j) {
309 T[j]++; //move values back up, in case the reverse FM needs to be built
310 }
311 T[N-1] = 0;
312
313
314 // Write the FM-index meta data
315 if(fwrite(&N, sizeof(uint64_t), 1, fp) != 1)
316 esl_fatal( "buildAndWriteFMIndex: Error writing block_length in FM index.\n");
317 if(fwrite(&term_loc, sizeof(uint32_t), 1, fp) != 1)
318 esl_fatal( "buildAndWriteFMIndex: Error writing terminal location in FM index.\n");
319 if(fwrite(&seq_offset, sizeof(uint32_t), 1, fp) != 1)
320 esl_fatal( "buildAndWriteFMIndex: Error writing seq_offset in FM index.\n");
321 if(fwrite(&ambig_offset, sizeof(uint32_t), 1, fp) != 1)
322 esl_fatal( "buildAndWriteFMIndex: Error writing ambig_offset in FM index.\n");
323 if(fwrite(&overlap, sizeof(uint32_t), 1, fp) != 1)
324 esl_fatal( "buildAndWriteFMIndex: Error writing overlap in FM index.\n");
325 if(fwrite(&seq_cnt, sizeof(uint32_t), 1, fp) != 1)
326 esl_fatal( "buildAndWriteFMIndex: Error writing seq_cnt in FM index.\n");
327 if(fwrite(&ambig_cnt, sizeof(uint32_t), 1, fp) != 1)
328 esl_fatal( "buildAndWriteFMIndex: Error writing ambig_cnt in FM index.\n");
329
330 // don't write Tcompressed or SAsamp if SAsamp == NULL
331 if( SAsamp != NULL && fwrite(*Tcompressed, sizeof(uint8_t), compressed_bytes, fp) != compressed_bytes)
332 esl_fatal( "buildAndWriteFMIndex: Error writing T in FM index.\n");
333 if(fwrite(BWT, sizeof(uint8_t), compressed_bytes, fp) != compressed_bytes)
334 esl_fatal( "buildAndWriteFMIndex: Error writing BWT in FM index.\n");
335 if(SAsamp != NULL && fwrite(SAsamp, sizeof(uint32_t), (size_t)num_SA_samples, fp) != (size_t)num_SA_samples)
336 esl_fatal( "buildAndWriteFMIndex: Error writing SA in FM index.\n");
337 if(fwrite(occCnts_b, sizeof(uint16_t)*(meta->alph_size), (size_t)num_freq_cnts_b, fp) != (size_t)num_freq_cnts_b)
338 esl_fatal( "buildAndWriteFMIndex: Error writing occCnts_b in FM index.\n");
339 if(fwrite(occCnts_sb, sizeof(uint32_t)*(meta->alph_size), (size_t)num_freq_cnts_sb, fp) != (size_t)num_freq_cnts_sb)
340 esl_fatal( "buildAndWriteFMIndex: Error writing occCnts_sb in FM index.\n");
341
342
343 return eslOK;
344
345 ERROR:
346 /* Deallocate memory. */
347 return eslFAIL;
348
349 }
350
351
352
353 /* Function: main()
354 * Synopsis: break input sequence set into chunks, for each one building the
355 * Burrows-Wheeler transform and corresponding FM-index. Maintain requisite
356 * meta data.
357 * Notes: Currently depends on the divsufsort-lite code of Yuta Mori, though this
358 * could easily be replaced.
359 */
360 int
361 main(int argc, char **argv)
362 {
363 int status = eslOK;
364 char tmp_filename[16] = "fmtmpXXXXXX";
365 FILE *fptmp = NULL;
366 FILE *fp = NULL;
367
368
369 // these will be allocated once, and reused for each built block
370 FM_METADATA *meta = NULL;
371 FM_DATA *fm_data = NULL;
372 uint32_t *SAsamp = NULL;
373 uint32_t *cnts_sb = NULL;
374 uint16_t *cnts_b = NULL;
375 uint8_t *Tcompressed = NULL;
376
377
378
379 clock_t t1, t2;
380 struct tms ts1, ts2;
381
382 long i,j,c;
383
384 int chars_per_byte;
385 int num_freq_cnts_sb ;
386 int num_freq_cnts_b ;
387 int num_SA_samples ;
388
389 int infmt = eslSQFILE_UNKNOWN;
390 int alphatype = eslUNKNOWN;
391 ESL_ALPHABET *abc = NULL;
392 ESL_SQ *sq = NULL;
393 ESL_SQFILE *sqfp = NULL;
394
395 ESL_SQ *tmpsq = NULL;
396 ESL_SQ_BLOCK *block = NULL;
397
398 char *fname_in = NULL;
399 char *fname_out= NULL;
400 uint32_t block_size = 50000000;
401 int sq_cnt = 0;
402 int use_tmpsq = 0;
403 uint64_t block_length;
404 uint64_t total_char_count = 0;
405
406 uint32_t max_block_size;
407
408 int numblocks = 0;
409 uint32_t numseqs = 0;
410
411
412 int allocedseqs = 1000;
413 uint32_t seq_offset = 0;
414 uint32_t ambig_offset = 0;
415 uint32_t overlap = 0;
416 uint32_t seq_cnt;
417 uint32_t ambig_cnt;
418 int compressed_bytes;
419 uint32_t term_loc;
420 int alphaguess;
421
422 ESL_GETOPTS *go = NULL; /* command line processing */
423
424 int in_ambig_run = 0;
425
426 ESL_RANDOMNESS *r = esl_randomness_Create(42);
427
428
429 #if !defined (eslENABLE_SSE)
430 p7_Fail("The hmmerfm sequence database file format is valid only on systems supporting SSE vector instructions\n");
431 #endif
432
433 ESL_ALLOC (meta, sizeof(FM_METADATA));
434 if (meta == NULL)
435 esl_fatal("unable to allocate memory to store FM meta data\n");
436 meta->alph = NULL;
437
438
439 ESL_ALLOC (meta->ambig_list, sizeof(FM_AMBIGLIST));
440 if (meta->ambig_list == NULL)
441 esl_fatal("unable to allocate memory to store FM ambiguity data\n");
442 fm_initAmbiguityList(meta->ambig_list);
443
444
445 meta->alph_type = fm_DNA;
446 meta->freq_SA = 8;
447 meta->freq_cnt_b = 256;
448 meta->freq_cnt_sb = pow(2,16); //65536 - that's the # values in a short
449 meta->seq_count = 0;
450 ESL_ALLOC (meta->seq_data, allocedseqs * sizeof(FM_SEQDATA));
451 if (meta->seq_data == NULL )
452 esl_fatal("unable to allocate memory to store FM sequence data\n");
453
454
455 process_commandline(argc, argv, &go, &fname_in, &fname_out);
456
457 if (esl_opt_IsOn(go, "--bin_length")) meta->freq_cnt_b = esl_opt_GetInteger(go, "--bin_length");
458 if ( meta->freq_cnt_b < 32 || meta->freq_cnt_b >4096 || (meta->freq_cnt_b & (meta->freq_cnt_b - 1)) ) // test power of 2
459 esl_fatal("bin_length must be a power of 2, at least 128, and at most 4096\n");
460
461 if (esl_opt_IsOn(go, "--sa_freq")) meta->freq_SA = esl_opt_GetInteger(go, "--sa_freq");
462 if ( (meta->freq_SA & (meta->freq_SA - 1)) ) // test power of 2
463 esl_fatal ("SA_freq must be a power of 2\n");
464
465
466 if (esl_opt_IsOn(go, "--block_size")) block_size = 1000000 * esl_opt_GetInteger(go, "--block_size");
467 if ( block_size <= 0 )
468 esl_fatal ("block_size must be a positive number\n");
469
470 if ( block_size > 3500000000 )
471 esl_fatal ("block_size must less than 3500M\n");
472
473
474 //start timer
475 t1 = times(&ts1);
476
477 output_header(stdout, go, fname_in, fname_out);
478
479 if (esl_opt_GetString(go, "--informat") != NULL) {
480 infmt = esl_sqio_EncodeFormat(esl_opt_GetString(go, "--informat"));
481 if (infmt == eslSQFILE_UNKNOWN) esl_fatal("%s is not a valid input sequence file format for --informat");
482 }
483
484 status = esl_sqfile_Open(fname_in, infmt, NULL, &sqfp);
485 if (status == eslENOTFOUND) esl_fatal("No such file %s", fname_in);
486 else if (status == eslEFORMAT) esl_fatal("Format of seqfile %s unrecognized.", fname_in);
487 else if (status != eslOK) esl_fatal("Open failed, code %d.", status);
488
489 meta->fwd_only = 0;
490
491
492 if ( esl_opt_IsUsed(go, "--amino") ) {
493 meta->alph_type = fm_AMINO;
494 alphatype = eslAMINO;
495 meta->fwd_only = 1;
496 } else if (esl_opt_IsUsed(go, "--dna") || esl_opt_IsUsed(go, "--rna") ){
497
498 //meta->alph = "dna"; //esl_opt_IsUsed(go, "--dna") ? "dna" || "rna";
499 meta->alph_type = fm_DNA;
500 alphatype = eslDNA;
501
502 } else {
503 esl_sqfile_GuessAlphabet(sqfp, &alphaguess);
504
505 if (alphaguess == eslDNA || alphaguess == eslRNA) {
506 meta->alph_type = fm_DNA;
507 alphatype = eslDNA;
508 } else if (alphaguess == eslAMINO) {
509 meta->alph_type = fm_AMINO;
510 alphatype = eslAMINO;
511 meta->fwd_only = 1;
512 } else {
513 esl_fatal("Unable to guess alphabet. Try '--dna' or '--amino'\n%s", ""); //'dna_full'
514 }
515 }
516
517
518 if (esl_opt_IsOn(go, "--fwd_only") )
519 meta->fwd_only = 1;
520
521 //getInverseAlphabet
522 fm_alphabetCreate(meta, &(meta->charBits));
523 chars_per_byte = 8/meta->charBits;
524
525 //shift inv_alph up one, to make space for '$' at 0
526 for (i=0; i<256; i++)
527 if ( meta->inv_alph[i] >= 0)
528 meta->inv_alph[i]++;
529
530
531 abc = esl_alphabet_Create(alphatype);
532 sq = esl_sq_CreateDigital(abc);
533 tmpsq = esl_sq_CreateDigital(abc);
534
535 esl_sqfile_SetDigital(sqfp, abc);
536 block = esl_sq_CreateDigitalBlock(FM_BLOCK_COUNT, abc);
537 block->complete = FALSE;
538 max_block_size = FM_BLOCK_OVERLAP+block_size+1 + ceil(block_size*.05); // first +1 for the '$', +5% of block size because that's the slop allowed by readwindow
539
540 /* Allocate BWT, Text, SA, and FM-index data structures, allowing storage of maximally large sequence*/
541 ESL_ALLOC(fm_data, sizeof(FM_DATA) );
542 fm_data->T = NULL;
543 fm_data->BWT_mem = NULL;
544 fm_data->BWT = NULL;
545 fm_data->SA = NULL;
546 fm_data->C = NULL;
547 fm_data->occCnts_sb = NULL;
548 fm_data->occCnts_b = NULL;
549
550 ESL_ALLOC (fm_data->T, max_block_size * sizeof(uint8_t));
551 ESL_ALLOC (fm_data->BWT_mem, max_block_size * sizeof(uint8_t));
552 fm_data->BWT = fm_data->BWT_mem; // in SSE code, used to align memory. Here, doesn't matter
553 ESL_ALLOC (fm_data->SA, max_block_size * sizeof(int));
554 ESL_ALLOC (SAsamp, (1 + floor((double)max_block_size/meta->freq_SA) ) * sizeof(uint32_t));
555 ESL_ALLOC (fm_data->occCnts_sb, (1+ceil((double)max_block_size/meta->freq_cnt_sb)) * meta->alph_size * sizeof(uint32_t)); // every freq_cnt_sb positions, store an array of ints
556 ESL_ALLOC (fm_data->occCnts_b, ( 1+ceil((double)max_block_size/meta->freq_cnt_b)) * meta->alph_size * sizeof(uint16_t)); // every freq_cnt_b positions, store an array of 8-byte ints
557 ESL_ALLOC (cnts_sb, meta->alph_size * sizeof(uint32_t));
558 ESL_ALLOC (cnts_b, meta->alph_size * sizeof(uint16_t));
559
560 // Open a temporary file, to which FM-index data will be written
561 if (esl_tmpfile(tmp_filename, &fptmp) != eslOK) esl_fatal("unable to open fm-index tmpfile");
562
563 /* Main loop: */
564 while (status == eslOK ) {
565 //reset block as an empty vessel
566 for (i=0; i<block->count; i++){
567 esl_sq_Reuse(block->list + i);
568 }
569 // Check how much space the block structure is using and re-allocate if it has grown to more than 20*block_size bytes
570 // this loop iterates from 0 to block->listsize rather than block->count because we want to count all of the
571 // block's sub-structures, not just the ones that contained sequence data after the last call to ReadBlock()
572 // This doesn't check some of the less-common sub-structures in a sequence, but it should be good enough for
573 // our goal of keeping block size under control
574 uint64_t block_space = 0;
575 for(i=0; i<block->listSize; i++){
576 block_space += block->list[i].nalloc;
577 block_space += block->list[i].aalloc;
578 block_space += block->list[i].dalloc;
579 block_space += block->list[i].srcalloc;
580 block_space += block->list[i].salloc;
581 if (block->list[i].ss != NULL){
582 block_space += block->list[i].salloc; // ss field is not always presesnt, but takes salloc bytes if it is
583 }
584 }
585
586 if(block_space > 20*block_size){
587 ESL_SQ_BLOCK *new_block = esl_sq_CreateDigitalBlock(FM_BLOCK_COUNT, abc);
588 new_block->count = block->count; // copying this field shouldn't be necessary, but I can't guarantee that it isn't.
589 new_block->listSize = block->listSize;
590 new_block->complete = block->complete;
591 new_block->first_seqidx = block->first_seqidx;
592 esl_sq_DestroyBlock(block);
593 block = new_block;
594 }
595 if (use_tmpsq) {
596 esl_sq_Copy(tmpsq , block->list);
597 block->complete = FALSE; //this lets ReadBlock know that it needs to append to a small bit of previously-read seqeunce
598 block->list->C = FM_BLOCK_OVERLAP; // overload the ->C value, which ReadBlock uses to determine how much
599 // overlap should be retained in the ReadWindow step
600 } else {
601 block->complete = TRUE;
602 }
603
604
605 status = esl_sqio_ReadBlock(sqfp, block, block_size, -1, /*max_init_window=*/FALSE, alphatype != eslAMINO);
606 if (status == eslEOF) continue;
607 if (status != eslOK) esl_fatal("Parse failed (sequence file %s): status:%d\n%s\n",
608 sqfp->filename, status, esl_sqfile_GetErrorBuf(sqfp));
609
610 seq_offset = numseqs;
611 ambig_offset = meta->ambig_list->count;
612
613 if (block->complete || block->count == 0) {
614 use_tmpsq = FALSE;
615 } else {
616 /* The final sequence on the block was a probably-incomplete window of the active sequence.
617 * Grab a copy of the end for use in the next pass, to ensure we don't miss hits crossing
618 * the boundary between two blocks.
619 */
620 esl_sq_Copy(block->list + (block->count - 1) , tmpsq);
621 use_tmpsq = TRUE;
622 }
623
624 block->first_seqidx = sq_cnt;
625 sq_cnt += block->count - (use_tmpsq ? 1 : 0);// if there's an incomplete sequence read into the block wait to count it until it's complete.
626
627
628 /* Read dseqs from block into text element T.
629 * Convert the dsq from esl-alphabet to fm-alphabet (1..k for alphabet of size k).
630 * (a) collapsing upper/lower case for appropriate sorting.
631 * (b) reserving 0 for '$', which must be lexicographically smallest
632 * (these will later be shifted to 0-based alphabet, once SA has been built)
633 *
634 */
635 block_length = 0;
636 for (i=0; i<block->count; i++) {
637
638 //start a new block, with space for the name
639 allocateSeqdata(meta, block->list+i, numseqs, &allocedseqs);
640
641 //meta data
642 meta->seq_data[numseqs].target_id = block->first_seqidx + i ;
643 meta->seq_data[numseqs].target_start = block->list[i].start;
644 meta->seq_data[numseqs].fm_start = block_length;
645
646 if (block->list[i].name == NULL) meta->seq_data[numseqs].name[0] = '\0';
647 else strcpy(meta->seq_data[numseqs].name, block->list[i].name );
648 if (block->list[i].acc == NULL) meta->seq_data[numseqs].acc[0] = '\0';
649 else strcpy(meta->seq_data[numseqs].acc, block->list[i].acc );
650 if (block->list[i].source == NULL) meta->seq_data[numseqs].source[0] = '\0';
651 else strcpy(meta->seq_data[numseqs].source, block->list[i].source );
652 if (block->list[i].desc == NULL) meta->seq_data[numseqs].desc[0] = '\0';
653 else strcpy(meta->seq_data[numseqs].desc, block->list[i].desc );
654
655 meta->seq_data[numseqs].length = 0;
656 for (j=1; j<=block->list[i].n; j++) {
657 c = abc->sym[block->list[i].dsq[j]];
658 if ( meta->alph_type == fm_DNA) {
659 if (meta->inv_alph[c] == -1) {
660 // replace ambiguity characters by random choice of A,C,G, and T.
661 c = meta->alph[(int)(esl_random(r)*4)];
662
663 if (!in_ambig_run) {
664 fm_addAmbiguityRange(meta->ambig_list, block_length, block_length);
665 in_ambig_run=1;
666 } else {
667 meta->ambig_list->ranges[meta->ambig_list->count - 1].upper = block_length;
668 }
669 } else {
670 in_ambig_run=0;
671 }
672 } else if (meta->inv_alph[c] == -1) {
673 esl_fatal("requested alphabet doesn't match input text\n");
674 }
675
676 fm_data->T[block_length] = meta->inv_alph[c];
677
678 block_length++;
679 if (j>block->list[i].C) total_char_count++; // add to total count, only if it's not redundant with earlier read
680 meta->seq_data[numseqs].length++;
681 }
682 numseqs++;
683 in_ambig_run = 0;
684 }
685
686 fm_data->T[block_length] = 0; // last character 0 is effectively '$' for suffix array
687 block_length++;
688
689 seq_cnt = numseqs-seq_offset;
690 ambig_cnt = meta->ambig_list->count - ambig_offset;
691
692
693 //build and write FM-index for T. This will be a BWT on the reverse of the sequence, required for reverse-traversal of the BWT
694 buildAndWriteFMIndex(meta, seq_offset, ambig_offset, seq_cnt, ambig_cnt, (uint32_t)block->list[0].C, fm_data,
695 SAsamp, cnts_sb, cnts_b, block_length, &Tcompressed, fptmp);
696
697
698 if ( ! meta->fwd_only ) {
699 //build and write FM-index for un-reversed T (used to find reverse hits using forward traversal of the BWT
700 buildAndWriteFMIndex(meta, seq_offset, ambig_offset, seq_cnt, ambig_cnt, 0, fm_data,
701 NULL, cnts_sb, cnts_b, block_length, &Tcompressed, fptmp);
702 }
703 numblocks++;
704 }
705
706
707 esl_sqfile_Close(sqfp);
708 esl_alphabet_Destroy(abc);
709 esl_sq_Destroy(sq);
710 esl_sq_Destroy(tmpsq);
711 esl_sq_DestroyBlock(block);
712
713 esl_randomness_Destroy(r);
714
715 meta->seq_count = numseqs;
716 meta->block_count = numblocks;
717
718 /* Finished writing the FM-index data to a temporary file. Now write
719 * metadata to fname_out, than append FM-index data from temp file
720 */
721 if((fp = fopen(fname_out, "wb")) == NULL)
722 esl_fatal( "%s: Cannot open file `%s': ", argv[0], fname_out);
723
724
725 //write out meta data
726 if( fwrite(&(meta->fwd_only), sizeof(meta->fwd_only), 1, fp) != 1 ||
727 fwrite(&(meta->alph_type), sizeof(meta->alph_type), 1, fp) != 1 ||
728 fwrite(&(meta->alph_size), sizeof(meta->alph_size), 1, fp) != 1 ||
729 fwrite(&(meta->charBits), sizeof(meta->charBits), 1, fp) != 1 ||
730 fwrite(&(meta->freq_SA), sizeof(meta->freq_SA), 1, fp) != 1 ||
731 fwrite(&(meta->freq_cnt_sb), sizeof(meta->freq_cnt_sb), 1, fp) != 1 ||
732 fwrite(&(meta->freq_cnt_b), sizeof(meta->freq_cnt_b), 1, fp) != 1 ||
733 fwrite(&(meta->block_count), sizeof(meta->block_count), 1, fp) != 1 ||
734 fwrite(&(meta->seq_count), sizeof(meta->seq_count), 1, fp) != 1 ||
735 fwrite(&(meta->ambig_list->count), sizeof(meta->ambig_list->count), 1, fp) != 1 ||
736 fwrite(&total_char_count, sizeof(total_char_count), 1, fp) != 1
737 )
738 esl_fatal( "%s: Error writing meta data for FM index.\n", argv[0]);
739
740
741 for (i=0; i<meta->seq_count; i++) {
742
743 if( fwrite(&(meta->seq_data[i].target_id), sizeof(meta->seq_data[i].target_id), 1, fp) != 1 ||
744 fwrite(&(meta->seq_data[i].target_start), sizeof(meta->seq_data[i].target_start), 1, fp) != 1 ||
745 fwrite(&(meta->seq_data[i].fm_start), sizeof(meta->seq_data[i].fm_start), 1, fp) != 1 ||
746 fwrite(&(meta->seq_data[i].length), sizeof(meta->seq_data[i].length), 1, fp) != 1 ||
747 fwrite(&(meta->seq_data[i].name_length), sizeof(meta->seq_data[i].name_length), 1, fp) != 1 ||
748 fwrite(&(meta->seq_data[i].acc_length), sizeof(meta->seq_data[i].acc_length), 1, fp) != 1 ||
749 fwrite(&(meta->seq_data[i].source_length),sizeof(meta->seq_data[i].source_length), 1, fp) != 1 ||
750 fwrite(&(meta->seq_data[i].desc_length), sizeof(meta->seq_data[i].desc_length), 1, fp) != 1 ||
751 fwrite(meta->seq_data[i].name, sizeof(char), meta->seq_data[i].name_length+1 , fp) != meta->seq_data[i].name_length+1 ||
752 fwrite(meta->seq_data[i].acc, sizeof(char), meta->seq_data[i].acc_length+1 , fp) != meta->seq_data[i].acc_length+1 ||
753 fwrite(meta->seq_data[i].source, sizeof(char), meta->seq_data[i].source_length+1, fp) != meta->seq_data[i].source_length+1 ||
754 fwrite(meta->seq_data[i].desc, sizeof(char), meta->seq_data[i].desc_length+1 , fp) != meta->seq_data[i].desc_length+1
755 )
756 esl_fatal( "%s: Error writing meta data for FM index.\n", argv[0]);
757 }
758 for (i=0; i<meta->ambig_list->count; i++) {
759 if( fwrite(&(meta->ambig_list->ranges[i].lower), sizeof(meta->ambig_list->ranges[i].lower), 1, fp) != 1 ||
760 fwrite(&(meta->ambig_list->ranges[i].upper), sizeof(meta->ambig_list->ranges[i].upper), 1, fp) != 1
761 )
762 esl_fatal( "%s: Error writing ambiguity data for FM index.\n", argv[0]);
763 }
764
765
766 /* now append the FM-index data in fptmp to the desired output file, fp */
767 rewind(fptmp);
768 for (i=0; i<numblocks; i++) {
769
770 for(j=0; j< (meta->fwd_only?1:2); j++ ) { //do this once or twice, once for forward-T index, and possibly once for reversed
771 //first, read
772 if(fread(&block_length, sizeof(block_length), 1, fptmp) != 1)
773 esl_fatal( "%s: Error reading block_length in FM index.\n", argv[0]);
774 if(fread(&term_loc, sizeof(term_loc), 1, fptmp) != 1)
775 esl_fatal( "%s: Error reading terminal location in FM index.\n", argv[0]);
776 if(fread(&seq_offset, sizeof(seq_offset), 1, fptmp) != 1)
777 esl_fatal( "%s: Error reading seq_offset in FM index.\n", argv[0]);
778 if(fread(&ambig_offset, sizeof(ambig_offset ), 1, fptmp) != 1)
779 esl_fatal( "%s: Error reading ambig_offset in FM index.\n", argv[0]);
780 if(fread(&overlap, sizeof(overlap), 1, fptmp) != 1)
781 esl_fatal( "%s: Error reading overlap in FM index.\n", argv[0]);
782 if(fread(&seq_cnt, sizeof(seq_cnt), 1, fptmp) != 1)
783 esl_fatal( "%s: Error reading seq_cnt in FM index.\n", argv[0]);
784 if(fread(&ambig_cnt, sizeof(ambig_cnt), 1, fptmp) != 1)
785 esl_fatal( "%s: Error reading ambig_cnt in FM index.\n", argv[0]);
786
787
788 compressed_bytes = ((chars_per_byte-1+block_length)/chars_per_byte);
789 num_freq_cnts_b = 1+ceil((double)block_length/meta->freq_cnt_b);
790 num_freq_cnts_sb = 1+ceil((double)block_length/meta->freq_cnt_sb);
791 num_SA_samples = 1+floor((double)block_length/meta->freq_SA);
792
793
794 //j==0 test cause T and SA to be written only for forward sequence
795 if(j==0 && fread(fm_data->T, sizeof(uint8_t), compressed_bytes, fptmp) != compressed_bytes)
796 esl_fatal( "%s: Error reading T in FM index.\n", argv[0]);
797 if(fread(fm_data->BWT, sizeof(uint8_t), compressed_bytes, fptmp) != compressed_bytes)
798 esl_fatal( "%s: Error reading BWT in FM index.\n", argv[0]);
799 if(j==0 && fread(SAsamp, sizeof(uint32_t), (size_t)num_SA_samples, fptmp) != (size_t)num_SA_samples)
800 esl_fatal( "%s: Error reading SA in FM index.\n", argv[0]);
801 if(fread(fm_data->occCnts_b, sizeof(uint16_t)*(meta->alph_size), (size_t)num_freq_cnts_b, fptmp) != (size_t)num_freq_cnts_b)
802 esl_fatal( "%s: Error reading occCnts_b in FM index.\n", argv[0]);
803 if(fread(fm_data->occCnts_sb, sizeof(uint32_t)*(meta->alph_size), (size_t)num_freq_cnts_sb, fptmp) != (size_t)num_freq_cnts_sb)
804 esl_fatal( "%s: Error reading occCnts_sb in FM index.\n", argv[0]);
805
806
807
808 //then, write
809 if(fwrite(&block_length, sizeof(block_length), 1, fp) != 1)
810 esl_fatal( "%s: Error writing block_length in FM index.\n", argv[0]);
811 if(fwrite(&term_loc, sizeof(term_loc), 1, fp) != 1)
812 esl_fatal( "%s: Error writing terminal location in FM index.\n", argv[0]);
813 if(fwrite(&seq_offset, sizeof(seq_offset), 1, fp) != 1)
814 esl_fatal( "%s: Error writing seq_offset in FM index.\n", argv[0]);
815 if(fwrite(&ambig_offset, sizeof(ambig_offset), 1, fp) != 1)
816 esl_fatal( "%s: Error writing ambig_offset in FM index.\n", argv[0]);
817 if(fwrite(&overlap, sizeof(overlap), 1, fp) != 1)
818 esl_fatal( "%s: Error writing overlap in FM index.\n", argv[0]);
819 if(fwrite(&seq_cnt, sizeof(seq_cnt), 1, fp) != 1)
820 esl_fatal( "%s: Error writing seq_cnt in FM index.\n", argv[0]);
821 if(fwrite(&ambig_cnt, sizeof(ambig_cnt), 1, fp) != 1)
822 esl_fatal( "%s: Error writing ambig_cnt in FM index.\n", argv[0]);
823
824
825 if(j==0 && fwrite(fm_data->T, sizeof(uint8_t), compressed_bytes, fp) != compressed_bytes)
826 esl_fatal( "%s: Error writing T in FM index.\n", argv[0]);
827 if(fwrite(fm_data->BWT, sizeof(uint8_t), compressed_bytes, fp) != compressed_bytes)
828 esl_fatal( "%s: Error writing BWT in FM index.\n", argv[0]);
829 if(j==0 && fwrite(SAsamp, sizeof(uint32_t), (size_t)num_SA_samples, fp) != (size_t)num_SA_samples)
830 esl_fatal( "%s: Error writing SA in FM index.\n", argv[0]);
831 if(fwrite(fm_data->occCnts_b, sizeof(uint16_t)*(meta->alph_size), (size_t)num_freq_cnts_b, fp) != (size_t)num_freq_cnts_b)
832 esl_fatal( "%s: Error writing occCnts_b in FM index.\n", argv[0]);
833 if(fwrite(fm_data->occCnts_sb, sizeof(uint32_t)*(meta->alph_size), (size_t)num_freq_cnts_sb, fp) != (size_t)num_freq_cnts_sb)
834 esl_fatal( "%s: Error writing occCnts_sb in FM index.\n", argv[0]);
835
836 }
837 }
838
839 fclose(fp);
840 fclose(fptmp);
841
842
843 if (fm_data != NULL)
844 fm_FM_destroy(fm_data, TRUE);
845 free(fm_data);
846 free(SAsamp);
847
848 free(cnts_b);
849 free(cnts_sb);
850
851 free(Tcompressed);
852
853 fm_metaDestroy(meta);
854 esl_getopts_Destroy(go);
855
856
857 // compute and print the elapsed time in millisec
858 t2 = times(&ts2);
859 {
860 double clk_ticks = sysconf(_SC_CLK_TCK);
861 double elapsedTime = (t2-t1)/clk_ticks;
862
863 fprintf (stderr, "run time: %.2f seconds\n", elapsedTime);
864 }
865
866
867 return (eslOK);
868
869
870 ERROR:
871 /* Deallocate memory. */
872 if (fp) fclose(fp);
873 if (fm_data) fm_FM_destroy(fm_data, TRUE);
874 free(fm_data);
875
876 free(SAsamp);
877 free(cnts_b);
878 free(cnts_sb);
879
880 fm_metaDestroy(meta);
881 esl_getopts_Destroy(go);
882
883
884 esl_sqfile_Close(sqfp);
885 esl_alphabet_Destroy(abc);
886 esl_sq_Destroy(sq);
887 if (tmpsq) esl_sq_Destroy(tmpsq);
888 if (block) esl_sq_DestroyBlock(block);
889
890 fprintf (stderr, "failure during memory allocation\n");
891
892 exit(status);
893
894 }