Debian Codegraph @

hmmer/src/hmmerfm-exactmatch.c

raw symbols SCIP
1 #include <p7_config.h>
2
3 #include <sys/times.h>
4 #include <string.h>
5
6 #include "easel.h"
7 #include "hmmer.h"
8
9 static ESL_OPTIONS options[] = {
10 /* name type default env range toggles reqs incomp help docgroup*/
11 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
12 { "--out", eslARG_STRING, "none", NULL, NULL, NULL, NULL, NULL, "save list of hits to file <s> ('-' writes to stdout)", 2 },
13 { "--count_only", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "compute just counts, not locations", 2 },
14 { "--fwd_only", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "don't compute matches to the reversed sequence", 2 },
15 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
16 };
17 static char usage[] = "[options] <qfile> <fmfile>";
18 static char banner[] = "Find all instances of each <qfile> sequence in the database represented by <fmfile>";
19
20
21 static int
22 process_commandline(int argc, char **argv, ESL_GETOPTS **ret_go, char **ret_fmfile, char **ret_qfile)
23 {
24 ESL_GETOPTS *go = esl_getopts_Create(options);
25 int status;
26
27 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; }
28 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; }
29 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; }
30
31 /* help format: */
32 if (esl_opt_GetBoolean(go, "-h") == TRUE)
33 {
34 esl_banner(stdout, argv[0], banner);
35 esl_usage(stdout, argv[0], usage);
36
37 if (puts("\nBasic options:") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
38 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 120=textwidth*/
39
40 if (puts("\nSpecial options:") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
41 esl_opt_DisplayHelp(stdout, go, 2, 2, 80); /* 2= group; 2 = indentation; 120=textwidth*/
42
43 exit(0);
44 }
45
46 if (esl_opt_ArgNumber(go) != 2) { if (puts("Incorrect number of command line arguments.") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
47 if ((*ret_qfile = esl_opt_GetArg(go, 1)) == NULL) { if (puts("Failed to get <qfile> argument on command line") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
48 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; }
49
50 /* Validate any attempted use of stdin streams */
51 if (esl_strcmp(*ret_fmfile, "-") == 0 && esl_strcmp(*ret_qfile, "-") == 0)
52 { if (puts("Either <fmfile> or <qfile> may be '-' (to read from stdin), but not both.") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed"); goto FAILURE; }
53
54 *ret_go = go;
55 return eslOK;
56
57 FAILURE: /* all errors handled here are user errors, so be polite. */
58 esl_usage(stdout, argv[0], usage);
59 puts("\nwhere basic options are:");
60 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1= group; 2 = indentation; 80=textwidth*/
61 printf("\nTo see more help on available options, do %s -h\n\n", argv[0]);
62 esl_getopts_Destroy(go);
63 exit(1);
64
65 ERROR:
66 if (go) esl_getopts_Destroy(go);
67 exit(status);
68 }
69
70 //see: http://c-faq.com/stdio/commaprint.html
71 char *
72 commaprint(unsigned long n)
73 {
74 static int comma = ',';
75 static char retbuf[30];
76 char *p = &retbuf[sizeof(retbuf)-1];
77 int i = 0;
78 *p = '\0';
79
80 do {
81 if(i%3 == 0 && i != 0)
82 *--p = comma;
83 *--p = '0' + n % 10;
84 n /= 10;
85 i++;
86 } while(n != 0);
87
88 return p;
89 }
90
91 static int
92 output_header(FM_METADATA *meta, FILE *ofp, const ESL_GETOPTS *go, char *fmfile, char *qfile)
93 {
94 char *alph;
95 char *appname = NULL;
96 int status;
97
98 if (meta->alph_type == fm_DNA) alph = "dna";
99 else if (meta->alph_type == fm_AMINO) alph = "amino";
100
101 if ((status = esl_FileTail(go->argv[0], FALSE, &appname)) != eslOK) return status;
102
103
104
105 if (fprintf(ofp, "# %s :: %s\n", appname, banner) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
106 if (fprintf(ofp, "# %s\n", EASEL_COPYRIGHT) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
107 if (fprintf(ofp, "# %s\n", EASEL_LICENSE) < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
108 if (fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n") < 0) ESL_XEXCEPTION_SYS(eslEWRITE, "write failed");
109
110
111 if (fprintf(ofp, "# input binary-formatted HMMER database: %s\n", fmfile) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
112 if (fprintf(ofp, "# input file of query sequences: %s\n", qfile) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
113
114 if (esl_opt_IsUsed(go, "--out")) {
115 char *outfile = esl_opt_GetString(go, "--out");
116 if (fprintf(ofp, "# output file containing list of hits: %s\n", (esl_strcmp(outfile, "-") == 0 ? "stdout" : outfile)) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
117 }
118
119 if (esl_opt_IsUsed(go, "--count_only") && fprintf(ofp, "# output only counts, not hit locations\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
120 if (esl_opt_IsUsed(go, "--fwd_only") && fprintf(ofp, "# don't compute matches to the reversed sequence\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
121
122
123 if (fprintf(ofp, "# alphabet : %s\n", alph) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
124 if (fprintf(ofp, "# bin_length : %d\n", meta->freq_cnt_b) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
125 if (fprintf(ofp, "# suffix array sample rate: %d\n", meta->freq_SA) < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
126 if (fprintf(ofp, "# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n\n") < 0) ESL_EXCEPTION_SYS(eslEWRITE, "write failed");
127
128
129 if (appname) free(appname);
130 return eslOK;
131
132 ERROR:
133 if (appname) free(appname);
134 return status;
135
136 }
137
138
139
140 /* Function: getFMHits()
141 * Synopsis: For a given interval, identify the position in original text for each element
142 * of interval
143 * Purpose: Implement Algorithm 3.7 (p17) of Firth paper (A Comparison of BWT Approaches
144 * to String Pattern Matching). Most of the meat is in the method of counting
145 * characters - bwt_getOccCount, which depends on compilation choices.
146 */
147 int
148 getFMHits( FM_DATA *fm, FM_CFG *cfg, FM_INTERVAL *interval, int block_id, int hit_offset, int hit_length, FM_HIT *hits_ptr, int fm_direction) {
149
150 int i, j, len = 0;
151 int dist_from_end;
152
153 for (i = interval->lower; i<= interval->upper; i++) {
154 j = i;
155 len = 0;
156
157 while ( j != fm->term_loc && (j % cfg->meta->freq_SA)) { //go until we hit a position in the full SA that was sampled during FM index construction
158 uint8_t c = fm_getChar( cfg->meta->alph_type, j, fm->BWT);
159 j = fm_getOccCount (fm, cfg, j-1, c);
160 j += abs((int)(fm->C[c]));
161 len++;
162 }
163
164
165 hits_ptr[hit_offset + i - interval->lower].block = block_id;
166 hits_ptr[hit_offset + i - interval->lower].direction = fm_direction;
167 hits_ptr[hit_offset + i - interval->lower].length = hit_length;
168
169 dist_from_end = 1 + len + (j==fm->term_loc ? 0 : fm->SA[ j / cfg->meta->freq_SA ]) ; // len is how many backward steps we had to take to find a sampled SA position
170
171 if (fm_direction == fm_forward)
172 dist_from_end += hit_length;
173 else
174 dist_from_end += 1;
175
176 //the SA is on the reversed string. What would be the position in the unreversed string?
177 hits_ptr[hit_offset + i - interval->lower].start = fm->N - dist_from_end;
178
179 //printf ("SA: %d\n", hits_ptr[hit_offset + i - interval->lower].start);
180
181 }
182
183 return eslOK;
184
185 }
186
187 /* hit_sorter(): qsort's pawn, below */
188 static int
189 hit_sorter(const void *a, const void *b)
190 {
191 FM_HIT *h1 = (FM_HIT*)a;
192 FM_HIT *h2 = (FM_HIT*)b;
193
194 if (h1->sortkey > h2->sortkey) return 1;
195 else if (h1->sortkey < h2->sortkey) return -1;
196 else {
197 if (h1->direction > h2->direction) return 1;
198 else if (h1->direction < h2->direction) return -1;
199 else {
200 if (h1->start > h2->start) return 1;
201 else if(h1->start < h2->start) return -1;
202 else return 0;
203 }
204 }
205 }
206
207 /* Function: main()
208 * Synopsis: Run set of queries against an FM
209 * Purpose: Read in a FM and a file of query sequences.
210 * For each query, find matching FM interval, then collect positions in
211 * the original text T for the corresponding occurrences. These positions
212 * are 0-based (so first character is position 0).
213 */
214 int
215 main(int argc, char *argv[])
216 {
217 void* tmp; // used for RALLOC calls
218 clock_t t1, t2;
219 struct tms ts1, ts2;
220 char *fname_fm = NULL;
221 char *fname_queries = NULL;
222 FM_HIT *hits = NULL;
223 char *line = NULL;
224 int status = eslOK;
225 int hit_cnt = 0;
226 int hit_indiv_cnt = 0;
227 int miss_cnt = 0;
228 int hit_num = 0;
229 int hit_num2 = 0;
230 int hits_size = 0;
231 int i,j;
232 int count_only = 0;
233
234 FM_INTERVAL interval;
235 FM_DATA *fmsf = NULL;
236 FM_DATA *fmsb = NULL;
237 FILE* fp_fm = NULL;
238 FILE* fp = NULL;
239 FILE* out = NULL;
240 char *outname = NULL;
241
242 ESL_GETOPTS *go = NULL; /* command line processing */
243 FM_CFG *cfg;
244 FM_METADATA *meta;
245
246 ESL_SQ *tmpseq; // used for sequence validation
247 ESL_ALPHABET *abc = NULL;
248
249 //start timer
250 t1 = times(&ts1);
251
252 process_commandline(argc, argv, &go, &fname_fm, &fname_queries);
253
254
255 if (esl_opt_IsOn(go, "--out")) {
256 outname = esl_opt_GetString(go, "--out");
257 if ( esl_strcmp ("-", outname) == 0 ) {
258 out = stdout;
259 outname = "stdout";
260 } else {
261 out = fopen(outname,"w");
262 }
263 }
264
265 if (esl_opt_IsOn(go, "--count_only"))
266 count_only = 1;
267
268
269 if((fp_fm = fopen(fname_fm, "rb")) == NULL)
270 esl_fatal("Cannot open file `%s': ", fname_fm);
271
272
273 fm_configAlloc(&cfg);
274 cfg->occCallCnt = 0;
275 meta = cfg->meta;
276 meta->fp = fp_fm;
277
278
279 fm_readFMmeta( meta);
280
281 if (meta->alph_type == fm_DNA) abc = esl_alphabet_Create(eslDNA);
282 else if (meta->alph_type == fm_AMINO) abc = esl_alphabet_Create(eslAMINO);
283 tmpseq = esl_sq_CreateDigital(abc);
284
285
286
287 //read in FM-index blocks
288 ESL_ALLOC(fmsf, meta->block_count * sizeof(FM_DATA) );
289 if (!meta->fwd_only )
290 ESL_ALLOC(fmsb, meta->block_count * sizeof(FM_DATA) );
291
292 for (i=0; i<meta->block_count; i++) {
293 fm_FM_read( fmsf+i,meta, TRUE );
294
295 if (!meta->fwd_only) { // whether or not we're going to search forward, need to read it in
296 fm_FM_read(fmsb+i, meta, FALSE );
297 fmsb[i].SA = fmsf[i].SA;
298 fmsb[i].T = fmsf[i].T;
299 }
300 }
301 fclose(fp_fm);
302
303 output_header(meta, stdout, go, fname_fm, fname_queries);
304
305
306 /* initialize a few global variables, then call initGlobals
307 * to do architecture-specific initialization
308 */
309 fm_configInit(cfg, NULL);
310
311 fm_alphabetCreate(meta, NULL); // don't override charBits
312
313 fp = fopen(fname_queries,"r");
314 if (fp == NULL)
315 esl_fatal("Unable to open file %s\n", fname_queries);
316
317 ESL_ALLOC(line, FM_MAX_LINE * sizeof(char));
318
319 hits_size = 200;
320 ESL_ALLOC(hits, hits_size * sizeof(FM_HIT));
321
322 while(fgets(line, FM_MAX_LINE, fp) ) {
323 int qlen=0;
324 while (line[qlen] != '\0' && line[qlen] != '\n') qlen++;
325 if (line[qlen] == '\n') line[qlen] = '\0';
326
327 hit_num = 0;
328
329 for (i=0; i<meta->block_count; i++) {
330
331 fm_getSARangeReverse(fmsf+i, cfg, line, meta->inv_alph, &interval);
332 if (interval.lower>=0 && interval.lower <= interval.upper) {
333 int new_hit_num = interval.upper - interval.lower + 1;
334 hit_num += new_hit_num;
335 if (!count_only) {
336 if (hit_num > hits_size) {
337 hits_size = 2*hit_num;
338 ESL_RALLOC(hits, tmp, hits_size * sizeof(FM_HIT));
339 }
340 getFMHits(fmsf+i, cfg, &interval, i, hit_num-new_hit_num, qlen, hits, fm_forward);
341 }
342
343 }
344
345
346 /* find reverse hits, using backward search on the forward FM*/
347 if (!meta->fwd_only && !(esl_opt_IsOn(go, "--fwd_only")) ) {
348 fm_getSARangeForward(fmsb+i, cfg, line, meta->inv_alph, &interval);// yes, use the backward fm to produce the equivalent of a forward search on the forward fm
349 if (interval.lower>=0 && interval.lower <= interval.upper) {
350 int new_hit_num = interval.upper - interval.lower + 1;
351 hit_num += new_hit_num;
352 if (!count_only) {
353 if (hit_num > hits_size) {
354 hits_size = 2*hit_num;
355 ESL_RALLOC(hits, tmp, hits_size * sizeof(FM_HIT));
356 }
357 //even though I used fmsb above, use fmsf here, since we'll now do a backward trace
358 //in the FM-index to find the next sampled SA position
359 getFMHits(fmsf+i, cfg, &interval, i, hit_num-new_hit_num, qlen, hits, fm_backward);
360 }
361 }
362
363 }
364
365 }
366
367
368 if (hit_num > 0) {
369 if (count_only) {
370 hit_cnt++;
371 hit_indiv_cnt += hit_num;
372 } else {
373 hit_num2 = 0;
374
375 //for each hit, identify the sequence id and position within that sequence
376 for (i = 0; i< hit_num; i++) {
377
378 hits[i].sortkey = 0;
379
380 // validate match - if any characters in orig sequence were ambiguities, reject.
381 // This step gets the letters in the hit range, with ambiguity characters returned.
382 // (if direction is fm_backwards, then the string is reversed ... doesn't matter for our purposes
383 uint64_t range2DSQ_start = (hits[i].direction == fm_forward ? hits[i].start : hits[i].start-hits[i].length+1);
384 fm_convertRange2DSQ( fmsf + hits[i].block, meta, range2DSQ_start, hits[i].length,
385 p7_NOCOMPLEMENT, tmpseq, TRUE );
386
387 // Compare to ambig-base corrected hit to filter out made up sequence hits
388 for (j=1; j<=hits[i].length; j++) {
389 if (tmpseq->dsq[j] >= abc->K) {
390 hits[i].sortkey = -1; //reject
391 j = hits[i].length+1; //quit looking
392 }
393 }
394
395
396 if (hits[i].sortkey != -1 ) { // no ambiguity characters
397
398 uint32_t segment_id = fm_computeSequenceOffset( fmsf, meta, hits[i].block, hits[i].start);
399
400 // Make sure that this hit doesn't span two target sequences
401 if ( ( hits[i].start - meta->seq_data[segment_id].fm_start ) + hits[i].length - 1 > meta->seq_data[ segment_id ].length )
402 hits[i].sortkey = -1;
403 else
404 hits[i].sortkey = meta->seq_data[ segment_id ].target_id;
405
406 // hits[].start: Absolute position of hit within block ( containing possibly multiple
407 // concatenated sequences and/or sequence segments.
408 // fm_seq[].target_id: The index into the sequence records for this sequence segment.
409 // fm_seq[].fm_start: Position in block where this sequence segment begins
410 // target_start: The absolute position within sequence ("target_id") where this segment
411 // start.
412 // Therefore:
413 // What is the absolute position of this hit against sequence "target_id"?
414 hits[i].start = ( hits[i].start - meta->seq_data[segment_id].fm_start) +
415 meta->seq_data[segment_id].target_start;
416
417
418 // This approach reuses the .block memory to get the segment_id back.
419 // Unfortunately we have lost the information on the actual block the hit
420 // was found in, confusing anyone who assumes that <FM_HIT>.block is actually
421 // the block number. Sorry.
422 // TODO: move away from this approach.
423 hits[i].block = segment_id;
424 }
425
426
427 if (hits[i].sortkey != -1)
428 hit_num2++; // legitimate hit
429
430 }
431
432
433 if (hit_num2 > 0)
434 hit_cnt++;
435
436 //now sort according the the sequence_id corresponding to that seq_offset
437 qsort(hits, hit_num, sizeof(FM_HIT), hit_sorter);
438
439 //skim past the skipped entries
440 i = 0;
441 while ( i < hit_num ) {
442 if (hits[i].sortkey != -1 )
443 break; //
444 i++;
445 }
446
447
448 if (i < hit_num) {
449 if (out != NULL) {
450 fprintf (out, "%s\n",line);
451 //fprintf (out, "\t%10s (%8d %s)\n",meta->seq_data[ hits[i].block ].name, hits[i].start, (hits[i].direction==fm_forward?"+":"-"));
452 fprintf (out, " %8ld %s %10s\n", (long)(hits[i].start), (hits[i].direction==fm_forward?"f":"r"), meta->seq_data[ hits[i].block ].name);
453 }
454 hit_indiv_cnt++;
455 i++; // skip the first one, since I'll be comparing each to the previous
456
457 for ( ; i< hit_num; i++) {
458 if ( //meta->seq_data[ hits[i].block ].id != meta->seq_data[ hits[i-1].block ].id ||
459 hits[i].sortkey != hits[i-1].sortkey || //sortkey is seq_data[].id
460 hits[i].direction != hits[i-1].direction ||
461 hits[i].start != hits[i-1].start )
462 {
463 if (out != NULL)
464 //fprintf (out, "\t%10s (%8d %s)\n",meta->seq_data[ hits[i].block ].name, hits[i].start, (hits[i].direction==fm_forward?"+":"-"));
465 fprintf (out, " %8ld %s %10s\n", (long)(hits[i].start), (hits[i].direction==fm_forward?"f":"r"), meta->seq_data[ hits[i].block ].name);
466 hit_indiv_cnt++;
467 }
468 }
469 if (out != NULL)
470 fprintf (out, "\n");
471 }
472 }
473 } else {
474 miss_cnt++;
475 }
476
477
478 }
479
480 for (i=0; i<meta->block_count; i++) {
481 fm_FM_destroy( fmsf+i, 1 );
482 if (!meta->fwd_only)
483 fm_FM_destroy( fmsb+i, 0 );
484 }
485
486
487 free (hits);
488 free (line);
489 fclose(fp);
490
491 fm_configDestroy(cfg);
492
493
494 // compute and print the elapsed time in millisec
495 t2 = times(&ts2);
496 {
497 double clk_ticks = sysconf(_SC_CLK_TCK);
498 double elapsedTime = (t2-t1)/clk_ticks;
499 double throughput = cfg->occCallCnt/elapsedTime;
500
501 fprintf (stderr, "hit: %-10d (%d)\n", hit_cnt, hit_indiv_cnt);
502 fprintf (stderr, "miss:%-10d\n", miss_cnt);
503 fprintf (stderr, "run time: %.2f seconds\n", elapsedTime);
504 fprintf (stderr, "occ calls: %12s\n", commaprint(cfg->occCallCnt));
505 fprintf (stderr, "occ/sec: %12s\n", commaprint(throughput));
506 }
507
508 exit(eslOK);
509
510
511 ERROR:
512 printf ("failure allocating memory for hits\n");
513 exit(status);
514 }
515
516