Debian Codegraph @

hmmer/src/fm_ssv.c

raw symbols SCIP
1 #include <p7_config.h>
2
3 #include <string.h>
4
5 #include "easel.h"
6 #include "esl_alphabet.h"
7 #include "esl_gumbel.h"
8 #include "esl_sq.h"
9
10 #include "hmmer.h"
11
12
13 /* hit_sorter(): qsort's pawn, below */
14 static int
15 FM_hit_sorter(const void *a, const void *b)
16 {
17 // return 2 * (((FM_DIAG*)a)->sortkey > ((FM_DIAG*)b)->sortkey) - 1; // same as the test below
18 if ( ((FM_DIAG*)a)->sortkey > ((FM_DIAG*)b)->sortkey) return 1;
19 else if( ((FM_DIAG*)a)->sortkey < ((FM_DIAG*)b)->sortkey) return -1;
20 else return 0;
21 }
22
23
24
25 /* Function: FM_mergeSeeds()
26 *
27 * Synopsis: Given collection of seeds, sort and merge overlapping ones
28 *
29 * Returns: <eslOK> on success.
30 */
31 static int
32 FM_mergeSeeds(FM_DIAGLIST *seeds, int N, int ssv_length) {
33 int i;
34 int j = 0;
35
36 FM_DIAG next;
37 int tmp;
38 int next_is_complement;
39 int curr_is_complement;
40 int curr_n;
41 int curr_k;
42 int curr_len;
43 int curr_end;
44 int curr_diagval;
45
46 FM_DIAG *diags = seeds->diags;
47
48
49 if (seeds->count == 0)
50 return eslOK;
51
52 //sort, first by direction, then N (position on database sequence), then K (model position)
53 qsort(diags, seeds->count, sizeof(FM_DIAG), FM_hit_sorter);
54
55 next = diags[0];
56
57 curr_is_complement = (next.complementarity == p7_COMPLEMENT);
58 curr_n = next.n;
59 curr_k = next.k;
60 curr_len = next.length;
61 curr_end = curr_n + curr_len - 1;
62 curr_diagval = next.n - next.k;
63
64 for( i=1; i<seeds->count; i++) {
65
66 next = diags[i];
67 next_is_complement = (next.complementarity == p7_COMPLEMENT);
68
69 if ( next_is_complement == curr_is_complement //same direction
70 && ( next.n - next.k) == curr_diagval //overlapping diagonals will share the same value of (n - k)
71 && next.n + next.length < curr_n + curr_len + ssv_length //overlapping, or close to it
72 ) {
73
74
75 //overlapping diags; extend, if appropriate
76 tmp = next.n + next.length - 1;
77 if (tmp > curr_end) {
78 curr_end = tmp;
79 curr_len = curr_end - curr_n + 1;
80 }
81 } else {
82 //doesn't overlap current diagonal, so store current...
83 diags[j].n = curr_n;
84 diags[j].k = curr_k;
85 diags[j].length = curr_end - curr_n + 1;
86 diags[j].complementarity = curr_is_complement;
87 diags[j].score = 0.0;
88
89 // ... then start up a new one
90 curr_n = next.n;
91 curr_k = next.k;
92 curr_len = next.length;
93 curr_end = curr_n + curr_len - 1;
94 curr_diagval = next.n - next.k;
95 curr_is_complement = next_is_complement;
96
97 j++;
98 }
99 }
100 // store final entry
101 diags[j].n = curr_n;
102 diags[j].k = curr_k;
103 diags[j].length = curr_end - curr_n + 1;
104 diags[j].score = 0.0;
105 diags[j].complementarity = curr_is_complement;
106
107 seeds->count = j+1;
108
109 return eslOK;
110
111 }
112
113
114 /* Function: FM_backtrackSeed()
115 *
116 * Synopsis: Find position(s) in the FM index for a diagonal that meets score threshold
117 *
118 * Details: Follows the BWT/FM-index until finding an entry of the implicit
119 * suffix array that is found in the sampled SA.
120
121 *
122 * Args: fmf - FM index for finding matches to the input sequence
123 * fm_cfg - FM-index meta data
124 * i - Single position in the BWT
125 *
126 * Returns: <eslOK> on success.
127 */
128 static uint32_t
129 FM_backtrackSeed(const FM_DATA *fmf, const FM_CFG *fm_cfg, int i) {
130 int j = i;
131 int len = 0;
132 int c;
133
134 while ( j != fmf->term_loc && (j % fm_cfg->meta->freq_SA)) { //go until we hit a position in the full SA that was sampled during FM index construction
135 c = fm_getChar( fm_cfg->meta->alph_type, j, fmf->BWT);
136 j = fm_getOccCount (fmf, fm_cfg, j-1, c);
137 j += abs((int)(fmf->C[c]));
138 len++;
139 }
140
141 return len + (j==fmf->term_loc ? 0 : fmf->SA[ j / fm_cfg->meta->freq_SA ]) ; // len is how many backward steps we had to take to find a sampled SA position
142 }
143
144 /* Function: FM_getPassingDiags()
145 *
146 * Synopsis: Find position(s) in the FM index for a seed that meets score threshold, keep list
147 *
148 * Details: This step determines the location of each instance of the seed
149 * and creates a diagonal for that instance
150 *
151 * Args: fmf - FM index for finding matches to the input sequence
152 * fmb - FM index for finding matches to the reverse of the input sequence
153 * fm_cfg - FM-index meta data
154 * k - Position of the diagonal in the model
155 * M - Length of the model
156 * depth - Length of the diagonal
157 * fm_direction - which FM is in use for this diag
158 * model_direction - forward or reverse path over the model
159 * complementarity - top or bottom strand
160 * interval - FM-index interval
161 * seeds - RETURN: collection of threshold-passing windows
162 *
163 * Returns: <eslOK> on success.
164 */
165 static int
166 FM_getPassingDiags(const FM_DATA *fmf, const FM_CFG *fm_cfg,
167 int k, int M, float sc, int depth, int fm_direction,
168 int model_direction, int complementarity,
169 FM_INTERVAL *interval,
170 FM_DIAGLIST *seeds
171 )
172 {
173 int i;
174 FM_DIAG *seed;
175
176 //iterate over the forward interval, for each entry backtrack until hitting a sampled suffix array entry
177 for (i = interval->lower; i<= interval->upper; i++) {
178
179 seed = fm_newSeed(seeds);
180 seed->k = k;
181 seed->length = depth;
182
183 if (complementarity == p7_NOCOMPLEMENT )
184 seed->n = fmf->N - FM_backtrackSeed(fmf, fm_cfg, i) - depth - 1;
185 else
186 seed->n = FM_backtrackSeed(fmf, fm_cfg, i) ;
187
188 seed->complementarity = complementarity;
189
190 /* seed->n corresponds to the start of the seed in terms of the
191 * target sequence, in a forward direction. seed->k holds the
192 * model position at the beginning of that seed. If model_direction
193 * is fm_reverse, the ->n value is from the beginning of the revcomp,
194 */
195 if (model_direction == fm_forward)
196 seed->k -= (depth - 1) ;
197
198
199 seed->sortkey = (int)( complementarity == p7_COMPLEMENT ? fmf->N + 1 : 0) // makes complement seeds cover a different score range than non-complements
200 + ((int)(seed->n) - (int)(seed->k) ) // unique diagonal within the complement/non-complement score range
201 + ((double)(seed->k)/(double)(M+1)) ; // fractional part, used to sort seeds sharing a diagonal
202
203
204 }
205
206 return eslOK;
207 }
208
209 /* Function: FM_Recurse()
210 *
211 * Synopsis: Recursively traverse/prune a string trie, testing all strings vs the model
212 *
213 * Details: This is the heart of the FM SSV method. Given a path P on the
214 * trie, we keep track of a compact list of all not-yet-pruned
215 * diagonals in the DP table of the string S corresponding to
216 * P against the model. The preserved diagonals might be for
217 * either a forward or backwards pass over the model and a pass
218 * over either the top or bottom (reverse complemented) strand
219 * of the target sequences.
220 *
221 * Args: depth - how long is the current path
222 * Kp - alphabet size (including ambiguity)
223 * fmf - FM index for finding matches to the input sequence
224 * fmb - FM index for finding matches to the reverse of the input sequence
225 * fm_cfg - FM-index meta data
226 * ssvdata - compact data required for computing SSV scores
227 * sc_threshFM - Score that a short diagonal must pass to warrant extension to a full diagonal
228 * dp_pairs - Compact representation of the surviving diagonals in the DP table
229 * first - The index of the first entry in dp_pairs for the current column of the DP table
230 * last - The index of the last entry in dp_pairs for the current column of the DP table
231 * interval_1 - FM-index interval - used for the standard backwards pass along the BWT (fmf)
232 * interval_2 - FM-index interval - used for the forward pass along the BWT (fmb)
233 * seeds - RETURN: collection of threshold-passing windows
234 * seq - preallocated char* used to capture and print the string for the current path - for debugging only
235 *
236 * Returns: <eslOK> on success.
237 */
238 static int
239 FM_Recurse( int depth, int Kp, int fm_direction,
240 const FM_DATA *fmf, const FM_DATA *fmb,
241 const FM_CFG *fm_cfg,
242 const P7_SCOREDATA *ssvdata, uint8_t *consensus,
243 float sc_threshFM,
244 FM_DP_PAIR *dp_pairs, int first, int last,
245 FM_INTERVAL *interval_1, FM_INTERVAL *interval_2,
246 FM_DIAGLIST *seeds
247 // , char *seq
248 )
249 {
250
251
252 float sc, next_score;
253
254 int c, i, k;
255 FM_INTERVAL interval_1_new, interval_2_new;
256 uint8_t positive_run = 0;
257 uint8_t consec_consensus = 0;
258 uint8_t cons_c = 0;
259
260 for (c=0; c< fm_cfg->meta->alph_size; c++) {//acgt
261 int dppos = last;
262 //seq[depth-1] = fm_cfg->meta->alph[c];
263 //seq[depth] = '\0';
264
265 for (i=first; i<=last; i++) { // for each surviving diagonal from the previous round
266
267 if (dp_pairs[i].model_direction == fm_forward)
268 k = dp_pairs[i].pos + 1;
269 else //fm_backward
270 k = dp_pairs[i].pos - 1;
271
272 if (dp_pairs[i].complementarity == p7_COMPLEMENT) {
273 next_score = ssvdata->ssv_scores_f[k*Kp + fm_cfg->meta->compl_alph[c]];
274 cons_c = fm_cfg->meta->compl_alph[consensus[k]];
275 } else {
276 next_score = ssvdata->ssv_scores_f[k*Kp + c];
277 cons_c = consensus[k];
278 }
279
280 sc = dp_pairs[i].score + next_score;
281 positive_run = (next_score > 0 ? dp_pairs[i].consec_pos + 1 : 0);
282 consec_consensus = (c == cons_c ? dp_pairs[i].consec_consensus+1 : 0);
283
284 if ( sc >= sc_threshFM
285 || (fm_cfg->consensus_match_req > 0 && consec_consensus == fm_cfg->consensus_match_req)
286 ) { // this is a seed I want to extend
287
288 interval_1_new.lower = interval_1->lower;
289 interval_1_new.upper = interval_1->upper;
290
291 if (fm_direction == fm_forward) {
292 if ( interval_1_new.lower >= 0 && interval_1_new.lower <= interval_1_new.upper ) //no use extending a non-existent string
293 fm_updateIntervalReverse( fmf, fm_cfg, c, &interval_1_new);
294
295 if ( interval_1_new.lower >= 0 && interval_1_new.lower <= interval_1_new.upper ) { //no use passing a non-existent string
296 FM_getPassingDiags(fmf, fm_cfg, k, ssvdata->M, sc, depth, fm_forward,
297 dp_pairs[i].model_direction, dp_pairs[i].complementarity,
298 &interval_1_new, seeds);
299 }
300 } else { // fm_direction == fm_reverse
301 //searching for forward matches on the FM-index
302 interval_2_new.lower = interval_2->lower;
303 interval_2_new.upper = interval_2->upper;
304
305 //searching for reverse matches on the FM-index
306 if ( interval_1_new.lower >= 0 && interval_1_new.lower <= interval_1_new.upper ) //no use extending a non-existent string
307 fm_updateIntervalForward( fmb, fm_cfg, c, &interval_1_new, &interval_2_new);
308
309 if ( interval_2_new.lower >= 0 && interval_2_new.lower <= interval_2_new.upper ) { //no use passing a non-existent string
310 FM_getPassingDiags(fmf, fm_cfg, k, ssvdata->M, sc, depth, fm_backward,
311 dp_pairs[i].model_direction, dp_pairs[i].complementarity,
312 &interval_2_new, seeds);
313 }
314 }
315
316 } else if ( sc <= 0 //some other path in the string enumeration tree will do the job
317 || depth == fm_cfg->max_depth //can't extend anymore, 'cause we've reached the pruning length
318 || ( dp_pairs[i].model_direction == fm_forward && k == ssvdata->M) //can't extend anymore, 'cause we're at the end of the model, going forward
319 || ( dp_pairs[i].model_direction == fm_backward && k == 1 ) //can't extend anymore, 'cause we're at the beginning of the model, going backwards
320 || (depth == dp_pairs[i].score_peak_len + fm_cfg->drop_max_len) //too many consecutive positions with a negative total score contribution (sort of like Xdrop)
321 || (depth > 4 && depth > consec_consensus && (float)sc/(float)depth < fm_cfg->score_density_req) //score density is too low (don't bother checking in the first couple slots
322 || (dp_pairs[i].max_consec_pos < fm_cfg->consec_pos_req && //a seed is expected to have at least one run of positive-scoring matches at least length consec_pos_req; if it hasn't, (see Tue Nov 23 09:39:54 EST 2010)
323 (fm_cfg->consec_pos_req - positive_run) == (fm_cfg->max_depth - depth + 1) // if we're close to the end of the sequence, abort -- if that end does have sufficiently long all-positive run, I'll find it on the reverse sweep
324 )
325 || (dp_pairs[i].model_direction == fm_forward &&
326 ( (depth > (fm_cfg->max_depth - 10)) && sc + ssvdata->opt_ext_fwd[k][fm_cfg->max_depth-depth-1] < sc_threshFM) //can't hit threshold, even with best possible forward extension up to length ssv_req
327 )
328 || (dp_pairs[i].model_direction == fm_backward &&
329 ( (depth > (fm_cfg->max_depth - 10)) && sc + ssvdata->opt_ext_rev[k-1][fm_cfg->max_depth-depth-1] < sc_threshFM ) //can't hit threshold, even with best possible extension up to length ssv_req
330 )
331
332 )
333 {
334
335 //do nothing - it's been pruned
336
337 } else { // it's possible to extend this diagonal and reach the threshold score
338
339 dppos++;
340
341 dp_pairs[dppos].pos = k;
342 dp_pairs[dppos].score = sc;
343 dp_pairs[dppos].model_direction = dp_pairs[i].model_direction;
344 dp_pairs[dppos].complementarity = dp_pairs[i].complementarity;
345
346 if (sc > dp_pairs[i].max_score) {
347 dp_pairs[dppos].max_score = sc;
348 dp_pairs[dppos].score_peak_len = depth;
349 } else {
350 dp_pairs[dppos].max_score = dp_pairs[i].max_score;
351 if (sc >= dp_pairs[i].max_score - fm_cfg->drop_lim)
352 dp_pairs[dppos].score_peak_len = depth; // close enough to call it a new peak
353 else
354 dp_pairs[dppos].score_peak_len = dp_pairs[i].score_peak_len;
355 }
356
357 dp_pairs[dppos].consec_pos = positive_run;
358 dp_pairs[dppos].max_consec_pos = ESL_MAX( positive_run, dp_pairs[i].max_consec_pos);
359 dp_pairs[dppos].consec_consensus = consec_consensus;
360 }
361 }
362
363 if ( dppos > last ){ // at least one diagonal that might reach threshold score, but hasn't yet, so extend
364
365 interval_1_new.lower = interval_1->lower;
366 interval_1_new.upper = interval_1->upper;
367
368 if (fm_direction == fm_forward) {
369
370 if ( interval_1_new.lower >= 0 && interval_1_new.lower <= interval_1_new.upper ) //no use extending a non-existent string
371 fm_updateIntervalReverse( fmf, fm_cfg, c, &interval_1_new);
372
373 if ( interval_1_new.lower < 0 || interval_1_new.lower > interval_1_new.upper ) { //that string doesn't exist in fwd index
374 continue;
375 }
376 FM_Recurse(depth+1, Kp, fm_direction,
377 fmf, fmb, fm_cfg, ssvdata, consensus,
378 sc_threshFM, dp_pairs, last+1, dppos,
379 &interval_1_new, NULL,
380 seeds
381 //, seq
382 );
383
384
385 } else { // fm_direction == fm_reverse
386
387 interval_2_new.lower = interval_2->lower;
388 interval_2_new.upper = interval_2->upper;
389
390 if ( interval_1_new.lower >= 0 && interval_1_new.lower <= interval_1_new.upper ) //no use extending a non-existent string
391 fm_updateIntervalForward( fmb, fm_cfg, c, &interval_1_new, &interval_2_new);
392
393
394 if ( interval_1_new.lower < 0 || interval_1_new.lower > interval_1_new.upper ) { //that string doesn't exist in reverse index
395 continue;
396 }
397 FM_Recurse(depth+1, Kp, fm_direction,
398 fmf, fmb, fm_cfg, ssvdata, consensus,
399 sc_threshFM, dp_pairs, last+1, dppos,
400 &interval_1_new, &interval_2_new,
401 seeds
402 //, seq
403 );
404
405 }
406
407 }
408
409 }
410
411 return eslOK;
412 }
413
414 /* Function: FM_getSeeds()
415 *
416 * Synopsis: Find short diagonal seeds with score above a modest threshold.
417 *
418 * Details: Given FM configuration <fm_cfg>, model scoring data <ssvdata>,
419 * both forward and backward FM indexes (<fmf>, <fmb>), and
420 * a score threshold <sc_threshFM>, find all seeds in the FMs
421 * that meet the threshold, and place them in the container
422 * <seeds>.
423 *
424 * This involves building diagonals in both forward and reverse
425 * orientation relative to the model, because the pruning method
426 * includes a score density calculation - sometimes that density
427 * is only found on one end of the hit. This function merely
428 * kickstarts the task of traversing over a trie of all strings
429 * up to some fixed length looking for threshold-passing
430 * diagonals - FM_Recurse() does the hard work.
431 *
432 * Args: fmf - FM index for finding matches to the input sequence
433 * fmb - FM index for finding matches to the reverse of the input sequence
434 * fm_cfg - FM-index meta data
435 * ssvdata - compact data required for computing SSV scores
436 * Kp - Alphabet size (including ambiguity chars)
437 * sc_threshFM - Score that a short diagonal must pass to warrant extension to a full diagonal
438 * strands - p7_STRAND_TOPONLY | p7_STRAND_BOTTOMONLY | p7_STRAND_BOTH
439 * seeds - RETURN: collection of threshold-passing windows
440 *
441 * Returns: <eslOK> on success.
442 */
443 static int FM_getSeeds ( const FM_DATA *fmf, const FM_DATA *fmb,
444 const FM_CFG *fm_cfg, const P7_SCOREDATA *ssvdata,
445 uint8_t *consensus, int Kp, float sc_threshFM,
446 int strands, FM_DIAGLIST *seeds
447 )
448 {
449 FM_INTERVAL interval_f1, interval_f2, interval_bk;
450 int i, k;
451 int status;
452 float sc;
453 //char *seq;
454
455 FM_DP_PAIR *dp_pairs_fwd;
456 FM_DP_PAIR *dp_pairs_rev;
457
458 ESL_ALLOC(dp_pairs_fwd, ssvdata->M * fm_cfg->max_depth * sizeof(FM_DP_PAIR)); // guaranteed to be enough to hold all diagonals
459 ESL_ALLOC(dp_pairs_rev, ssvdata->M * fm_cfg->max_depth * sizeof(FM_DP_PAIR));
460
461 //ESL_ALLOC(seq, 50*sizeof(char));
462
463 for (i=0; i<fm_cfg->meta->alph_size; i++) {
464 int fwd_cnt=0;
465 int rev_cnt=0;
466 interval_f1.lower = interval_f2.lower = interval_bk.lower = fmf->C[i];
467 interval_f1.upper = interval_f2.upper = interval_bk.upper = abs((int)(fmf->C[i+1]))-1;
468
469 if (interval_f1.lower<0 ) //none of that character found
470 continue;
471
472 // This is here for debugging purposes only. Feel free to comment out.
473 //seq[0] = fm_cfg->meta->alph[i];
474 //seq[1] = '\0';
475
476 // Fill in a DP column for the character c, (compressed so that only positive-scoring entries are kept)
477 // There will be 4 DP columns for each character, (1) fwd-std, (2) fwd-complement, (3) rev-std, (4) rev-complement
478 for (k = 1; k <= ssvdata->M; k++) // there's no need to bother keeping an entry starting at the last position (gm->M)
479 {
480
481 if (strands != p7_STRAND_BOTTOMONLY) {
482 sc = ssvdata->ssv_scores_f[k*Kp + i];
483 if (sc>0) { // we'll extend any positive-scoring diagonal
484 /* fwd on model, fwd on FM (really, reverse on FM, but the FM is on a reversed string, so its fwd*/
485 if (k < ssvdata->M-3) { // don't bother starting a forward diagonal so close to the end of the model
486 //Forward pass on the FM-index
487 dp_pairs_fwd[fwd_cnt].pos = k;
488 dp_pairs_fwd[fwd_cnt].score = sc;
489 dp_pairs_fwd[fwd_cnt].max_score = sc;
490 dp_pairs_fwd[fwd_cnt].score_peak_len = 1;
491 dp_pairs_fwd[fwd_cnt].consec_pos = 1;
492 dp_pairs_fwd[fwd_cnt].max_consec_pos = 1;
493 dp_pairs_fwd[fwd_cnt].consec_consensus = (i==consensus[k] ? 1 : 0);
494 dp_pairs_fwd[fwd_cnt].complementarity = p7_NOCOMPLEMENT;
495 dp_pairs_fwd[fwd_cnt].model_direction = fm_forward;
496 fwd_cnt++;
497 }
498
499 /* rev on model, rev on FM (the FM is on the unreversed string)*/
500 if (k > 4) { // don't bother starting a reverse diagonal so close to the start of the model
501 dp_pairs_rev[rev_cnt].pos = k;
502 dp_pairs_rev[rev_cnt].score = sc;
503 dp_pairs_rev[rev_cnt].max_score = sc;
504 dp_pairs_rev[rev_cnt].score_peak_len = 1;
505 dp_pairs_rev[rev_cnt].consec_pos = 1;
506 dp_pairs_rev[rev_cnt].max_consec_pos = 1;
507 dp_pairs_rev[rev_cnt].consec_consensus = (i==consensus[k] ? 1: 0);
508 dp_pairs_rev[rev_cnt].complementarity = p7_NOCOMPLEMENT;
509 dp_pairs_rev[rev_cnt].model_direction = fm_backward;
510 rev_cnt++;
511 }
512 }
513 }
514
515
516 // Now do the reverse complement
517 if (strands != p7_STRAND_TOPONLY) {
518 sc = ssvdata->ssv_scores_f[k*Kp + fm_cfg->meta->compl_alph[i]];
519 if (sc>0) { // we'll extend any positive-scoring diagonal
520 /* rev on model, fwd on FM (really, reverse on FM, but the FM is on a reversed string, so its fwd*/
521 if (k > 4) { // don't bother starting a reverse diagonal so close to the start of the model
522 dp_pairs_fwd[fwd_cnt].pos = k;
523 dp_pairs_fwd[fwd_cnt].score = sc;
524 dp_pairs_fwd[fwd_cnt].max_score = sc;
525 dp_pairs_fwd[fwd_cnt].score_peak_len = 1;
526 dp_pairs_fwd[fwd_cnt].consec_pos = 1;
527 dp_pairs_fwd[fwd_cnt].max_consec_pos = 1;
528 dp_pairs_fwd[fwd_cnt].consec_consensus = (i==consensus[k] ? 1: 0);
529 dp_pairs_fwd[fwd_cnt].complementarity = p7_COMPLEMENT;
530 dp_pairs_fwd[fwd_cnt].model_direction = fm_backward;
531 fwd_cnt++;
532 }
533
534 /* fwd on model, rev on FM (the FM is on the unreversed string - complemented)*/
535 if (k < ssvdata->M-3) { // don't bother starting a forward diagonal so close to the end of the model
536 dp_pairs_rev[rev_cnt].pos = k;
537 dp_pairs_rev[rev_cnt].score = sc;
538 dp_pairs_rev[rev_cnt].max_score = sc;
539 dp_pairs_rev[rev_cnt].score_peak_len = 1;
540 dp_pairs_rev[rev_cnt].consec_pos = 1;
541 dp_pairs_rev[rev_cnt].max_consec_pos = 1;
542 dp_pairs_rev[rev_cnt].consec_consensus = (i==consensus[k] ? 1: 0);
543 dp_pairs_rev[rev_cnt].complementarity = p7_COMPLEMENT;
544 dp_pairs_rev[rev_cnt].model_direction = fm_forward;
545 rev_cnt++;
546 }
547
548 }
549 }
550 }
551
552
553 FM_Recurse ( 2, Kp, fm_forward,
554 fmf, fmb, fm_cfg, ssvdata, consensus,
555 sc_threshFM, dp_pairs_fwd, 0, fwd_cnt-1,
556 &interval_f1, NULL,
557 seeds
558 //, seq
559 );
560
561 FM_Recurse ( 2, Kp, fm_backward,
562 fmf, fmb, fm_cfg, ssvdata, consensus,
563 sc_threshFM, dp_pairs_rev, 0, rev_cnt-1,
564 &interval_bk, &interval_f2,
565 seeds
566 //, seq
567 );
568 }
569
570
571 //merge duplicates
572 FM_mergeSeeds(seeds, fmf->N, fm_cfg->ssv_length);
573
574 free (dp_pairs_fwd);
575 free (dp_pairs_rev);
576 //if (seq) free(seq);
577 return eslOK;
578
579 ERROR:
580 return eslEMEM;
581 }
582
583
584 /* Function: FM_window_from_diag()
585 *
586 * Synopsis: Create a hit window, with sequence-based coordinates, from a diagonal
587 * holding FM-based coordinates
588 *
589 * Details: The submitted diagonal is in FM-based coordinates. Since a single
590 * FM index might be the concatenation of many sequences in the
591 * original, this needs to be converted to coordinates in the
592 * original sequence space (get sequence ID and positions). A diag
593 * might span multiple input strings, so it is broken up as
594 * necessary (usually, only one of these will pan out as a legit
595 * diagonal, but we'll let the next stage sort that out).
596 *
597 * Args: diag - The FM-based diagonal
598 * fm - Data for the FM-index.
599 * meta - FM metadata from the config
600 * windowlist - RETURN: collection of SSV-passing windows, with meta data required for downstream stages.
601 *
602 * Returns: <eslOK> on success.
603 */
604 static int
605 FM_window_from_diag (FM_DIAG *diag, const FM_DATA *fm, const FM_METADATA *meta, P7_HMM_WINDOWLIST *windowlist)
606 {
607 uint32_t seg_id;
608 uint64_t seg_pos;
609 // if diag->complementarity == p7_NOCOMPLEMENT, these positions are in context of FM->T
610 // otherwise, they're in context of revcomp(FM->T).
611
612 fm_getOriginalPosition (fm, meta, 0, diag->length, diag->complementarity, diag->n, &seg_id, &seg_pos);
613
614 p7_hmmwindow_new(windowlist, seg_id, seg_pos, diag->n, diag->k+diag->length-1, diag->length, diag->score, diag->complementarity,
615 meta->seq_data[seg_id].length);
616
617 return eslOK;
618 }
619
620
621 /* Function: FM_extendSeed()
622 * Synopsis: Extend seed in both diagonal directions, capturing the score
623 *
624 * Details: Given a diagonal seed found using FM-index traversal (typically
625 * around length 16, with a modest score, but not necessarily enough
626 * to pass the SSV threshold), establish a window around that seed,
627 * and extend it to maximize score (with the constraint of not going
628 * through a long negative scoring stretch). Capture the score of
629 * this extended diagonal.
630 *
631 * Args: diag - The initial seed
632 * fm - Data for the FM-index (only need the forward FM from the
633 * calling function).
634 * ssvdata - Compact data required for computing MSV (SSV) scores
635 * cfg - FM-index meta data
636 * tmp_sq - Sequence object that this function uses for calculations.
637 * Must be pre-allocated.
638 *
639 * Returns: <eslOK> on success.
640 */
641 static int
642 FM_extendSeed(FM_DIAG *diag, const FM_DATA *fm, const P7_SCOREDATA *ssvdata, FM_CFG *cfg, ESL_SQ *tmp_sq)
643 {
644 uint64_t k,n;
645 int32_t model_start, model_end;
646 int64_t target_start, target_end;
647 int64_t hit_start, max_hit_start, max_hit_end;
648 float sc;
649 float max_sc = 0.0;
650 int c;
651 // this will allow a diagonal to be extended at least 10 bases in each direction, an up to as much as required to allow a diag of length cfg->ssv_length
652 int extend = ESL_MAX(10, cfg->ssv_length - diag->length);
653
654 //this determines the start and end of the window that we think it's possible we'll extend to the window to (which determines the sequence we'll extract)
655 model_start = ESL_MAX ( 1, diag->k - extend + 1) ;
656 model_end = ESL_MIN( ssvdata->M, diag->k + diag->length + extend - 1 );
657 target_start = diag->n - (diag->k - model_start);
658 target_end = diag->n + (model_end - diag->k);
659
660 if (target_start < 0) {
661 model_start -= target_start;
662 target_start = 0;
663 }
664 if (target_end > fm->N-2) {
665 model_end -= target_end - (fm->N-2);
666 target_end = fm->N-2;
667 }
668
669 fm_convertRange2DSQ(fm, cfg->meta, target_start, target_end-target_start+1, diag->complementarity, tmp_sq, FALSE );
670
671
672 //This finds the highest-scoring sub-diag in the just-determined potential diagonal range.
673 k = model_start;
674 n = 1;
675 sc = 0.0;
676
677 hit_start = n;
678 for ( ; k <= model_end; k++, n++) {
679 c = tmp_sq->dsq[n];
680
681 sc += ssvdata->ssv_scores_f[k*tmp_sq->abc->Kp + c];
682
683 if (sc < 0) {
684 sc = 0;
685 hit_start = n+1;
686 } else if (sc > max_sc) {
687 max_sc = sc;
688 max_hit_start = hit_start;
689 max_hit_end = n;
690 }
691 }
692
693
694 diag->n = target_start + max_hit_start - 1;
695 diag->k = model_start + max_hit_start - 1;
696 diag->length = max_hit_end - max_hit_start + 1;
697 diag->score = max_sc;
698
699 return eslOK;
700 }
701
702
703 /* Function: p7_SSVFM_longlarget()
704 * Synopsis: Finds windows with SSV scores above given threshold, using FM-index
705 *
706 * Details: Uses FM-index to find high-scoring diagonals (seeds), then extends those
707 * seeds to maximal scoring diagonals (no gaps). Windows meeting the SSV
708 * scoring threshold (usually score s.t. p=0.02) are captured, and passed
709 * on to the Viterbi and Forward stages of the pipeline.
710 *
711 * Args: om - optimized profile
712 * nu - configuration: expected number of hits (use 2.0 as a default)
713 * bg - the background model, required for translating a P-value threshold into a score threshold
714 * F1 - p-value below which a window is captured as being above threshold
715 * fmf - data for forward traversal of the FM-index
716 * fmb - data for backward traversal of the FM-index
717 * fm_cfg - FM-index meta data
718 * ssvdata - compact data required for computing SSV scores
719 * strands - p7_STRAND_TOPONLY | p7_STRAND_BOTTOMONLY | p7_STRAND_BOTH
720 * windowlist - RETURN: collection of SSV-passing windows, with meta data required for downstream stages.
721 *
722 * Returns: <eslOK> on success.
723 *
724 * Throws: <eslEMEM> if trouble allocating memory for seeds
725 */
726 int
727 p7_SSVFM_longlarget( P7_OPROFILE *om, float nu, P7_BG *bg, double F1,
728 const FM_DATA *fmf, const FM_DATA *fmb, FM_CFG *fm_cfg, const P7_SCOREDATA *ssvdata,
729 int strands, ESL_RANDOMNESS *r, P7_HMM_WINDOWLIST *windowlist)
730 {
731 float sc_thresh, sc_threshFM;
732 float invP;
733 //, invP_FM;
734 float nullsc;
735
736 int i;
737
738 float tloop = logf((float) om->max_length / (float) (om->max_length+3));
739 float tloop_total = tloop * om->max_length;
740 float tmove = logf( 3.0f / (float) (om->max_length+3));
741 float tbmk = logf( 2.0f / ((float) om->M * (float) (om->M+1)));
742 float tec = logf(1.0f / nu);
743 FM_DIAG *diag;
744
745 ESL_SQ *tmp_sq;
746 uint8_t *consensus;
747
748
749 FM_DIAGLIST seeds;
750 int status;
751 status = fm_initSeeds(&seeds);
752 if (status != eslOK)
753 ESL_EXCEPTION(eslEMEM, "Error allocating memory for seed list\n");
754
755 /* convert the consensus to a collection of ints, so I can test for runs of identity to the consensus */
756 ESL_ALLOC(consensus, (om->M+1)*sizeof(uint8_t) );
757 for (i=1; i<=om->M; i++) {
758 consensus[i] = om->abc->inmap[(int)(om->consensus[i])];
759 if (consensus[i] > om->abc->K)
760 consensus[i] = esl_rnd_Roll(r,om->abc->K);
761 }
762
763
764 /* Set false target length. This is a conservative estimate of the length of window that'll
765 * soon be passed on to later phases of the pipeline; used to recover some bits of the score
766 * that we would miss if we left length parameters set to the full target length */
767 p7_oprofile_ReconfigMSVLength(om, om->max_length);
768 p7_bg_SetLength(bg, om->max_length);
769 p7_bg_NullOne (bg, NULL, om->max_length, &nullsc);
770
771 tmp_sq = esl_sq_CreateDigital(om->abc);
772
773 /*
774 * Computing the score required to let P meet the F1 prob threshold
775 * In original code, converting from an SSV score S (the score getting
776 * to state C) to a probability goes like this:
777 * S = XMX(L,p7G_C)
778 * usc = S + tmove + tloop_total
779 * P = f ( (usc - nullsc) / eslCONST_LOG2 , mu, lambda)
780 * and XMX(C) was the diagonal score + tmove + tbmk + tec
781 * and we're computing the threshold score S, so reverse it:
782 * (usc - nullsc) / eslCONST_LOG2 = inv_f( P, mu, lambda)
783 * usc = nullsc + eslCONST_LOG2 * inv_f( P, mu, lambda)
784 * S = usc - tmove - tloop_total - tmove - tbmk - tec
785 *
786 *
787 * Here, I compute threshold with length model based on max_length. Usually, the
788 * length of a window returned by this scan will be 2*max_length-1 or longer. Doesn't
789 * really matter - in any case, both the bg and om models will change with roughly
790 * 1 bit for each doubling of the length model, so they offset.
791 */
792
793 invP = esl_gumbel_invsurv(F1, om->evparam[p7_MMU], om->evparam[p7_MLAMBDA]);
794 sc_thresh = (invP * eslCONST_LOG2) + nullsc - (tmove + tloop_total + tmove + tbmk + tec);
795
796
797 // invP_FM = esl_gumbel_invsurv(0.5, om->evparam[p7_MMU], om->evparam[p7_MLAMBDA]);
798 // sc_threshFM = ESL_MAX(fm_cfg->scthreshFM, (invP_FM * eslCONST_LOG2) + nullsc - (tmove + tloop_total + tmove + tbmk + tec) ) ;
799 sc_threshFM = fm_cfg->scthreshFM * fm_cfg->sc_thresh_ratio;
800
801 //get diagonals that score above sc_threshFM
802 status = FM_getSeeds(fmf, fmb, fm_cfg, ssvdata, consensus, om->abc->Kp, sc_threshFM, strands, &seeds );
803 if (status != eslOK)
804 ESL_EXCEPTION(eslEMEM, "Error allocating memory for seed computation\n");
805
806 //now extend those diagonals to find ones scoring above sc_thresh
807 for(i=0; i<seeds.count; i++) {
808 FM_extendSeed( seeds.diags+i, fmf, ssvdata, fm_cfg, tmp_sq);
809 }
810
811 for(i=0; i<seeds.count; i++) {
812 diag = seeds.diags+i;
813 if (diag->score >= sc_thresh)
814 FM_window_from_diag(diag, fmf, fm_cfg->meta, windowlist );
815
816 }
817
818 esl_sq_Destroy(tmp_sq);
819
820 free(seeds.diags);
821 free(consensus);
822 return eslEOF;
823
824 ERROR:
825 ESL_EXCEPTION(eslEMEM, "Error allocating memory for SSVFM longtarget\n");
826
827 }
828 /*------------------ end, FM_MSV() ------------------------*/
829
830