Debian Codegraph @

src/cm_p7_band.c

raw symbols SCIP
1 /* cm_p7_band.c
2 *
3 * Functions for p7 HMM banding.
4 * BEWARE: only partially implemented.
5 */
6
7 #include <esl_config.h>
8 #include <p7_config.h>
9 #include "config.h"
10
11 #include <stdio.h>
12 #include <math.h>
13 #include <assert.h>
14
15 #include "easel.h"
16 #include "esl_sse.h"
17 #include "esl_vectorops.h"
18
19 #include "hmmer.h"
20
21 #include "infernal.h"
22
23 /* Function: p7_gmx_Match2DMatrix()
24 * Synopsis: Copy the dp match cells of a generic matrix
25 * to a ESL_DMATRIX, for visualization with esl_dmx_Visualize()
26 *
27 * Incept: SRE, Fri Jul 13 09:56:04 2007 [Janelia]
28 *
29 * Purpose: Dump matrix <gx> to stream <fp> for diagnostics.
30 */
31 int
32 p7_gmx_Match2DMatrix(P7_GMX *gx, int do_diff, ESL_DMATRIX **ret_D, double *ret_min, double *ret_max)
33 {
34 int i, k;
35 ESL_DMATRIX *D;
36 double min = eslINFINITY;
37 double max = -eslINFINITY;
38 float sc;
39
40 D = esl_dmatrix_Create(gx->M+1, gx->L);
41 /* fill k == 0 row, the X matrix E state (logically, the begin state) scores */
42 for (i = 1; i <= gx->L; i++) {
43 D->mx[0][(i-1)] = gx->xmx[i * p7G_NXCELLS + 0];
44 }
45
46 for (i = 1; i <= gx->L; i++) {
47 for (k = 1; k <= gx->M; k++) {
48 sc = gx->dp[i][k * p7G_NSCELLS + p7G_M];
49 if(do_diff) {
50 if((i < 2) || (k < 2)) D->mx[k][(i-1)] = 0.;
51 else D->mx[k][(i-1)] = sc - ESL_MAX(D->mx[k][(i-2)], D->mx[0][(i-2)]);
52 }
53 else {
54 D->mx[k][(i-1)] = sc;
55 }
56 min = ESL_MIN(min, D->mx[k][(i-1)]);
57 max = ESL_MAX(max, D->mx[k][(i-1)]);
58 }
59 }
60
61 *ret_D = D;
62 *ret_min = min;
63 *ret_max = max;
64 return eslOK;
65 }
66
67 /****************************************************************
68 * Stolen from hmmer/h3/heatmap.c SVN revision 2171
69 * as dmx_Visualize. Then modified so that the full
70 * matrix is printed (not half split diagonally).
71 */
72 /* my_dmx_Visualize()
73 * Incept: SRE, Wed Jan 24 11:58:21 2007 [Janelia]
74 *
75 * Purpose:
76 *
77 * Color scheme roughly follows Tufte, Envisioning
78 * Information, p.91, where he shows a beautiful
79 * bathymetric chart. The CMYK values conjoin two
80 * recommendations from ColorBrewer (Cindy Brewer
81 * and Mark Harrower)
82 * [http://www.personal.psu.edu/cab38/ColorBrewer/ColorBrewer.html],
83 * specifically the 9-class sequential2 Blues and
84 * 9-class sequential YlOrBr.
85 *
86 * Might eventually become part of Easel, once mature?
87 *
88 * Note: Binning rules basically follow same convention as
89 * esl_histogram. nb = xmax-xmin/w, so w = xmax-xmin/nb;
90 * picking bin is (int) ceil((x - xmin)/w) - 1. (xref
91 * esl_histogram_Score2Bin()). This makes bin b contain
92 * values bw+min < x <= (b+1)w+min. (Which means that
93 * min itself falls in bin -1, whoops - but we catch
94 * all bin<0 and bin>=nshades and put them in the extremes.
95 *
96 * Args:
97 *
98 * Returns:
99 *
100 * Throws: (no abnormal error conditions)
101 *
102 * Xref:
103 */
104 int
105 my_dmx_Visualize(FILE *fp, ESL_DMATRIX *D, double min, double max, double min2fill)
106 {
107 int nshades = 18;
108 double cyan[] = { 1.00, 1.00, 0.90, 0.75, 0.57, 0.38, 0.24, 0.13, 0.03,
109 0.00, 0.00, 0.00, 0.00, 0.00, 0.07, 0.20, 0.40, 0.60};
110 double magenta[] = { 0.55, 0.45, 0.34, 0.22, 0.14, 0.08, 0.06, 0.03, 0.01,
111 0.00, 0.03, 0.11, 0.23, 0.40, 0.55, 0.67, 0.75, 0.80};
112 double yellow[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
113 0.10, 0.25, 0.40, 0.65, 0.80, 0.90, 1.00, 1.00, 1.00};
114 double black[] = { 0.30, 0.07, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
115 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00};
116 double w;
117 int i,j;
118 int bin;
119 int boxsize; /* box size in points */
120 int xcoord, ycoord; /* postscript coords in points */
121 int leftmargin, rightmargin;
122 int bottommargin, topmargin;
123 float fboxsize; /* box size in fractional points */
124
125 /* Set some defaults that might become arguments later.
126 */
127 leftmargin = rightmargin = 20;
128 bottommargin = topmargin = 20;
129
130 /* Determine some working parameters
131 */
132 w = (max-min) / (double) nshades; /* w = bin size for assigning values->colors*/
133 boxsize = ESL_MAX(1, (ESL_MIN((792 - bottommargin) / D->n,
134 (612 - leftmargin) / D->m)));
135 fboxsize= ESL_MIN( (792. - ((float) bottommargin + topmargin)) / (float) D->n,
136 (612. - ((float) leftmargin + rightmargin)) / (float) D->m);
137
138
139 fprintf(fp, "%.4f %.4f scale\n", (fboxsize/(float) boxsize), (fboxsize/(float) boxsize));
140 /* printf("n: %d\nm: %d\n", D->n, D->m); */
141 for (i = 0; i < D->n; i++) {
142 /* printf("\n"); */
143 /* for (j = i; j < D->n; j++) */
144 for (j = 0; j < D->m; j++)
145 {
146 /* printf("i: %4d j: %4d %5.1f\n", i, j, D->mx[i][j]); */
147 xcoord = j * boxsize + leftmargin;
148 ycoord = (D->m-(i+1)) * boxsize + bottommargin; /* difference w/heatmap.c: (D->m-i+1) */
149
150 if (D->mx[i][j] < min2fill) continue;
151 /* if ((i > 0) && (j > 0) && (D->mx[i][j] <= D->mx[i-1][j-1]) && (D->mx[i][j] < min2fill)) continue;*/
152 else if (D->mx[i][j] == -eslINFINITY) bin = 0;
153 else if (D->mx[i][j] == eslINFINITY) bin = nshades-1;
154 else {
155 bin = (int) ceil((D->mx[i][j] - min) / w) - 1;
156 if (bin < 0) bin = 0;
157 if (bin >= nshades) bin = nshades-1;
158 }
159
160 printf("%4d %4d %10.3f\n", i, j, D->mx[i][j]);
161 fprintf(fp, "newpath\n");
162 fprintf(fp, " %d %d moveto\n", xcoord, ycoord);
163 fprintf(fp, " 0 %d rlineto\n", boxsize);
164 fprintf(fp, " %d 0 rlineto\n", boxsize);
165 fprintf(fp, " 0 -%d rlineto\n", boxsize);
166 fprintf(fp, " closepath\n");
167 fprintf(fp, " %.2f %.2f %.2f %.2f setcmykcolor\n",
168 cyan[bin], magenta[bin], yellow[bin], black[bin]);
169 fprintf(fp, " fill\n");
170 }
171 }
172 fprintf(fp, "showpage\n");
173 return eslOK;
174 }
175
176
177 /* Function: my_p7_GTraceMSV()
178 * Incept: EPN, Mon Aug 11 10:01:23 2008
179 *
180 * Purpose: Traceback of a MSV matrix: retrieval of optimum alignment.
181 *
182 * Based on p7_GTrace().
183 *
184 * This function is currently implemented as a
185 * reconstruction traceback, rather than using a shadow
186 * matrix. Because H3 uses floating point scores, and we
187 * can't compare floats for equality, we have to compare
188 * floats for near-equality and therefore, formally, we can
189 * only guarantee a near-optimal traceback. However, even in
190 * the unlikely event that a suboptimal is returned, the
191 * score difference from true optimal will be negligible.
192 *
193 * Args: dsq - digital sequence aligned to, 1..L
194 * L - length of <dsq>
195 * gm - profile
196 * mx - MSV matrix to trace, L x M
197 * tr - storage for the recovered traceback.
198 *
199 * Return: <eslOK> on success.
200 * <eslFAIL> if even the optimal path has zero probability;
201 * in this case, the trace is set blank (<tr->N = 0>).
202 * <eslEINCOMPAT> if the optimal trace is discontiguous wrt
203 * the sequence, node k > kp emits residue i < ip, while kp
204 * emits ip. In this case, trace is invalid - caller must
205 * know this.
206 *
207 * Note: Care is taken to evaluate the prev+tsc+emission
208 * calculations in exactly the same order that Viterbi did
209 * them, lest you get numerical problems with
210 * a+b+c = d; d-c != a+b because d,c are nearly equal.
211 * (This bug appeared in dev: xref J1/121.)
212 */
213
214 /* for HMMER3 P7 HMMs */
215 #define P7MMX(i,k) (dp[(i)][(k) * p7G_NSCELLS + p7G_M])
216 #define P7XMX(i,s) (xmx[(i) * p7G_NXCELLS + (s)])
217 #define P7MSC(k) (rsc[(k) * p7P_NR + p7P_MSC])
218
219 /* for CP9 HMMs */
220 #define CP9TSC(s,k) (tsc[(k) * cp9O_NTRANS + (s)])
221
222 int
223 my_p7_GTraceMSV(const ESL_DSQ *dsq, int L, const P7_PROFILE *gm, const P7_GMX *gx, P7_TRACE *tr, int **ret_i2k, int **ret_k2i, float **ret_isc, int **ret_iconflict)
224 {
225 int status = eslOK;
226 int i; /* position in seq (1..L) */
227 int k; /* position in model (1..M) */
228 int M = gm->M;
229 float **dp = gx->dp;
230 float *xmx = gx->xmx;
231 float tol = 1e-5;
232 float esc = p7_profile_IsLocal(gm) ? 0 : -eslINFINITY;
233 /* new vars */
234 float tloop = logf((float) L / (float) (L+3));
235 float tmove = logf( 3.0f / (float) (L+3));
236 float tbmk = logf( 2.0f / ((float) gm->M * (float) (gm->M+1)));
237 float tec = logf(0.5f);
238
239 int *k2i; /* [0.1..k..gm->M] = i, residue i emitted from node k's match state in MSV trace */
240 int *i2k; /* [0.1..i..L] = k, residue i emitted from node k's match state in MSV trace */
241 int *iconflict; /* [0.1..i..L] = TRUE | FALSE. TRUE to eventually remove the kmer with pin at i */
242 float *isc; /*[0.1..i..L] = sc, match emission score for residue i is sc */
243
244 ESL_ALLOC(k2i, sizeof(int) * (gm->M+1));
245 ESL_ALLOC(i2k, sizeof(int) * (L+1));
246 ESL_ALLOC(iconflict, sizeof(int) * (L+1));
247 ESL_ALLOC(isc, sizeof(float) * (L+1));
248 esl_vec_ISet(k2i, (gm->M+1), -1);
249 esl_vec_ISet(i2k, (L+1), -1);
250 esl_vec_ISet(iconflict, (L+1), FALSE);
251 esl_vec_FSet(isc, (L+1), -eslINFINITY);
252
253 if ((status = p7_trace_Reuse(tr)) != eslOK) goto ERROR;
254
255 /* Initialization.
256 * (back to front. ReverseTrace() called later.)
257 */
258 if ((status = p7_trace_Append(tr, p7T_T, 0, 0)) != eslOK) goto ERROR;
259 if ((status = p7_trace_Append(tr, p7T_C, 0, 0)) != eslOK) goto ERROR;
260 i = L; /* next position to explain in seq */
261
262 /* Traceback
263 */
264 while (tr->st[tr->N-1] != p7T_S) {
265 float const *rsc = gm->rsc[dsq[i]];
266
267 switch (tr->st[tr->N-1]) {
268 case p7T_C: /* C(i) comes from E(i) */
269 if (P7XMX(i,p7G_C) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible C reached at i=%d", i);
270
271 if (esl_FCompare_old(P7XMX(i, p7G_C), P7XMX(i-1, p7G_C) + tloop, tol) == eslOK) {
272 tr->i[tr->N-1] = i--; /* first C doesn't emit: subsequent ones do */
273 status = p7_trace_Append(tr, p7T_C, 0, 0);
274 } else if (esl_FCompare_old(P7XMX(i, p7G_C), P7XMX(i, p7G_E) + tec, tol) == eslOK)
275 status = p7_trace_Append(tr, p7T_E, 0, 0);
276 else ESL_XEXCEPTION(eslFAIL, "C at i=%d couldn't be traced", i);
277 break;
278
279 case p7T_E: /* E connects from any M state. k set here */
280 if (P7XMX(i, p7G_E) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible E reached at i=%d", i);
281
282 if (esl_FCompare_old(P7XMX(i, p7G_E), P7MMX(i,M), tol) == eslOK) { k = M; status = p7_trace_Append(tr, p7T_M, M, i); }
283 else {
284 for (k = M-1; k >= 1; k--)
285 if (esl_FCompare_old(P7XMX(i, p7G_E), P7MMX(i,k) + esc, tol) == eslOK)
286 { status = p7_trace_Append(tr, p7T_M, k, i); break; }
287 if (k < 0) ESL_XEXCEPTION(eslFAIL, "E at i=%d couldn't be traced", i);
288 }
289 break;
290
291 case p7T_M: /* M connects from i-1,k-1, or B */
292 if (P7MMX(i,k) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible M reached at k=%d,i=%d", k,i);
293 if (esl_FCompare_old(P7MMX(i,k), P7XMX(i-1,p7G_B) + tbmk + P7MSC(k), tol) == eslOK) status = p7_trace_Append(tr, p7T_B, 0, 0);
294 else if (esl_FCompare_old(P7MMX(i,k), P7MMX(i-1,k-1) + P7MSC(k), tol) == eslOK) {
295 status = p7_trace_Append(tr, p7T_M, k-1, i-1);
296 /*if(k2i[(k-1)] != -1) { status = eslEINCOMPAT; printf("! discontiguous trace k2i[k-1=%d] != -1 (%d) i-1 = %d\n", k-1, k2i[(k-1)], i-1); goto ERROR;} */
297 /*if(i2k[(i-1)] != -1) { status = eslEINCOMPAT; printf("! discontiguous trace i2k[i-1=%d] != -1 (%d) k-1 = %d\n", i-1, i2k[(i-1)], k-1); goto ERROR;} */
298 if(i2k[(i-1)] != -1 || k2i[(k-1)] != -1) {
299 iconflict[(k2i[(k-1)])] = TRUE; /* eventually remove pin kmer that included k we *thought* pinned i-1 */
300 iconflict[(i-1)] = TRUE; /* eventually remove pin kmer that includes k we currently think pins i-1 */
301 }
302 k2i[(k-1)] = i-1;
303 i2k[(i-1)] = k-1;
304 isc[(i-1)] = P7MSC(k);
305 }
306 else ESL_XEXCEPTION(eslFAIL, "M at k=%d,i=%d couldn't be traced", k,i);
307
308 if (status != eslOK) goto ERROR;
309 k--;
310 i--;
311 break;
312
313 case p7T_N: /* N connects from S, N */
314 if (P7XMX(i, p7G_N) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible N reached at i=%d", i);
315
316 if (i == 0) status = p7_trace_Append(tr, p7T_S, 0, 0);
317 else if (esl_FCompare_old(P7XMX(i,p7G_N), P7XMX(i-1, p7G_N) + tloop, tol) == eslOK)
318 {
319 tr->i[tr->N-1] = i--;
320 status = p7_trace_Append(tr, p7T_N, 0, 0);
321 }
322 else ESL_XEXCEPTION(eslFAIL, "N at i=%d couldn't be traced", i);
323 break;
324
325 case p7T_B: /* B connects from N, J */
326 if (P7XMX(i,p7G_B) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible B reached at i=%d", i);
327
328 if (esl_FCompare_old(P7XMX(i,p7G_B), P7XMX(i, p7G_N) + tmove, tol) == eslOK)
329 status = p7_trace_Append(tr, p7T_N, 0, 0);
330 else if (esl_FCompare_old(P7XMX(i,p7G_B), P7XMX(i, p7G_J) + tmove, tol) == eslOK)
331 status = p7_trace_Append(tr, p7T_J, 0, 0);
332 else ESL_XEXCEPTION(eslFAIL, "B at i=%d couldn't be traced", i);
333 break;
334
335 case p7T_J: /* J connects from E(i) or J(i-1) */
336 if (P7XMX(i,p7G_J) == -eslINFINITY) ESL_XEXCEPTION(eslFAIL, "impossible J reached at i=%d", i);
337
338 if (esl_FCompare_old(P7XMX(i,p7G_J), P7XMX(i-1,p7G_J) + tloop, tol) == eslOK) {
339 tr->i[tr->N-1] = i--;
340 status = p7_trace_Append(tr, p7T_J, 0, 0);
341 } else if (esl_FCompare_old(P7XMX(i,p7G_J), P7XMX(i,p7G_E) + tec, tol) == eslOK)
342 status = p7_trace_Append(tr, p7T_E, 0, 0);
343 else ESL_XEXCEPTION(eslFAIL, "J at i=%d couldn't be traced", i);
344 break;
345
346 default: ESL_XEXCEPTION(eslFAIL, "bogus state in traceback");
347 } /* end switch over statetype[tpos-1] */
348
349 if (status != eslOK) goto ERROR;
350 } /* end traceback, at S state */
351
352 if ((status = p7_trace_Reverse(tr)) != eslOK) goto ERROR;
353 if (ret_i2k != NULL) { *ret_i2k = i2k; } else free(i2k);
354 if (ret_k2i != NULL) { *ret_k2i = k2i; } else free(k2i);
355 if (ret_isc != NULL) { *ret_isc = isc; } else free(isc);
356 if (ret_iconflict != NULL) { *ret_iconflict = iconflict; } else free(iconflict);
357 return eslOK;
358
359 ERROR:
360 if (ret_i2k != NULL) { *ret_i2k = i2k; } else free(i2k);
361 if (ret_k2i != NULL) { *ret_k2i = k2i; } else free(k2i);
362 if (ret_isc != NULL) { *ret_isc = isc; } else free(isc);
363 return status;
364 }
365
366
367
368 /* Function: Parsetree2i_to_k()
369 * Date: EPN, Mon Aug 11 13:41:38 2008
370 *
371 * Purpose: Given a parsetree, fill a vector i2k[0.1..i..L] = k, saying that
372 * residue i is emitted into consensus column k. If k <= 0, this implies
373 * residue i was inserted after consensus column (-1 * k).
374 *
375 * Returns: eslOK on success
376 * eslEINCOMPAT on contract violation.
377 */
378 int
379 Parsetree2i_to_k(CM_t *cm, CMEmitMap_t *emap, int L, char *errbuf, Parsetree_t *tr, int **ret_i2k)
380 {
381 int status; /* Easel status code */
382 int tidx; /* counter through positions in the parsetree */
383 int v; /* state index in CM */
384 int nd;
385 int *i2k;
386
387 ESL_ALLOC(i2k, sizeof(int) * (L+1));
388 esl_vec_ISet(i2k, (L+1), -1 * (cm->clen + 1));
389
390 /* contract check */
391 if(emap == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "Parsetree2i_to_k(): emap == NULL.");
392
393 /* trivial preorder traverse, since we're already numbered that way */
394 for (tidx = 0; tidx < tr->n; tidx++) {
395 v = tr->state[tidx]; /* index of parent state in CM */
396 nd = cm->ndidx[v];
397 if (v == cm->M) continue; /* special case: v is EL, local alignment end */
398 switch (cm->sttype[v]) {
399 case MP_st:
400 i2k[tr->emitl[tidx]] = emap->lpos[nd];
401 i2k[tr->emitr[tidx]] = emap->rpos[nd];
402 break;
403
404 case ML_st:
405 i2k[tr->emitl[tidx]] = emap->lpos[nd];
406 break;
407
408 case MR_st:
409 i2k[tr->emitr[tidx]] = emap->rpos[nd];
410 break;
411
412 case IL_st:
413 i2k[tr->emitl[tidx]] = (-1 * emap->lpos[nd]);
414 break;
415
416 case IR_st:
417 i2k[tr->emitr[tidx]] = (-1 * (emap->rpos[nd] - 1)); /* IR's emit to before consensus column rpos */
418 break;
419
420 }
421 }
422
423 *ret_i2k = i2k;
424 return eslOK;
425
426 ERROR:
427 ESL_FAIL(status, errbuf, "Parsetree2i_to_k(), memory allocation error.");
428 return status; /* NEVERREACHED */
429 }
430
431 /* Function: prune_i2k()
432 * Incept: EPN, Mon Aug 11 15:02:35 2008
433 *
434 * Purpose: Prune an i2k array of pins. Optionally prune by the following
435 * criteria (in this order):
436 * o match score of the pin
437 * o length (n) of n-mer each pin exists in
438 * o proximity to end of n-mer
439 *
440 * Args: i2k - the input pin array, modified (pruned) in place
441 * iconflict - [0.1..i..L] TRUE if i:i2k[i] pin is involved in a conflict, remove the whole nmer pin
442 * isc - score (match emission) for each pin
443 * L - length of current sequence
444 * phi - phi array, phi[k][v] is expected number of times (probability)
445 * state v (0 = match, 1 insert, 2 = delete) in
446 * node k is *entered*. Node 0 is special, state 0 = B state, state 1 = N_state, state 2 = NULL
447 * Calculated *without* taking insert->insert transitions into account.
448 * min_sc - minimum score to allow as a pin, 0. to allow any score
449 * min_len - min n-mer size, 1 to allow any size
450 * min_end - min distance from end to allow, prune away any others, 0 to not prune based on end proximity
451 * min_mprob - min match phi probability to allow in a pin
452 * min_mcprob - min cumulative match phi probability to allow in a nmer pin
453 * max_iprob - max insert phi probability to allow in a pin
454 * max_ilprob - max insert phi probability to allow in a state to the left of a pin
455 *
456 * Return: <eslOK> on success.
457 *
458 */
459 int
460 prune_i2k(int *i2k, int *iconflict, float *isc, int L, double **phi, float min_sc, int min_len, int min_end, float min_mprob, float min_mcprob, float max_iprob, float max_ilprob)
461 {
462 int i, j;
463
464 int do_end;
465 int do_sc;
466 int do_len;
467 float tol = 1e-5;
468 float mcprob = 1.; /* cumulative match probability */
469 int n = 0;
470 int ip;
471
472 do_sc = (esl_FCompare_old(0., min_sc, tol) == eslOK) ? FALSE : TRUE;
473 do_end = (min_end == 0) ? FALSE : TRUE;
474 do_len = (min_len == 1) ? FALSE : TRUE;
475
476 /* pass 1, prune on conflict from trace, this must be first pass */
477 for(i = 1; i <= L; i++) {
478 if(iconflict[i] == TRUE) {
479 /* remove entire nmer's pins */
480 ip = i;
481 while((ip > 0) && (i2k[ip] != -1)) i2k[ip--] = -1;
482 ip = i;
483 while((ip <= L) && (i2k[ip] != -1)) i2k[ip++] = -1;
484 }
485 }
486
487 /* pass 2, prune on scores */
488 if(do_sc) {
489 for(i = 1; i <= L; i++) if((i2k[i] != -1) && (isc[i] < min_sc)) i2k[i] = -1;
490 }
491
492 /* pass 3, prune on phi values */
493 for(i = 1; i <= L; i++) {
494 if(i2k[i] != -1) { /* position i is currently pinned */
495 if ((phi[i2k[i]][HMMMATCH] < min_mprob) || /* match prob too low */
496 (phi[i2k[i]][HMMINSERT] > max_iprob) || /* insert to the right prob too high */
497 (phi[(i2k[i]-1)][HMMINSERT] > max_ilprob)) { /* insert to the left prob too high */
498 /* remove pin */
499 /*printf("removing pin %4d %.4f\n", i, phi[i2k[i]][HMMMATCH]);*/
500 i2k[i] = -1;
501 }
502 }
503 }
504
505 /* pass 4, prune on nmer length, match score, match phi probability, and distance from end */
506 if(do_len || do_end) { /* determine the size n of the n-mer each residue i is in */
507 for(i = 1; i <= L; i++) {
508 if((i2k[i] == -1) || /* position i is not pinned */
509 ((i2k[(i-1)] != -1) && !(i2k[(i-1)] == (i2k[i]-1)))) { /* position i is pinned to k, position i-1 is pinned to kp, but k and kp are not consecutive */
510 /* we just ended an n-mer (n >= 0) */
511 if(n > 0 && n < min_len) {
512 for(j = (i - n); j < i; j++) i2k[j] = -1; /* remove the n-mer */
513 mcprob = 1.;
514 }
515 else if (do_end && n >= min_len) { /* n >= min_len, remove those within do_end of end */
516 for(j = (i - n); j < (i - (n+1)) + min_end; j++) i2k[j] = -1; /* remove the part of the n-mer within nend residues of the beginning edge */
517 for(j = (i - min_end); j < i; j++) i2k[j] = -1; /* remove the part of the n-mer within nend residues of the end edge */
518 }
519 if(i2k[i] == -1) { /* position i is not pinned */
520 mcprob = 1.;
521 n = 0;
522 }
523 else { /* position i is pinned to k, position i-1 is pinned to kp, but k and kp are not consecutive */
524 mcprob = phi[(i2k[i])][HMMMATCH];
525 n = 1;
526 if(mcprob < min_mcprob) { i2k[i] = -1; n = 0; mcprob = 1.; }
527 }
528 }
529 else {
530 n++;
531 mcprob *= phi[(i2k[i])][HMMMATCH];
532 if(mcprob < min_mcprob) { /* remove the n-mer up to this point */
533 for(j = (i - n); j < i; j++) i2k[j] = -1; /* remove the n-mer */
534 mcprob = 1.;
535 n = 0;
536 }
537 }
538 }
539 /* deal with possibility that last n residues were an n-mer, with n < min_len */
540 if(n > 0 && n < min_len) { for(j = (i - n); j < i; j++) i2k[j] = -1; /* remove the n-mer */}
541 }
542
543 return eslOK;
544 }
545
546 /* Function: p7_pins2bands()
547 * Incept: EPN, Mon Aug 11 15:41:44 2008
548 *
549 * Purpose: Given an i2k pins array, determine the imin and imax bands.
550 *
551 * Args: i2k - the input pin array, modified (pruned) in place
552 * errbuf - for error messages
553 * L - length of current sequence
554 * M - number of nodes in the HMM
555 * pad - pad on each side of pin, if pad = 3, we allow +/- 3 residues from pin
556 * ret_kmin - [0.i..L] = k, min node k for residue i
557 * ret_kmax - [0.i..L] = k, max node k for residue i
558 * ret_ncells - number of cells within bands, to return
559 #if 0
560 * ret_imin - [0.k..M] = i, min residue i for node k
561 * ret_imax - [0.k..M] = i, max residue i for node k
562 #endif
563 *
564 * Return: <eslOK> on success.
565 *
566 */
567 int
568 p7_pins2bands(int *i2k, char *errbuf, int L, int M, int pad, int **ret_kmin, int **ret_kmax, int *ret_ncells)
569 {
570 int status;
571
572 int i;
573 int kn = 0;
574 int kx = M;
575 int *kmin, *kmax;
576
577 ESL_ALLOC(kmin, sizeof(int) * (L+1));
578 ESL_ALLOC(kmax, sizeof(int) * (L+1));
579
580 /* traverse residues left to right to get kmins */
581 for(i = 0; i <= L; i++) {
582 if(i2k[i] != -1) {
583 if(kn >= i2k[i] && kn > 1) {
584 ESL_FAIL(eslFAIL, errbuf, "p7_pins2bands() error i: %d, i2k[i]: %d but current kn: %d\n", i, i2k[i], kn);
585 }
586 kn = ESL_MAX(1, i2k[i] - pad);
587 }
588 kmin[i] = kn;
589 }
590
591 /* traverse nodes right to left to get imaxs */
592 for(i = L; i >= 0; i--) {
593 if(i2k[i] != -1) {
594 if(kx <= i2k[i] && kx < L) ESL_FAIL(eslFAIL, errbuf, "p7_pins2bands() error: i: %d, i2k[i]: %d but current kx: %d\n", i, i2k[i], kx);
595 kx = ESL_MIN(M, i2k[i] + pad);
596 }
597 kmax[i] = kx;
598 }
599
600 /* M_0 == B state, which must start the parse with i == 0 */
601 kmin[0] = 0;
602
603 /* get number of cells if wanted */
604 int ncells;
605 if(ret_ncells != NULL) {
606 ncells = 0;
607 for(i = 1; i <= L; i++) ncells += kmax[i] - kmin[i] + 1;
608 *ret_ncells = ncells;
609 }
610
611 if(ret_kmin != NULL) { *ret_kmin = kmin; } else free(kmin);
612 if(ret_kmax != NULL) { *ret_kmax = kmax; } else free(kmax);
613 return eslOK;
614
615 ERROR:
616 ESL_FAIL(status, errbuf, "p7_pins2bands() memory error.");
617 return status; /* NEVERREACHED */
618
619 #if 0
620 /* if we want to get imin/imax instead of kmin/kmax */
621 int in = 1;
622 int ix = L;
623 int *imin;
624 int *imax;
625 int *k2i;
626
627 ESL_ALLOC(imin, sizeof(int) * (M+1));
628 ESL_ALLOC(imax, sizeof(int) * (M+1));
629 ESL_ALLOC(k2i, sizeof(int) * (M+1));
630
631 imin[0] = imax[0] = -1;
632 esl_vec_ISet(k2i, (M+1), -1);
633
634 for(i = 1; i <= L; i++) if(i2k[i] != -1) k2i[i2k[i]] = i;
635
636 /* traverse nodes left to right to get imins */
637 for(k = 1; k <= M; k++) {
638 if(k2i[k] != -1) {
639 if(k2i[k] != 1 && in >= k2i[k]) ESL_FAIL(eslFAIL, errbuf, "p7_pins2bands() error k: %d, k2i[k]: %d but current in: %d\n", k, k2i[k], in);
640 in = ESL_MAX(1, k2i[k] - pad);
641 }
642 imin[k] = in;
643 }
644
645 /* traverse nodes right to left to get imaxs */
646 for(k = M; k >= 1; k--) {
647 if(k2i[k] != L && k2i[k] != -1) {
648 if(ix <= k2i[k]) ESL_FAIL(eslFAIL, errbuf, "p7_pins2bands() error: k: %d, k2i[k]: %d but current ix: %d\n", k, k2i[k], ix);
649 ix = ESL_MIN(L, k2i[k] + pad);
650 }
651 imax[k] = ix;
652 }
653
654 free(k2i);
655
656 /* get number of cells if wanted */
657 int ncells;
658 if(ret_ncells != NULL) {
659 ncells = 0;
660 for(k = 1; k <= M; k++) ncells += imax[k] - imin[k] + 1;
661 *ret_ncells = ncells;
662 }
663 if(ret_imin != NULL) { *ret_imin = imin; } else free(imin);
664 if(ret_imax != NULL) { *ret_imax = imax; } else free(imax);
665 #endif
666 }
667
668 /* Function: DumpP7Bands()
669 * Incept: EPN, Thu Aug 14 08:45:54 2008
670 *
671 * Purpose: Given i2k and kmin, kmax arrays, print them.
672 *
673 * Args: i2k - [0.k..M] = i, node k is pinned to residue i
674 * kmin - [0.i..L] = k, min node k for residue i
675 * kmax - [0.i..L] = k, max node k for residue i
676 * L - length of current sequence
677 *
678 * Return: <eslOK> on success.
679 *
680 */
681 int
682 DumpP7Bands(FILE *fp, int *i2k, int *kmin, int *kmax, int L)
683 {
684 int i;
685
686 fprintf(fp, "# %4s %4s %4s ... %4s\n", "i", "i2k", "kmin", "kmax");
687 fprintf(fp, "# %4s %4s %13s\n", "----", "----", "-------------");
688 for(i = 0; i <= L; i++) {
689 fprintf(fp, " %4d %4d %4d ... %4d\n", i, i2k[i], kmin[i], kmax[i]);
690 }
691 return eslOK;
692
693 }
694
695 /* Function: cp9_ForwardP7B()
696 *
697 * Purpose: Runs the banded Forward dynamic programming algorithm on an
698 * input sequence (1..L). Complements cp9_BackwardP7B().
699 * The 'P7B' suffix indicates plan 7 HMM derived bands
700 * in the kmin and kmax arrays are applied. This function
701 * was derived from cp9_Forward(), differences from that
702 * function were introduced solely to impose bands on the
703 * matrix.
704 *
705 * Because of the bands, some options that exist to cp9_Forward()
706 * (like be_efficient and do_scan and reporting hits in scan mode)
707 * are not available here. This function is meant to be used
708 * solely for first stage of a Forward, Backward, Posterior type
709 * calculation.
710 *
711 * Also due to bands, only L is passed as seq length, instead
712 * of i0 and j0 (seq start/stop). This simplifies the application
713 * of bands kmin[i]/kmax[i] refers to residue i.
714 *
715 * This function requires that local EL states are turned off, if
716 * they're not it returns. A separate function should exist to align
717 * with EL states on, I don't think it's worth the extra computations to
718 * make 1 function that handles both.
719 *
720 * See additional notes in cp9_Forward() "Purpose" section.
721 *
722 * Args:
723 * cp9 - the CP9 HMM
724 * errbuf - char buffer for error messages
725 * mx - the matrix, expanded to correct size (if nec), and filled here
726 * dsq - sequence in digitized form
727 * L - start of target subsequence (1 for beginning of dsq)
728 * kmin - [0.1..i..N] minimum k for residue i
729 * kmax - [0.1..i..N] maximum k for residue i
730 * ret_sc - RETURN: log P(S|M,bands)/P(S|R), as a bit score
731 *
732 * Returns: eslOK on success;
733 * eslEINCOMPAT on contract violation;
734 */
735 #define INBAND(i,k) ((k >= kmin[i]) && (k <= kmax[i]))
736
737 int
738 cp9_ForwardP7B(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int L, int *kmin, int *kmax, float *ret_sc)
739 {
740 int status;
741 int i; /* j-W: position in the subsequence */
742 int k; /* CP9 HMM node position */
743 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
744 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
745 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
746 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
747 int *erow; /* end score for each position [0..1] */
748 int M; /* cp9->M, query length, number of consensus nodes of model */
749 int kp, kn, kx, kpcur, kpprv;
750
751 /* Contract checks */
752 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, cp9 is NULL.\n");
753 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, dsq is NULL.");
754 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, mx is NULL.\n");
755 if(mx->M != cp9->M) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, mx->M != cp9->M.\n");
756 if(kmin == NULL || kmax == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, kmin and/or kmax == NULL.\n");
757 if(cp9->flags & CPLAN9_EL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B, cp9 EL flag up.\n");
758
759 M = cp9->M;
760
761 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
762
763 /* gamma allocation and initialization.
764 * This is a little SHMM that finds an optimal scoring parse
765 * of multiple nonoverlapping hits. */
766
767 /* Rearrange DP matrix for this seq */
768 if((status = GrowCP9Matrix(mx, errbuf, L, M, kmin, kmax, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
769 ESL_DPRINTF2(("#DEBUG: cp9_ForwardP7B(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
770
771 /* Initialization of the zero row. */
772 mmx[0][0] = 0; /* M_0 is state B, and everything starts in B */
773 imx[0][0] = -INFTY; /* I_0 is state N, can't get here without emitting*/
774 dmx[0][0] = -INFTY; /* D_0 doesn't exist. */
775 elmx[0][0]= -INFTY; /* can't go from B to EL state */
776 erow[0] = -INFTY;
777
778 /* Because there's a D state for every node 1..M,
779 dmx[0][k] is possible for all k 1..M (if it's within kmin[0]..kmax[0]) */
780 int sc;
781 i = 0;
782 kn = ESL_MAX(1, kmin[0]);
783 kp = kn - kmin[0];
784 for (k = kn; k <= kmax[0]; k++, kp++) {
785 assert(kp >= 0);
786 mmx[0][kp] = imx[0][kp] = elmx[0][kp] = -INFTY; /* need seq to get here */
787 sc = -INFTY;
788 if(kp > 0) { /* if kp == 0, kp-1 is outside the bands */
789 sc = ILogsum(ILogsum(mmx[0][kp-1] + CP9TSC(cp9O_MD,k-1),
790 imx[0][kp-1] + CP9TSC(cp9O_ID,k-1)),
791 dmx[0][kp-1] + CP9TSC(cp9O_DD,k-1));
792 }
793 dmx[0][kp] = sc;
794 }
795 /* We can do a full parse through all delete states. */
796 erow[0] = -INFTY;
797 if(INBAND(0, M)) { erow[0] = dmx[0][M] + CP9TSC(cp9O_DM,M); }
798
799 /*****************************************************************
800 * The main loop: scan the sequence from position 1 to L.
801 *****************************************************************/
802 /* Recursion. */
803
804 for (i = 1; i <= L; i++)
805 {
806 int const *isc = cp9->isc[dsq[i]];
807 int const *msc = cp9->msc[dsq[i]];
808 int endsc = -INFTY;
809 int sc;
810
811 if(kmin[i] == 0) {
812 mmx[i][0] = -INFTY;
813 dmx[i][0] = -INFTY; /*D_0 is non-existent*/
814 elmx[i][0] = -INFTY; /*no EL state for node 0 */
815 sc = ILogsum(ILogsum(mmx[i-1][0] + CP9TSC(cp9O_MI,0),
816 imx[i-1][0] + CP9TSC(cp9O_II,0)),
817 dmx[i-1][0] + CP9TSC(cp9O_DI,0));
818 imx[i][0] = sc + isc[0];
819 kn = 1; /* kmin[i] + 1 */
820 }
821 else {
822 kn = kmin[i];
823 }
824
825 /*match state*/
826 kn = ESL_MAX(kn, (kmin[i-1]+1)); /* start at first cell from which we can look back to a valid cell at *mx[i-1][k-1] */
827 kx = ESL_MIN(kmax[i], kmax[i-1]+1);
828
829 /* NOT SURE ABOUT THIS AND HOW IT COUPLES WITH BLOCK ABOVE kmin[i] == 0 */
830 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) mmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
831 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) mmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
832
833 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
834 kpprv = kn - kmin[i-1];
835 for (k = kn; k <= kx; k++, kpcur++, kpprv++) {
836 /*printf("M i: %d kpprv: %d\n", i, kpprv);*/
837 assert((kpprv-1) >= 0);
838
839 sc = ILogsum(ILogsum(mmx[i-1][kpprv-1] + CP9TSC(cp9O_MM,k-1),
840 imx[i-1][kpprv-1] + CP9TSC(cp9O_IM,k-1)),
841 dmx[i-1][kpprv-1] + CP9TSC(cp9O_DM,k-1));
842
843 /* FIX ME: inefficient! check B->M_K transition */
844 if(INBAND(i-1, 0)) { /* if i-1 is in k == 0's band */
845 assert(kmin[(i-1)] == 0);
846 if(mmx[i-1][0] != -INFTY)
847 sc = ILogsum(sc, mmx[i-1][0] + CP9TSC(cp9O_BM,k));
848 }
849
850 if(sc != -INFTY) {
851 mmx[i][kpcur] = sc + msc[k];
852 /* E state update */
853 endsc = ILogsum(endsc, mmx[i][kpcur] + CP9TSC(cp9O_ME,k));
854 }
855 else {
856 mmx[i][kpcur] = -INFTY;
857 /* don't update E state */
858 }
859 ///printf("mmx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kpcur, mmx[i][kpcur]);
860 }
861
862 /* insert state*/
863 kn = ESL_MAX(kmin[i], kmin[i-1]);
864 kx = ESL_MIN(kmax[i], kmax[i-1]);
865
866 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) imx[i][kpcur] = -INFTY; /* impossible to reach these guys */
867 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) imx[i][kpcur] = -INFTY; /* impossible to reach these guys */
868
869 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
870 kpprv = kn - kmin[i-1];
871 for (k = kn; k <= kx; k++, kpcur++, kpprv++) {
872 /*insert state*/
873 assert(kpprv >= 0);
874 /* HERE, EVENTUALLY IF kmin/kmax differ b/t Match and Inserts:
875 * only look at match states from k that have i-1 within band */
876 /* all insert states from k should have i-1 within band */
877 /*printf("I i: %d kpprv: %d\n", i, kpprv);*/
878 sc = ILogsum(ILogsum(mmx[i-1][kpprv] + CP9TSC(cp9O_MI,k),
879 imx[i-1][kpprv] + CP9TSC(cp9O_II,k)),
880 dmx[i-1][kpprv] + CP9TSC(cp9O_DI,k));
881 if(sc != -INFTY) imx[i][kpcur] = sc + isc[k];
882 else imx[i][kpcur] = -INFTY;
883 ///printf("imx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kpcur, imx[i][kpcur]);
884 }
885
886 /*delete state*/
887 kn = kmin[i]+1;
888
889 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) dmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
890 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
891 for (k = kn; k <= kmax[i]; k++, kpcur++) { /* should I be adding one for delete off-by-one?? */
892 sc = ILogsum(ILogsum(mmx[i][kpcur-1] + CP9TSC(cp9O_MD,k-1),
893 imx[i][kpcur-1] + CP9TSC(cp9O_ID,k-1)),
894 dmx[i][kpcur-1] + CP9TSC(cp9O_DD,k-1));
895 dmx[i][kpcur] = sc;
896 ///printf("dmx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kpcur, dmx[i][kpcur]);
897 }
898 /*printf("mmx [jp:%d][%d]: %d\n", jp, k, mmx[j][k]);
899 printf("imx [jp:%d][%d]: %d\n", jp, k, imx[j][k]);
900 printf("dmx [jp:%d][%d]: %d\n", jp, k, dmx[j][k]);
901 printf("elmx[jp:%d][%d]: %d\n", jp, k, elmx[j][k]);*/
902
903 if(INBAND(i, M)) {
904 endsc = ILogsum(ILogsum(endsc, dmx[i][M-kmin[i]] + CP9TSC(cp9O_DM,M)), /* transition from D_M -> end */
905 imx[i][M-kmin[i]] + CP9TSC(cp9O_IM,M)); /* transition from I_M -> end */
906 }
907 /* transition penalty to EL incurred when EL was entered */
908 /*printf("endsc: %d\n", endsc);*/
909
910 erow[i] = endsc;
911 } /* end loop over end positions i */
912
913 *ret_sc = Scorify(erow[L]);
914 ESL_DPRINTF1(("#DEBUG: cp9_ForwardP7B() return score: %10.4f\n", Scorify(erow[L])));
915
916 return eslOK;
917 }
918
919
920
921 /* Function: cp9_ForwardP7B_OLD_WITH_EL()
922 *
923 * Purpose: Runs the banded Forward dynamic programming algorithm on an
924 * input sequence (1..L). Complements cp9_BackwardP7B().
925 * The 'P7B' suffix indicates plan 7 HMM derived bands
926 * in the kmin and kmax arrays are applied. This function
927 * was derived from cp9_Forward(), differences from that
928 * function were introduced solely to impose bands on the
929 * matrix.
930 *
931 * Because of the bands, some options that exist to cp9_Forward()
932 * (like be_efficient and do_scan and reporting hits in scan mode)
933 * are not available here. This function is meant to be used
934 * solely for first stage of a ForwardP7B, BackwardP7B, Posterior type
935 * calculation.
936 *
937 * Also due to bands, only L is passed as seq length, instead
938 * of i0 and j0 (seq start/stop). This simplifies the application
939 * of bands kmin[i]/kmax[i] refers to residue i.
940 *
941 * See additional notes in cp9_Forward() "Purpose" section.
942 *
943 * NOTE: EPN, Thu Aug 14 09:54:36 2008
944 * This is the original version written to potentially handle EL
945 * states, but I think omitting them when they're off is significantly
946 * more efficient, so I wrote a competing function called
947 * cp9_ForwardP7B(). Note the included EL dp steps HAVE NOT BEEN
948 * TESTED YET! I just left them here as a starting point if I
949 * ever want to implement them.
950 *
951 * Args:
952 * cp9 - the CP9 HMM
953 * errbuf - char buffer for error messages
954 * mx - the matrix, expanded to correct size (if nec), and filled here
955 * dsq - sequence in digitized form
956 * L - start of target subsequence (1 for beginning of dsq)
957 * kmin - [0.1..i..N] minimum k for residue i
958 * kmax - [0.1..i..N] maximum k for residue i
959 * ret_sc - RETURN: log P(S|M,bands)/P(S|R), as a bit score
960 *
961 * Returns: eslOK on success;
962 * eslEINCOMPAT on contract violation;
963 */
964
965 int
966 cp9_ForwardP7B_OLD_WITH_EL(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int L, int *kmin, int *kmax, float *ret_sc)
967 {
968 int status;
969 int i; /* j-W: position in the subsequence */
970 int k; /* CP9 HMM node position */
971 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
972 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
973 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
974 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
975 int *erow; /* end score for each position [0..1] */
976 int c; /* counter for EL states */
977 int M; /* cp9->M, query length, number of consensus nodes of model */
978 int kn, kx, kpcur, kpprv, kpprv_el;
979
980 /* Contract checks */
981 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B_OLD_WITH_EL, cm->cp9 is NULL.\n");
982 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B_OLD_WITH_EL, dsq is NULL.");
983 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B_OLD_WITH_EL, mx is NULL.\n");
984 if(mx->M != cp9->M) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B_OLD_WITH_EL, mx->M != cp9->M.\n");
985 if(kmin == NULL || kmax == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ForwardP7B_OLD_WITH_EL, kmin and/or kmax == NULL.\n");
986
987 M = cp9->M;
988
989 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
990
991 /* gamma allocation and initialization.
992 * This is a little SHMM that finds an optimal scoring parse
993 * of multiple nonoverlapping hits. */
994
995 /* Grow DP matrix if nec, to either 2 rows or L+1 rows (depending on be_efficient),
996 * stays M+1 columns */
997 if((status = GrowCP9Matrix(mx, errbuf, L, M, kmin, kmax, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
998 ESL_DPRINTF2(("#DEBUG: cp9_ForwardP7B_OLD_WITH_EL(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
999
1000 /* Initialization of the zero row. */
1001 mmx[0][0] = 0; /* M_0 is state B, and everything starts in B */
1002 imx[0][0] = -INFTY; /* I_0 is state N, can't get here without emitting*/
1003 dmx[0][0] = -INFTY; /* D_0 doesn't exist. */
1004 elmx[0][0]= -INFTY; /* can't go from B to EL state */
1005 erow[0] = -INFTY;
1006
1007 /* Because there's a D state for every node 1..M,
1008 dmx[0][k] is possible for all k 1..M */
1009 int sc;
1010 i = 0;
1011 kn = ESL_MAX(1, kmin[0]+1);
1012 kpcur = kn - kmin[0];
1013 for (k = kn; k <= kmax[0]; k++, kpcur++) {
1014 assert(kpcur >= 1);
1015 mmx[0][kpcur] = imx[0][kpcur] = elmx[0][kpcur] = -INFTY; /* need seq to get here */
1016 sc = ILogsum(ILogsum(mmx[0][kpcur-1] + CP9TSC(cp9O_MD,k-1),
1017 imx[0][kpcur-1] + CP9TSC(cp9O_ID,k-1)),
1018 dmx[0][kpcur-1] + CP9TSC(cp9O_DD,k-1));
1019 dmx[0][kpcur] = sc;
1020 }
1021 /* We can do a full parse through all delete states. */
1022 erow[0] = -INFTY;
1023 if(INBAND(0, M)) { erow[0] = dmx[0][M] + CP9TSC(cp9O_DM,M); }
1024
1025 /*****************************************************************
1026 * The main loop: scan the sequence from position 1 to L.
1027 *****************************************************************/
1028 /* Recursion. */
1029
1030 for (i = 1; i <= L; i++)
1031 {
1032 int const *isc = cp9->isc[dsq[i]];
1033 int const *msc = cp9->msc[dsq[i]];
1034 int endsc = -INFTY;
1035 int el_selfsc = cp9->el_selfsc;
1036 int sc;
1037
1038 if(kmin[i] == 0) {
1039 mmx[i][0] = -INFTY;
1040 dmx[i][0] = -INFTY; /*D_0 is non-existent*/
1041 elmx[i][0] = -INFTY; /*no EL state for node 0 */
1042 sc = ILogsum(ILogsum(mmx[i-1][0] + CP9TSC(cp9O_MI,0),
1043 imx[i-1][0] + CP9TSC(cp9O_II,0)),
1044 dmx[i-1][0] + CP9TSC(cp9O_DI,0));
1045 imx[i][0] = sc + isc[0];
1046 kn = 1; /* kmin[i] + 1 */
1047 }
1048 else {
1049 kn = kmin[i];
1050 }
1051
1052 /*match state*/
1053 kn = ESL_MAX(kn, (kmin[i-1]+1)); /* start at first cell from which we can look back to a valid cell at *mx[i-1][k-1] */
1054 kx = ESL_MIN(kmax[i], kmax[i-1]+1);
1055
1056 /* NOT SURE ABOUT THIS AND HOW IT COUPLES WITH BLOCK ABOVE kmin[i] == 0 */
1057 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) mmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1058 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) mmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1059
1060 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) elmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1061 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) elmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1062
1063 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
1064 kpprv = kn - kmin[i-1];
1065 for (k = kn; k <= kx; k++, kpcur++, kpprv++) {
1066 /*printf("M i: %d kpprv: %d\n", i, kpprv);*/
1067 assert((kpprv-1) >= 0);
1068
1069 sc = ILogsum(ILogsum(mmx[i-1][kpprv-1] + CP9TSC(cp9O_MM,k-1),
1070 imx[i-1][kpprv-1] + CP9TSC(cp9O_IM,k-1)),
1071 dmx[i-1][kpprv-1] + CP9TSC(cp9O_DM,k-1));
1072
1073 /* FIX ME: inefficient! check B->M_K transition */
1074 if(INBAND(i-1, 0)) { /* if i-1 is in k == 0's band */
1075 assert(kmin[(i-1)] == 0);
1076 if(mmx[i-1][0] != -INFTY)
1077 sc = ILogsum(sc, mmx[i-1][0] + CP9TSC(cp9O_BM,k));
1078 }
1079
1080 /* check possibility we came from an EL, if they're valid */
1081 for(c = 0; c < cp9->el_from_ct[k]; c++) { /* el_from_ct[k] is >= 0 */
1082 if(INBAND(i-1, cp9->el_from_idx[k][c])) {
1083 kpprv_el = cp9->el_from_idx[k][c] - kmin[(i-1)];
1084 sc = ILogsum(sc, elmx[i-1][kpprv_el]);
1085 }
1086 } /* transition penalty to EL incurred when EL was entered */
1087 if(sc != -INFTY) {
1088 mmx[i][kpcur] = sc + msc[k];
1089 /* E state update */
1090 endsc = ILogsum(endsc, mmx[i][kpcur] + CP9TSC(cp9O_ME,k));
1091 }
1092 else {
1093 mmx[i][kpcur] = -INFTY;
1094 /* don't update E state */
1095 }
1096 /*printf("k: %4d mmx[i:%4d][kpcur:%4d]: %d\n", k, i, kpcur, mmx[i][kpcur]);*/
1097
1098 /* el state */
1099 sc = -INFTY;
1100 if((cp9->flags & CPLAN9_EL) && cp9->has_el[k]) /* not all HMM nodes have an EL state (for ex:
1101 HMM nodes that map to right half of a MATP_MP) */
1102 {
1103 if(mmx[i][kpcur] != -INFTY) {
1104 kpprv_el = k - kmin[(i-1)];
1105 sc = ILogsum(mmx[i][kpcur] + CP9TSC(cp9O_MEL,k), /* transitioned from cur node's match state */
1106 elmx[i-1][kpprv_el] + el_selfsc); /* transitioned from cur node's EL state emitted ip on transition */
1107 }
1108 }
1109 elmx[i][kpcur] = sc;
1110 }
1111
1112 /* insert state*/
1113 kn = ESL_MAX(kmin[i], kmin[i-1]);
1114 kx = ESL_MIN(kmax[i], kmax[i-1]);
1115
1116 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) imx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1117 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) imx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1118
1119 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
1120 kpprv = kn - kmin[i-1];
1121 for (k = kn; k <= kx; k++, kpcur++, kpprv++) {
1122 /*insert state*/
1123 assert(kpprv >= 0);
1124 /* HERE, EVENTUALLY IF kmin/kmax differ b/t Match and Inserts:
1125 * only look at match states from k that have i-1 within band */
1126 /* all insert states from k should have i-1 within band */
1127 /*printf("I i: %d kpprv: %d\n", i, kpprv);*/
1128 sc = ILogsum(ILogsum(mmx[i-1][kpprv] + CP9TSC(cp9O_MI,k),
1129 imx[i-1][kpprv] + CP9TSC(cp9O_II,k)),
1130 dmx[i-1][kpprv] + CP9TSC(cp9O_DI,k));
1131 if(sc != -INFTY) imx[i][kpcur] = sc + isc[k];
1132 else imx[i][kpcur] = -INFTY;
1133 /*printf("k: %4d imx[i:%4d][kpcur:%4d]: %d\n", k, i, kpcur, imx[i][kpcur]);*/
1134 }
1135
1136 /*delete state*/
1137 kn = kmin[i]+1;
1138
1139 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) dmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1140 kpcur = kn - kmin[i]; /* unnec, loop above ends with this */
1141 for (k = kn; k <= kmax[i]; k++, kpcur++) { /* should I be adding one for delete off-by-one?? */
1142 sc = ILogsum(ILogsum(mmx[i][kpcur-1] + CP9TSC(cp9O_MD,k-1),
1143 imx[i][kpcur-1] + CP9TSC(cp9O_ID,k-1)),
1144 dmx[i][kpcur-1] + CP9TSC(cp9O_DD,k-1));
1145 dmx[i][kpcur] = sc;
1146 /*printf("k: %4d dmx[i:%4d][kpcur:%4d]: %d\n", k, i, kpcur, dmx[i][kpcur]);*/
1147 }
1148 /*printf("mmx [jp:%d][%d]: %d\n", jp, k, mmx[j][k]);
1149 printf("imx [jp:%d][%d]: %d\n", jp, k, imx[j][k]);
1150 printf("dmx [jp:%d][%d]: %d\n", jp, k, dmx[j][k]);
1151 printf("elmx[jp:%d][%d]: %d\n", jp, k, elmx[j][k]);*/
1152
1153 if(INBAND(i, M)) {
1154 endsc = ILogsum(ILogsum(endsc, dmx[i][M-kmin[i]] + CP9TSC(cp9O_DM,M)), /* transition from D_M -> end */
1155 imx[i][M-kmin[i]] + CP9TSC(cp9O_IM,M)); /* transition from I_M -> end */
1156 for(c = 0; c < cp9->el_from_ct[M+1]; c++) { /* el_from_ct[k] is >= 0 */
1157 if(INBAND(i, cp9->el_from_idx[M+1][c])) {
1158 kpprv_el = cp9->el_from_idx[M+1][c] - kmin[i];
1159 endsc = ILogsum(endsc, elmx[i][kpprv_el]);
1160 }
1161 }
1162 }
1163 /* transition penalty to EL incurred when EL was entered */
1164 /*printf("endsc: %d\n", endsc);*/
1165
1166 erow[i] = endsc;
1167 } /* end loop over end positions i */
1168
1169 *ret_sc = Scorify(erow[L]);
1170 ESL_DPRINTF1(("#DEBUG: cp9_ForwardP7B_OLD_WITH_EL() return score: %10.4f\n", Scorify(erow[L])));
1171
1172 return eslOK;
1173 }
1174
1175 /* Function: cp9_BackwardP7B()
1176 *
1177 * Purpose: Runs the banded Backward dynamic programming algorithm on an
1178 * input sequence (1..L). Complements cp9_ForwardP7B().
1179 * The 'P7B' suffix indicates plan 7 HMM derived bands
1180 * in the kmin and kmax arrays are applied. This function
1181 * was derived from cp9_Backward(), differences from that
1182 * function were introduced solely to impose bands on the
1183 * matrix.
1184 *
1185 * Because of the bands, some options that exist to cp9_Forward()
1186 * (like be_efficient and do_scan and reporting hits in scan mode)
1187 * are not available here. This function is meant to be used
1188 * solely for second stage of a Forward, Backward, Posterior type
1189 * calculation.
1190 *
1191 * Also due to bands, only L is passed as seq length, instead
1192 * of i0 and j0 (seq start/stop). This simplifies the application
1193 * of bands kmin[i]/kmax[i] refers to residue i.
1194 *
1195 * This function requires that local EL states are turned off, if
1196 * they're not it returns. A separate function should exist to align
1197 * with EL states on, I don't think it's worth the extra computations to
1198 * make 1 function that handles both.
1199 *
1200 * See additional notes in cp9_Backward() "Purpose" section.
1201 *
1202 * Args:
1203 * cp9 - the CP9 HMM
1204 * errbuf - char buffer for error messages
1205 * mx - the matrix, expanded to correct size (if nec), and filled here
1206 * dsq - sequence in digitized form
1207 * L - start of target subsequence (1 for beginning of dsq)
1208 * kmin - [0.1..i..N] minimum k for residue i
1209 * kmax - [0.1..i..N] maximum k for residue i
1210 * ret_sc - RETURN: log P(S|M,bands)/P(S|R), as a bit score, this is B->M[0][0]
1211 *
1212 * Returns: eslOK on success;
1213 * eslEINCOMPAT on contract violation;
1214 */
1215 int
1216 cp9_BackwardP7B(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int L, int *kmin, int *kmax, float *ret_sc)
1217 {
1218 int status;
1219 int i; /* j-W: position in the subsequence */
1220 int k; /* CP9 HMM node position */
1221 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
1222 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
1223 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
1224 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
1225 int *erow; /* end score for each position [0..1] */
1226 int c; /* counter for EL states */
1227 int M; /* cp9->M */
1228 int kpcur, kpprv, kpcur_el;
1229 int kprv, kprvn, kprvx;
1230 int kn, kx;
1231
1232 /* Contract checks */
1233 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_BackwardP7B, cp9 is NULL.\n");
1234 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_BackwardP7B, dsq is NULL.");
1235 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_BackwardP7B, mx is NULL.\n");
1236 if(mx->M != cp9->M) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_BackwardP7B, mx->M != cm->clen.\n");
1237 if(cp9->flags & CPLAN9_EL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_BackwardP7B, cp9 EL flag up!\n");
1238
1239 M = cp9->M;
1240
1241 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
1242
1243 /* Rearrange DP matrix for this seq */
1244 if((status = GrowCP9Matrix(mx, errbuf, L, M, kmin, kmax, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
1245 ESL_DPRINTF2(("#DEBUG: cp9_BackwardP7B(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
1246
1247 /* Initialization of the L row. */
1248 i = L;
1249
1250 /*******************************************************************
1251 * 0 Handle EL, looking at EL_k->E for all valid k.
1252 * we're going backwards so we have to work out of order, we could get
1253 * around this by storing the nodes each EL goes TO in an el_to_ct[] vec. */
1254 /* init to -INFTY */
1255 kpcur = 0;
1256 for (k = kmin[i]; k <= kmax[i]; k++, kpcur++) elmx[i][kpcur] = -INFTY;
1257 if(cp9->flags & CPLAN9_EL)
1258 {
1259 for(c = 0; c < cp9->el_from_ct[cp9->M+1]; c++) /* el_from_ct[cp9->M+1] holds # ELs that can go to END */
1260 if(INBAND(i, cp9->el_from_idx[M+1][c])) {
1261 kpcur_el = cp9->el_from_idx[M+1][c] - kmin[i];
1262 elmx[i][kpcur_el] = 0.;
1263 }
1264 }
1265 /*******************************************************************/
1266
1267 /* elmx[cur][cp9->M] is either 0 (if EL_M exists (it would nec be in el_from_idx[cp9->M+1] array if it does, so
1268 * it would be filled with 0 in above loop), or -INFTY if it doesn't exist. We don't add possibility of EL_M -> EL_M
1269 * self loop b/c it's impossible to do that without emitting, and we've already seen our last res emitted.
1270 * either way we don't have to modify it */
1271
1272 if(INBAND(i, M)) { /* if i is in k == M's band */
1273 assert(M == kmax[i]);
1274 kpcur = M-kmin[i];
1275 mmx[i][kpcur] = 0. +
1276 ILogsum(elmx[i][kpcur] + CP9TSC(cp9O_MEL, M),/* M_M<-EL_M<-E, with 0 self loops in EL_M */
1277 CP9TSC(cp9O_ME,M)); /* M_M<-E ... everything ends in E (the 0; 2^0=1.0) */
1278 mmx[i][kpcur] += cp9->msc[dsq[i]][M]; /* ... + emitted match symbol */
1279 imx[i][kpcur] = 0. + CP9TSC(cp9O_IM,M); /* I_M<-E ... everything ends in E (the 0; 2^0=1.0) */
1280 imx[i][kpcur] += cp9->isc[dsq[i]][M]; /* ... + emitted insert symbol */
1281 dmx[i][kpcur] = CP9TSC(cp9O_DM,M); /* D_M<-E */
1282 kx = M-1;
1283 kpcur--;
1284 }
1285 else { kx = kmax[i]; kpcur = kmax[i]-kmin[i]; }
1286 /*******************************************************************
1287 * No need to look at EL_k->M_M b/c elmx[i] with i == L means last emitted residue was L+1
1288 * and this is impossible if we've come from M_M (only would be valid if we were coming from
1289 * E which is handled above with the EL_k->E code).
1290 *******************************************************************/
1291
1292 for (k = kx; k >= kmin[i]; k--, kpcur--)
1293 {
1294 mmx[i][kpcur] = 0 + CP9TSC(cp9O_ME,k); /*M_k<- E */
1295
1296 if(INBAND(i, k+1)) {
1297 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_MD,k));
1298 }
1299 if(cp9->flags & CPLAN9_EL)
1300 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], elmx[i][kpcur] + CP9TSC(cp9O_MEL,k));
1301
1302 mmx[i][kpcur] += cp9->msc[dsq[i]][k];
1303
1304 /*******************************************************************
1305 * No need to look at EL_k->M_M b/c elmx[i] with i == L means last emitted residue was L+1
1306 * and this is impossible if we've come from M_M (only would be valid if we were coming from
1307 * E which is handled above with the EL_k->E code).
1308 *******************************************************************/
1309
1310 if(INBAND(i, k+1)) {
1311 imx[i][kpcur] = dmx[i][kpcur+1] + CP9TSC(cp9O_ID,k);
1312 imx[i][kpcur] += cp9->isc[dsq[i]][k];
1313
1314 dmx[i][kpcur] = dmx[i][kpcur+1] + CP9TSC(cp9O_DD,k);
1315 }
1316 else {
1317 imx[i][kpcur] = -INFTY;
1318 dmx[i][kpcur] = -INFTY;
1319 }
1320 /* elmx[i][k] was set above, out of order */
1321
1322 ////printf("mmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, mmx[i][kpcur]);
1323 ////printf("imx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, imx[i][kpcur]);
1324 ////printf("dmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, dmx[i][kpcur]);
1325 }
1326
1327 if(INBAND(i, 0)) {
1328 /* remember M_0 is special, the B state, a non-emitter */
1329 mmx[i][0] = dmx[i][1] + CP9TSC(cp9O_MD,0); /* M_0(B)->D_1, no seq emitted, all deletes */
1330 /* above line is diff from CPBackwardOLD() which has mmx[i][0] = -INFTY; */
1331 imx[i][0] = dmx[i][1] + CP9TSC(cp9O_ID,0);
1332 imx[i][0] += cp9->isc[dsq[i]][0];
1333
1334 dmx[i][0] = -INFTY; /*D_0 doesn't exist*/
1335 elmx[i][0] = -INFTY; /*EL_0 doesn't exist*/
1336 }
1337
1338 /*****************************************************************
1339 * The main loop: scan the sequence from position j0-1 to i0.
1340 *****************************************************************/
1341 /* Reision */
1342 for (i = L-1; i >= 1; i--)
1343 {
1344 /* init EL mx to -INFTY */
1345 kpcur = 0;
1346 for (k = kmin[i]; k <= kmax[i]; k++, kpcur++) elmx[i][kpcur] = -INFTY;
1347
1348 /* Deal with node k == M first */
1349 /* elmx[i][k] could have come from self (EL_k), we
1350 * can't have come from END b/c we haven't emitted the last res of the seq yet.
1351 */
1352 if(INBAND(i, M)) {
1353 kpcur = M-kmin[i];
1354 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[M]))
1355 elmx[i][kpcur] = elmx[i][kpcur] + cp9->el_selfsc;
1356
1357 if(INBAND(i+1, M)) {
1358 kpprv = M-kmin[i+1];
1359 mmx[i][kpcur] = imx[i+1][kpprv] + CP9TSC(cp9O_MI,M);
1360 mmx[i][kpcur] += cp9->msc[dsq[i]][M];
1361
1362 imx[i][kpcur] = imx[i+1][kpprv] + CP9TSC(cp9O_II,M);
1363 imx[i][kpcur] += cp9->isc[dsq[i]][M];
1364
1365 dmx[i][M] = imx[i+1][kpprv] + CP9TSC(cp9O_DI,M);
1366 }
1367 else {
1368 mmx[i][kpcur] = imx[i][kpcur] = dmx[i][kpcur] = -INFTY;
1369 }
1370
1371 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[M]))
1372 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], elmx[i][kpcur] + CP9TSC(cp9O_MEL,M));
1373
1374 /*******************************************************************
1375 * 1b Handle EL, looking at EL_k->M_M for all valid k.
1376 * EL_k->M_M transition, which has no transition penalty */
1377 if(INBAND(i+1, M)) {
1378 if(cp9->flags & CPLAN9_EL)
1379 {
1380 for(c = 0; c < cp9->el_from_ct[M]; c++) /* el_from_ct[M] holds # ELs that can go to M_M */
1381 if(INBAND(i, cp9->el_from_idx[M][c])) {
1382 kpcur_el = cp9->el_from_idx[M][c] - kmin[i];
1383 elmx[i][kpcur_el] = ILogsum(elmx[i][kpcur_el], mmx[i+1][kpprv]);
1384 }
1385 }
1386 }
1387 }
1388
1389 /*********************************************************/
1390 /* MATCH: *_k <- M_k+1 transitions FROM a match state*/
1391 kn = ESL_MAX(kmin[i], kmin[i+1]-1); /* start at first cell from which we can look ahead to a valid cell at mmx[i-1][k-1] */
1392 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1393 kx = ESL_MIN(kmax[i], kmax[i+1]-1);
1394
1395 for (kpcur = 0; kpcur < (kn - kmin[i]); kpcur++) mmx[i][kpcur] = imx[i][kpcur] = dmx[i][kpcur] = elmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1396 for (kpcur = kx-kmin[i]+1; kpcur <= kmax[i]-kmin[i]; kpcur++) mmx[i][kpcur] = imx[i][kpcur] = dmx[i][kpcur] = elmx[i][kpcur] = -INFTY; /* impossible to reach these guys */
1397
1398 kpcur = kx - kmin[i]; /* unnec, loop above ends with this */
1399 kpprv = kx - kmin[i+1];
1400 for (k = kx; k >= kn; k--, kpcur--, kpprv--)
1401 {
1402 /* Handle EL, looking at EL_k->M_k for all valid k and EL_k->EL_k
1403 * we're going backwards so we have to work out of order
1404 * we could get around this by storing the nodes each EL goes TO
1405 * in an el_to_ct[] vector. */
1406 if(cp9->flags & CPLAN9_EL) {
1407 for(c = 0; c < cp9->el_from_ct[k]; c++) { /* el_from_ct[k] holds # ELs that can go to M_k */
1408 if(INBAND(i, cp9->el_from_idx[k][c])) {
1409 kpcur_el = cp9->el_from_idx[k][c] - kmin[i];
1410 elmx[i][kpcur_el] = ILogsum(elmx[i][kpcur_el], mmx[i+1][kpprv]);
1411 /* EL<-M, penalty incurred when we enter EL (i.e. leave going backwards) */
1412 }
1413 }
1414 }
1415
1416 /* Finish off elmx[i][k] with possibility of coming from self (EL_k),
1417 * elmx[i][k] will have been filled by block above for ks > current k,
1418 * no M_k -> EL_k' with k' > k */
1419 if(INBAND(i+1, k)) {
1420 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[k]))
1421 elmx[i][k] = ILogsum(elmx[i][kpcur], elmx[i+1][kpprv] + cp9->el_selfsc);
1422 }
1423 mmx[i][kpcur] = mmx[i+1][kpprv+1] + CP9TSC(cp9O_MM,k);
1424 imx[i][kpcur] = mmx[i+1][kpprv+1] + CP9TSC(cp9O_IM,k);
1425 dmx[i][kpcur] = mmx[i+1][kpprv+1] + CP9TSC(cp9O_DM,k);
1426 }
1427
1428 /*********************************************************/
1429 /* INSERTIONS: *_k <- I_k+1 transitions FROM a insert state*/
1430 kn = ESL_MAX(kmin[i], kmin[i+1]); /* start at first cell from which we can look ahead to a valid cell at imx[i-1][k] */
1431 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1432 kx = ESL_MIN(kmax[i], kmax[i+1]);
1433
1434 kpcur = kx - kmin[i]; /* unnec, loop above ends with this */
1435 kpprv = kx - kmin[i+1];
1436 for (k = kx; k >= kn; k--, kpcur--, kpprv--)
1437 {
1438 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], imx[i+1][kpprv] + CP9TSC(cp9O_MI,k));
1439 imx[i][kpcur] = ILogsum(imx[i][kpcur], imx[i+1][kpprv] + CP9TSC(cp9O_II,k));
1440 dmx[i][kpcur] = ILogsum(dmx[i][kpcur], imx[i+1][kpprv] + CP9TSC(cp9O_DI,k));
1441 }
1442
1443 /*********************************************************/
1444 /* DELETIONS: *_k <- D_k+1 transitions FROM a delete state*/
1445 kn = ESL_MAX(kmin[i], kmin[i]-1); /* start at first cell from which we can look ahead to a valid cell at imx[i-1][k] */
1446 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1447 kx = ESL_MIN(kmax[i], kmax[i]-1);
1448
1449 kpcur = kx - kmin[i]; /* unnec, loop above ends with this */
1450 for (k = kx; k >= kn; k--, kpcur--)
1451 {
1452 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_MD,k));
1453 imx[i][kpcur] = ILogsum(imx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_ID,k));
1454 dmx[i][kpcur] = ILogsum(dmx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_DD,k));
1455
1456 /* now add in the emission score */
1457 mmx[i][kpcur] += cp9->msc[dsq[i]][k];
1458 imx[i][kpcur] += cp9->isc[dsq[i]][k];
1459 }
1460 /* there's one valid cell that we didn't consider in above loop to add emission score
1461 * b/c D_k <- D_k+1 (so k+1 is out of bounds for Delete) */
1462 for(k = kx+1; k <= kmax[i]; k++) {
1463 kpcur = k - kmin[i]; /* unnec, loop above ends with this */
1464 mmx[i][kpcur] += cp9->msc[dsq[i]][k];
1465 imx[i][kpcur] += cp9->isc[dsq[i]][k];
1466 }
1467 /*********************************************************/
1468 kpcur = kmax[i] - kmin[i];
1469 for(k = kmax[i]; k >= kmin[i] && k > 0; k--, kpcur--) {
1470 ////printf("mmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, mmx[i][kpcur]);
1471 ////printf("imx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, imx[i][kpcur]);
1472 ////printf("dmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, dmx[i][kpcur]);
1473 }
1474 /* special case when k == 0 */
1475 kpcur = 0;
1476 kpprv = 0 - kmin[i+1];
1477 if(INBAND(i, 0)) {
1478 assert(kmin[i] == 0);
1479 dmx[i][kpcur] = -INFTY; /* D_0 does not exist */
1480 elmx[i][kpcur] = -INFTY; /* EL_0 does not exist */
1481
1482 /* INSERT k=0 */
1483 imx[i][kpcur] = -INFTY;
1484 /* imx[i][0] is filled same as imx[i][1..k] in the loop above */
1485 if(INBAND(i+1, 1)) {
1486 if(mmx[i+1][kpprv+1] != -INFTY)
1487 imx[i][kpcur] = ILogsum(imx[i][kpcur], mmx[i+1][kpprv+1] + CP9TSC(cp9O_IM,0));
1488 }
1489 if(INBAND(i+1, 0)) {
1490 if(imx[i+1][kpprv] != -INFTY)
1491 imx[i][kpcur] = ILogsum(imx[i][kpcur], imx[i+1][kpprv] + CP9TSC(cp9O_II,0));
1492 }
1493 if(INBAND(i, 1)) {
1494 if(dmx[i][kpcur+1] != -INFTY)
1495 imx[i][kpcur] = ILogsum(imx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_ID,0));
1496 }
1497
1498 /*M_0 is the B state, it doesn't emit, and can be reached from any match via a begin transition */
1499 kprvn = ESL_MAX(1, kmin[i+1]);
1500 kprvx = kmax[i+1];
1501 /* careful, don't change kpcur - this is a special case the M_0 state, we loop over all M_k children, only kpprv changes */
1502 kpprv = kprvx - kmin[i+1];
1503 mmx[i][kpcur] = -INFTY;
1504 for(kprv = kprvx; kprv >= kprvn; kprv--, kpprv--) {
1505 if(mmx[i+1][kpprv] != -INFTY)
1506 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (mmx[i+1][kpprv] + CP9TSC(cp9O_BM,kprv)));
1507 }
1508 k = 0;
1509 if(INBAND(i+1, 0)) {
1510 kpprv = k - kmin[i+1];
1511 if(imx[i+1][kpprv] != -INFTY) {
1512 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (imx[i+1][kpprv] + CP9TSC(cp9O_MI,0)));
1513 }
1514 }
1515 if(INBAND(i, 1)) {
1516 if(dmx[i][kpcur+1] != -INFTY) {
1517 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (dmx[i][kpcur+1] + CP9TSC(cp9O_MD,0))); /* B->D_1 */
1518 }
1519 }
1520 }
1521 ////printf("mmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, 0, kpcur, mmx[i][kpcur]);
1522 ////printf("imx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, 0, kpcur, imx[i][kpcur]);
1523 ////printf("dmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, 0, kpcur, dmx[i][kpcur]);
1524 }
1525
1526 /*******************************************************************/
1527 /* Special case: i == 0 */
1528
1529 /* initialize all match, inserts, deletes and ELs to -INFTY
1530 * deletes and M_0 cells MAY get changed later, inserts and ELs always stay -INFTY
1531 * b/c we need at least 1 residue to get to those cells */
1532
1533 i = 0;
1534 kpcur = k - kmin[0];
1535 for (kpcur = 0; kpcur <= kmax[0] - kmin[0]; kpcur++) mmx[i][kpcur] = imx[i][kpcur] = dmx[i][kpcur] = elmx[i][kpcur] = -INFTY;
1536
1537 /* D_M(i == 0) <- I_M(i = 1) */
1538 if(INBAND(i, M)) {
1539 kpcur = M - kmin[i];
1540 kpprv = M - kmin[i+1];
1541 if(INBAND(i+1, M)) {
1542 dmx[i][kpcur] = imx[i+1][kpprv] + CP9TSC(cp9O_DI,M);
1543 }
1544 }
1545
1546 /* update D_k(i == 0) cells */
1547 /* D_k(i == 0) <- M_k+1(i == 1) */
1548 kn = ESL_MAX(kmin[i], kmin[i+1]-1); /* start at first cell from which we can look back to a valid cell at *mx[i-1][k-1] */
1549 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1550 kx = ESL_MIN(kmax[i], kmax[i+1]-1);
1551 kpcur = kx - kmin[i];
1552 kpprv = kx - kmin[i+1];
1553 for (k = kx; k >= kn; k--, kpcur--, kpprv--)
1554 dmx[i][kpcur] = mmx[i+1][kpprv+1] + CP9TSC(cp9O_DM,k);
1555
1556 /* D_k(i == 0) <- I_k(i == 1) */
1557 kn = ESL_MAX(kmin[i], kmin[i+1]); /* start at first cell from which we can look ahead to a valid cell at imx[i-1][k] */
1558 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1559 kx = ESL_MIN(kmax[i], kmax[i+1]);
1560 kpcur = kx - kmin[i]; /* unnec, loop above ends with this */
1561 kpprv = kx - kmin[i+1];
1562 for (k = kx; k >= kn; k--, kpcur--, kpprv--)
1563 dmx[i][kpcur] = ILogsum(dmx[i][kpcur], imx[i+1][kpprv] + CP9TSC(cp9O_DI,k));
1564
1565 /* D_k(i == 0) <- D_k+1(i == 0) */
1566 kn = ESL_MAX(kmin[i], kmin[i]-1); /* start at first cell from which we can look ahead to a valid cell at imx[i-1][k] */
1567 kn = ESL_MAX(kn, 1); /* kn can't go all the way down to 0, that's a special case, handled outside the main loop */
1568 kx = ESL_MIN(kmax[i], kmax[i]-1);
1569 kpcur = kx - kmin[i]; /* unnec, loop above ends with this */
1570 for (k = kx; k >= kn; k--, kpcur--)
1571 dmx[i][kpcur] = ILogsum(dmx[i][kpcur], dmx[i][kpcur+1] + CP9TSC(cp9O_DD,k));
1572
1573 ////printf("mmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, mmx[i][kpcur]);
1574 ////printf("imx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, imx[i][kpcur]);
1575 ////printf("dmx[i:%4d][k:%4d(kp:%4d)] %10d\n", i, k, kpcur, dmx[i][kpcur]);
1576
1577 /* Case when k == 0 (i is still 0) */
1578 k = 0;
1579 if(INBAND(i, 0)) {
1580 assert(kmin[i] == 0);
1581 imx[i][0] = -INFTY; /* need seq to get here */
1582 dmx[i][0] = -INFTY; /* D_0 does not exist */
1583 elmx[i][0] = -INFTY; /* EL_0 does not exist */
1584 mmx[i][0] = -INFTY;
1585
1586 /*M_0 is the B state, it doesn't emit, and can be reached from any match via a begin transition */
1587 kprvn = ESL_MAX(1, kmin[i+1]);
1588 kprvx = kmax[i+1];
1589
1590 kpcur = 0; /* special case, M_0 = B state */
1591 /* careful, this is a different assignment to kpcur b/c it's the M_0 state, we loop over all M_k children, only kpprv changes */
1592 kpprv = kprvx - kmin[i+1];
1593 mmx[i][kpcur] = -INFTY;
1594 for(kprv = kprvx; kprv >= kprvn; kprv--, kpprv--) {
1595 if(mmx[i+1][kpprv] != -INFTY)
1596 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (mmx[i+1][kpprv] + CP9TSC(cp9O_BM,kprv)));
1597 }
1598 k = 0;
1599 if(INBAND(i+1, 0)) {
1600 kpprv = k - kmin[i+1];
1601 if(imx[i+1][kpprv] != -INFTY) {
1602 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (imx[i+1][kpprv] + CP9TSC(cp9O_MI,0)));
1603 }
1604 }
1605 if(INBAND(i, 1)) {
1606 if(dmx[i][kpcur+1] != -INFTY) {
1607 mmx[i][kpcur] = ILogsum(mmx[i][kpcur], (dmx[i][kpcur+1] + CP9TSC(cp9O_MD,0))); /* B->D_1 */
1608 }
1609 }
1610 }
1611 /* No EL contribution here, can't go B->EL_* */
1612
1613 /* final score (fsc) is Scorify(mmx[i][0]); */
1614 /**********************************************************************************/
1615 /* End of Backward recursion */
1616
1617 ESL_DPRINTF1(("#DEBUG: cp9_BackwardP7B() return score: %10.4f\n", Scorify(mmx[i][0])));
1618 return eslOK;
1619 }
1620
1621
1622 /* Function: cp9_CheckFBP7B()
1623 *
1624 * Purpose: Debugging function to make sure the P7 banded
1625 * DP functions cp9_ForwardP7B() and cp9_BackwardP7B()
1626 * are working by checking:
1627 * For all positions i, and states k within kmin[i]..kmax[i]:
1628 * sum_k f[i][k] * b[i][k] = P(x|hmm)
1629 *
1630 * Args: fmx - p7 banded forward dp matrix, already filled
1631 * bmx - p7 banded backward dp matrix, already filled
1632 * hmm - the model
1633 * sc - P(x|hmm, p7 bands) the probability of the entire
1634 * seq given the model
1635 * i0 - start of target subsequence (often 1, beginning of dsq)
1636 * j0 - end of target subsequence (often L, end of dsq)
1637 * dsq - the digitized sequence
1638 *
1639 * Note about sequence position indexing: although this function
1640 * works on a subsequence from i0 to j0, fmx and bmx have offset indices,
1641 * from 1 to L, with L = j0-i0+1.
1642 *
1643 * Return: eslOK on success;
1644 * eslFAIL if any residue fails check
1645 */
1646 int
1647 cp9_CheckFBP7B(CP9_MX *fmx, CP9_MX *bmx, CP9_t *hmm, char *errbuf, float sc, int i0, int j0, ESL_DSQ *dsq, int *kmin, int *kmax)
1648 {
1649 if(fmx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFBP7B(), fmx is NULL.\n");
1650 if(bmx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFBP7B(), bmx is NULL.\n");
1651 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFBP7B(), dsq is NULL.");
1652
1653 int k, i;
1654 float max_diff; /* maximum allowed difference between sc and
1655 * sum_k f[i][k] * b[i][k] for any i */
1656 float diff;
1657 int fb_sum;
1658 float fb_sc;
1659 int L; /* subsequence length */
1660 int kp; /* k', relative k within band; k-kmin[i] */
1661 int to_add;
1662
1663 L = j0-i0+1; /* the length of the subsequence */
1664 max_diff = 0.1; /* tolerance, must be within .1 bits of original score */
1665
1666 /* In all possible paths through the model, each residue of the sequence must have
1667 * been emitted by exactly 1 insert, match or EL state. */
1668 for (i = 1; i <= L; i++) {
1669 fb_sum = -INFTY;
1670 kp = 0;
1671 for (k = kmin[i]; k <= kmax[i]; k++, kp++) {
1672 if (fmx->mmx[i][kp] == -INFTY) to_add = -INFTY;
1673 else if(bmx->mmx[i][kp] == -INFTY) to_add = -INFTY;
1674 else {
1675 to_add = fmx->mmx[i][kp] + bmx->mmx[i][kp];
1676 if(k > 0) to_add -= hmm->msc[dsq[i]][k];
1677 }
1678 /* hmm->msc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx
1679 * unless, we're talking about M_0, the B state, it doesn't emit */
1680 fb_sum = ILogsum(fb_sum, to_add);
1681
1682 /*printf("fmx->mmx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kp, fmx->mmx[i][kp]);
1683 printf("bmx->mmx[i:%4d][k:%4d(%4d)]: %d sum: %d\n", i, k, kp, (bmx->mmx[i][kp]-hmm->msc[dsq[i]][k]), fb_sum);*/
1684
1685 if (fmx->imx[i][kp] == -INFTY) to_add = -INFTY;
1686 else if(bmx->imx[i][kp] == -INFTY) to_add = -INFTY;
1687 else {
1688 to_add = fmx->imx[i][kp] + bmx->imx[i][kp];
1689 to_add -= hmm->isc[dsq[i]][k];
1690 }
1691 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
1692 fb_sum = ILogsum(fb_sum, to_add);
1693
1694 /*printf("fmx->imx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kp, fmx->imx[i][kp]);
1695 printf("bmx->imx[i:%4d][k:%4d(%4d)]: %d sum: %d\n", i, k, kp, (bmx->imx[i][kp]-hmm->isc[dsq[i]][k]), fb_sum);*/
1696
1697 if (fmx->elmx[i][kp] == -INFTY) to_add = -INFTY;
1698 else if(bmx->elmx[i][kp] == -INFTY) to_add = -INFTY;
1699 else {
1700 to_add = fmx->elmx[i][kp] + bmx->elmx[i][kp];
1701 /* EL emissions are by definition zero scoring */
1702 }
1703 fb_sum = ILogsum(fb_sum, to_add);
1704
1705 /*printf("fmx->elmx[i:%4d][k:%4d(%4d)]: %d\n", i, k, kp, fmx->elmx[i][kp]);
1706 printf("bmx->elmx[i:%4d][k:%4d(%4d)]: %d sum: %d\n", i, k, kp, bmx->elmx[i][kp], fb_sum);*/
1707 }
1708 fb_sc = Scorify(fb_sum);
1709 diff = fabs(fb_sc - sc);
1710 /*printf("FB CHECK: i: %4d %10.4f %10.4f (%10.4f)\n", i, fb_sc, sc, diff);*/
1711 if((fabs(diff) > max_diff))
1712 ESL_FAIL(eslFAIL, errbuf, "cp9_CheckFB(), residue at posn i:%d violates sum_k f[i][k]*b[i][k]=P(x|hmm), sum_k = %.4f bits (should be %.4f)\n", i, fb_sc, sc);
1713 }
1714 ESL_DPRINTF1(("#DEBUG: cp9_CheckFB() passed, Forward/Backward matrices pass check.\n"));
1715 /*printf("cp9_CheckFB() passed, Forward/Backward matrices pass check.\n");*/
1716 return eslOK;
1717 }
1718
1719
1720
1721 /* Function: cp9_Seq2BandsP7B
1722 * Date : EPN, Fri Aug 15 13:43:21 2008
1723 *
1724 * Purpose: Given a CM with precalc'ed CP9 HMM, CP9Map, and HMMER3 plan 7
1725 * HMM bands for the CP9 HMM DP matrices, a sequence and
1726 * a CP9Bands_t structure, calculate the CP9 HMM bands and store them
1727 * in the CP9Bands_t structure.
1728 *
1729 * Note: this function was never updated to handle truncated
1730 * alignment.
1731 *
1732 * Args: cm - the covariance model
1733 * errbuf - char buffer for reporting errors
1734 * fmx - CP9 dp matrix for Forward()
1735 * bmx - CP9 dp matrix for Backward()
1736 * pmx - CP9 dp matrix to fill with posteriors, can == bmx
1737 * dsq - sequence in digitized form
1738 * L - length of sequence we're aligning (1..L)
1739 * cp9b - PRE-ALLOCATED, the HMM bands for this sequence, filled here.
1740 * kmin - P7 dervied band to enforce: [0.i..L] = k, min node k for residue i
1741 * kmax - P7 derived band to enforce: [0.i..L] = k, min node k for residue i
1742 * debug_level - verbosity level for debugging printf()s
1743 * Return: eslOK on success;
1744 *
1745 */
1746 int
1747 cp9_Seq2BandsP7B(CM_t *cm, char *errbuf, CP9_MX *fmx, CP9_MX *bmx, CP9_MX *pmx, ESL_DSQ *dsq, int L, CP9Bands_t *cp9b, int *kmin, int *kmax, int debug_level)
1748 {
1749 int status;
1750 int use_sums; /* TRUE to fill and use posterior sums during HMM band calc, yields wider bands */
1751 float sc;
1752 int do_old_hmm2ij;
1753 CP9_t *cp9 = NULL; /* ptr to cp9 HMM (this could be Lcp9, Rcp9, Tcp9 if we update this function to possibly handle truncated alignment) */
1754
1755 /* Contract checks */
1756 if(cm->cp9map == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2BandsP7B, but cm->cp9map is NULL.\n");
1757 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2BandsP7B, dsq is NULL.");
1758 if(!((cm->align_opts & CM_ALIGN_HBANDED) || (cm->search_opts & CM_SEARCH_HBANDED))) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2BandsP7B, CM_ALIGN_HBANDED and CM_SEARCH_HBANDED flags both down, exactly 1 must be up.\n");
1759 if((cm->search_opts & CM_SEARCH_HMMALNBANDS) && (!(cm->search_opts & CM_SEARCH_HBANDED))) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2BandsP7B, CM_SEARCH_HMMALNBANDS flag raised, but not CM_SEARCH_HBANDED flag, this doesn't make sense\n");
1760 if(cm->tau > 0.5) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2BandsP7B, cm->tau (%f) > 0.5, we can't deal.", cm->tau);
1761
1762 use_sums = ((cm->align_opts & CM_ALIGN_SUMS) || (cm->search_opts & CM_SEARCH_SUMS)) ? TRUE : FALSE;
1763 do_old_hmm2ij = ((cm->align_opts & CM_ALIGN_HMM2IJOLD) || (cm->search_opts & CM_SEARCH_HMM2IJOLD)) ? TRUE : FALSE;
1764
1765 /* Determine which cp9 HMM to use: If the CM has local begins on, use cm->cp9loc, else use cm->cp9glb */
1766 cp9 = cm->cp9;
1767 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2Posteriors, relevant cp9 is NULL.\n");
1768
1769 /* Step 1: Get HMM Forward/Backward DP matrices.
1770 * Step 2: F/B -> HMM bands.
1771 * Step 3: HMM bands -> CM bands.
1772 */
1773
1774 /* Step 1: Get HMM Forward/Backward DP matrices. */
1775 if((status = cp9_ForwardP7B (cp9, errbuf, fmx, dsq, L, kmin, kmax, &sc)) != eslOK) return status;
1776 if((status = cp9_BackwardP7B(cp9, errbuf, bmx, dsq, L, kmin, kmax, &sc)) != eslOK) return status;
1777
1778 if(cm->align_opts & CM_ALIGN_CHECKFB) {
1779 if((status = cp9_CheckFBP7B(fmx, bmx, cp9, errbuf, sc, 1, L, dsq, kmin, kmax)) != eslOK) return status;
1780 printf("Forward/Backward matrices checked.\n");
1781 }
1782
1783 /* Step 2: F/B -> HMM bands. */
1784 if(use_sums){
1785 printf("USE SUMS!\n");
1786 exit(1);
1787 }
1788 else {
1789 if((status = cp9_FB2HMMBandsP7B(cp9, errbuf, dsq, fmx, bmx, pmx, cp9b, L, cp9b->hmm_M,
1790 (1.-cm->tau), do_old_hmm2ij, kmin, kmax, debug_level)) != eslOK) return status;
1791 cp9b->tau = cm->tau;
1792 }
1793 if(debug_level > 0) cp9_DebugPrintHMMBands(stdout, L, cp9b, cm->tau, 1);
1794
1795 /* Step 3: HMM bands -> CM bands. */
1796 if(do_old_hmm2ij) {
1797 if((status = cp9_HMM2ijBands_OLD(cm, errbuf, cm->cp9b, cm->cp9map, 1, L, FALSE, debug_level)) != eslOK) return status;
1798 }
1799 else {
1800 if((status = cp9_HMM2ijBands(cm, errbuf, cp9, cm->cp9b, cm->cp9map, 1, L, FALSE, FALSE, debug_level)) != eslOK) return status;
1801 /* For debugging, uncomment this block:
1802 if((status = cp9_HMM2ijBands(cm, errbuf, cm->cp9b, cm->cp9map, i0, j0, doing_search, FALSE, debug_level)) != eslOK) {
1803 ESL_SQ *tmp;
1804 tmp = esl_sq_CreateDigitalFrom(cm->abc, "irrelevant", dsq+i0-1, (j0-i0+1), NULL, NULL, NULL);
1805 esl_sq_Textize(tmp);
1806 printf("HEY! cm: %s\n", cm->name);
1807 printf(">irrelevant\n%s\n", tmp->seq);
1808 esl_sq_Destroy(tmp);
1809 return status;
1810 }
1811 */
1812 }
1813
1814 /* Use the CM bands on i and j to get bands on d, specific to j. */
1815 /* cp9_GrowHDBands() must be called before ij2d_bands() so hdmin, hdmax are adjusted for new seq */
1816 if((status = cp9_GrowHDBands(cp9b, errbuf)) != eslOK) return status;
1817 ij2d_bands(cm, L, cp9b->imin, cp9b->imax, cp9b->jmin, cp9b->jmax, cp9b->hdmin, cp9b->hdmax, FALSE, debug_level);
1818
1819 #if eslDEBUGLEVEL >= 1
1820 if((status = cp9_ValidateBands(cm, errbuf, cp9b, 1, L, FALSE)) != eslOK) return status;
1821 ESL_DPRINTF1(("#DEBUG: bands validated.\n"));
1822 #endif
1823 if(debug_level > 0) debug_print_ij_bands(cm);
1824
1825 if(debug_level > 0) PrintDPCellsSaved_jd(cm, cp9b->jmin, cp9b->jmax, cp9b->hdmin, cp9b->hdmax, L);
1826
1827 return eslOK;
1828 }
1829
1830
1831 /* Function: cp9_Seq2PosteriorsP7B
1832 * Date : EPN, Tue Aug 19 13:12:12 2008
1833 *
1834 * Purpose: Given a CM with precalc'ed CP9 HMM and CP9Map, and HMMER3 plan 7
1835 * HMM bands for the CP9 HMM DP matrices, and a sequence,
1836 * run HMM Forward and Backward algorithms, and return a CP9 posterior
1837 * matrix.
1838 *
1839 * Note: this function was never updated to handle
1840 * truncated alignment (b/c it's currently not hooked up
1841 * to any of the Infernal applications).
1842 *
1843 * Args: cm - the covariance model
1844 * errbuf - char buffer for error messages
1845 * fmx - CP9 dp matrix for Forward()
1846 * bmx - CP9 dp matrix for Backward()
1847 * pmx - CP9 dp matrix to fill with posteriors, can == bmx
1848 * dsq - sequence in digitized form
1849 * L - length of the sequence we're aligning (1..L)
1850 * kmin - P7 dervied band to enforce: [0.i..L] = k, min node k for residue i
1851 * kmax - P7 derived band to enforce: [0.i..L] = k, min node k for residue i
1852 * debug_level - verbosity level for debugging printf()s
1853 *
1854 * Return: eslOK on success
1855 */
1856 int
1857 cp9_Seq2PosteriorsP7B(CM_t *cm, char *errbuf, CP9_MX *fmx, CP9_MX *bmx, CP9_MX *pmx, ESL_DSQ *dsq, int L, int *kmin, int *kmax, int debug_level)
1858 {
1859 int status;
1860 float sc;
1861 CP9_t *cp9 = NULL; /* ptr to cp9 HMM (this could be Lcp9, Rcp9, Tcp9 if we update this function to possibly handle truncated alignment) */
1862
1863 /* Contract checks */
1864 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "in cp9_Seq2Posteriors(), dsq is NULL.");
1865 if(cm->cp9map == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "in cp9_Seq2Posteriors, but cm->cp9map is NULL.\n");
1866 if((cm->align_opts & CM_ALIGN_HBANDED) && (cm->search_opts & CM_SEARCH_HBANDED))
1867 ESL_FAIL(eslEINCOMPAT, errbuf, "in cp9_Seq2Posteriors, CM_ALIGN_HBANDED and CM_SEARCH_HBANDED flags both up, exactly 1 must be up.\n");
1868 if((cm->search_opts & CM_SEARCH_HMMALNBANDS) && (! (cm->search_opts & CM_SEARCH_HBANDED)))
1869 ESL_FAIL(eslEINCOMPAT, errbuf, "in cp9_Seq2Posteriors, CM_SEARCH_HMMALNBANDS flag raised, but not CM_SEARCH_HBANDED flag, this doesn't make sense\n");
1870
1871 /* determine which cp9 HMM to use, if CM is has local begins use cp9 (its local too) else use cp9glb (its global) */
1872 cp9 = cm->cp9;
1873 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Seq2Posteriors, relevant cp9 is NULL.\n");
1874
1875 /* Step 1: Get HMM posteriors.*/
1876 if((status = cp9_ForwardP7B (cp9, errbuf, fmx, dsq, L, kmin, kmax, &sc)) != eslOK) return status;
1877 if(debug_level > 0) printf("CP9P7B Forward score : %.4f\n", sc);
1878
1879 if((status = cp9_BackwardP7B(cp9, errbuf, bmx, dsq, L, kmin, kmax, &sc)) != eslOK) return status;
1880 if(debug_level > 0) printf("CP9 Backward score : %.4f\n", sc);
1881
1882 if(cm->align_opts & CM_ALIGN_CHECKFB) {
1883 if((status = cp9_CheckFBP7B(fmx, bmx, cp9, errbuf, sc, 1, L, dsq, kmin, kmax)) != eslOK) return status;
1884 printf("Forward/Backward matrices checked.\n");
1885 }
1886
1887 /* Get posteriors */
1888 if((status = cp9_PosteriorP7B(dsq, errbuf, L, cp9, fmx, bmx, pmx, kmin, kmax)) != eslOK) return status;
1889
1890 return eslOK;
1891 }
1892
1893
1894 /* Function: cp9_PosteriorP7B()
1895 * based on Ian Holmes' hmmer/src/postprob.c::P7EmitterPosterior()
1896 *
1897 * Purpose: Combines HMMER3 p7 banded Forward and Backward matrices into a
1898 * posterior probability matrix. For emitters (match and inserts) the
1899 * entries in row i of this matrix are the logs of the posterior
1900 * probabilities of each state emitting symbol i of the sequence.
1901 * For non-emitters the entries in row i of this matrix are the
1902 * logs of the posterior probabilities of each state being 'visited'
1903 * when the last emitted residue in the parse was symbol i of the
1904 * sequence.
1905 *
1906 * Args: dsq - sequence in digitized form
1907 * errbuf - for error messages
1908 * L - length of target subsequence 1..L
1909 * hmm - the model
1910 * forward - pre-calculated forward matrix
1911 * backward - pre-calculated backward matrix
1912 * pm - pre-allocated dynamic programming matrix for posteriors
1913 * kmin - P7 derived band to enforce: [0.i..L] = k, min node k for residue i
1914 * kmax - P7 derived band to enforce: [0.i..L] = k, min node k for residue i
1915 *
1916 * Return: eslOK on success;
1917 */
1918 int
1919 cp9_PosteriorP7B(ESL_DSQ *dsq, char *errbuf, int L, CP9_t *hmm, CP9_MX *fmx, CP9_MX *bmx, CP9_MX *pmx, int *kmin, int *kmax)
1920 {
1921 int i;
1922 int k;
1923 int sc;
1924 int M = hmm->M;
1925 int kp, kn, kx;
1926 /*float temp_sc;*/
1927
1928 if(bmx != pmx) GrowCP9Matrix(pmx, errbuf, L, M, kmin, kmax, NULL, NULL, NULL, NULL, NULL);
1929
1930 /* parses must start/stop at (i = 1)/(j = L) */
1931 sc = bmx->mmx[0][0];
1932
1933 /* note boundary conditions, i = 1 */
1934 assert(kmin[0] == 0);
1935 pmx->mmx[0][0] = fmx->mmx[0][0] + bmx->mmx[0][0] - sc; /* fmx->mmx[0][0] is 0, bmx->mmx[1][0] is overall score */
1936 pmx->imx[0][0] = -INFTY; /*need seq to get here*/
1937 pmx->dmx[0][0] = -INFTY; /*D_0 does not exist*/
1938 i = 0;
1939 kn = ESL_MAX(kmin[i], 1);
1940 kx = kmax[i];
1941 kp = kn - kmin[i];
1942 for (k = kn; k <= kx; k++, kp++) {
1943 pmx->mmx[0][kp] = -INFTY; /*need seq to get here*/
1944 pmx->imx[0][kp] = -INFTY; /*need seq to get here*/
1945 pmx->dmx[0][kp] = fmx->dmx[0][kp] + bmx->dmx[0][kp] - sc;
1946 }
1947
1948 for (i = 1; i <= L; i++) {
1949 k = 0;
1950 if(INBAND(i,0)) {
1951 kp = k - kmin[i];
1952 assert(kp == 0);
1953 pmx->mmx[i][kp] = ESL_MAX(fmx->mmx[i][kp] + bmx->mmx[i][kp] - sc, -INFTY); /* M_0 doesn't emit */
1954 pmx->imx[i][kp] = ESL_MAX(fmx->imx[i][kp] + bmx->imx[i][kp] - hmm->isc[dsq[i]][0] - sc, -INFTY);
1955 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
1956 pmx->dmx[i][kp] = -INFTY; /* D_0 doesn't exist */
1957 }
1958
1959 kn = ESL_MAX(kmin[i], 1);
1960 kx = kmax[i];
1961 kp = kn - kmin[i];
1962 for(k = kn; k <= kx; k++, kp++)
1963 {
1964 pmx->mmx[i][kp] = ESL_MAX(fmx->mmx[i][kp] + bmx->mmx[i][kp] - hmm->msc[dsq[i]][k] - sc, -INFTY);
1965 /*hmm->msc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
1966 pmx->imx[i][kp] = ESL_MAX(fmx->imx[i][kp] + bmx->imx[i][kp] - hmm->isc[dsq[i]][k] - sc, -INFTY);
1967 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
1968 pmx->dmx[i][kp] = ESL_MAX(fmx->dmx[i][kp] + bmx->dmx[i][kp] - sc, -INFTY);
1969 }
1970 }
1971
1972 /*
1973 float temp_sc;
1974 for(i = 0; i <= L; i++)
1975 {
1976 kp = 0;
1977 for(k = kmin[i]; k <= kmax[i]; k++, kp++)
1978 {
1979 temp_sc = Score2Prob(mx->mmx[i][kp], 1.);
1980 if(temp_sc > .0001)
1981 printf("mx->mmx[%3d][%3d]: %9d | %8f\n", i, k, mx->mmx[i][kp], temp_sc);
1982 temp_sc = Score2Prob(mx->imx[i][kp], 1.);
1983 if(temp_sc > .0001)
1984 printf("mx->imx[%3d][%3d]: %9d | %8f\n", i, k, mx->imx[i][kp], temp_sc);
1985 temp_sc = Score2Prob(mx->dmx[i][kp], 1.);
1986 if(temp_sc > .0001)
1987 printf("mx->dmx[%3d][%3d]: %9d | %8f\n", i, k, mx->dmx[i][kp], temp_sc);
1988 }
1989 }*/
1990 return eslOK;
1991 }
1992
1993 /* Function: cp9_FB2HMMBandsP7B()
1994 * Date: EPN, Fri Aug 15 14:00:59 2008
1995 *
1996 * Purpose: Determine the band on all HMM states given HMMER3 Plan 7 Banded
1997 * Forward and Backward matrices. Do this by calculating and summing
1998 * log posterior probabilities that each state emitted/was visited at each posn,
1999 * starting at the band ends, and creeping in, until the half the
2000 * maximum allowable probability excluded is reached on each side.
2001 *
2002 * Args:
2003 *
2004 * CP9_t hmm the HMM
2005 * errbuf char buffer for error messages
2006 * CP9_MX fmx: forward DP matrix, already calc'ed
2007 * CP9_MX bmx: backward DP matrix, already calc'ed
2008 * CP9_MX pmx: DP matrix for posteriors, filled here, can == bmx
2009 * dsq the digitized sequence
2010 * CP9Bands_t cp9b CP9 bands data structure
2011 * int L length of target subsequence (1..L)
2012 * int M number of nodes in HMM (num columns of pmx matrix)
2013 * double p_thresh the probability mass we're requiring is within each band
2014 * int do_old_hmm2ij TRUE if we'll use old cp9_HMM2ijBands_OLD() function downstream
2015 * int kmin P7 dervied band to enforce: [0.i..L] = k, min node k for residue i
2016 * int kmax P7 derived band to enforce: [0.i..L] = k, min node k for residue i
2017 * int debug_level [0..3] tells the function what level of debugging print
2018 * statements to print.
2019 *
2020 * Returns: eslOK on success;
2021 */
2022 int
2023 cp9_FB2HMMBandsP7B(CP9_t *hmm, char *errbuf, ESL_DSQ *dsq, CP9_MX *fmx, CP9_MX *bmx, CP9_MX *pmx, CP9Bands_t *cp9b,
2024 int L, int M, double p_thresh, int do_old_hmm2ij, int *kmin, int *kmax, int debug_level)
2025 {
2026 int status;
2027 int k; /* counter over nodes of the model */
2028 int thresh = Prob2Score(((1. - p_thresh)/2.), 1.); /* allowable prob mass excluded on each side */
2029
2030 /* *_m = match, *_i = insert, *_d = delete */
2031 int *kthresh_m, *kthresh_i, *kthresh_d; /* [0..k..hmm->M], individual thresholds for each state */
2032 int *nset_m, *nset_i, *nset_d; /* [0..k..hmm->M], has minimum been set for this state? */
2033 int *xset_m, *xset_i, *xset_d; /* [0..k..hmm->M], has maximum been set for this state? */
2034 int *mass_m, *mass_i, *mass_d; /* [0..k..hmm->M], summed log prob of pmx->mx[i][k] from 0..k or k..L */
2035 int i; /* actual position */
2036 int sc; /* summed score of all parses (derived from backward matrix)
2037 * if(cm->search_opts & CM_SEARCH_HMMALNBANDS) Forward and Backward
2038 * were run in 'scan mode' where each residue can be begin/end of a parse,
2039 * so we have to sum up parses that end at each posn,
2040 * if ! (cm->search_opts & CM_SEARCH_HMMALNBANDS) we know we have
2041 * to start at residue 1 and end at residue L, so sc is simply bmx->mmx[0][0]
2042 */
2043 int hmm_is_localized; /* TRUE if HMM has local begins, ends or ELs on */
2044 int kp, kn, kx;
2045
2046 hmm_is_localized = ((hmm->flags & CPLAN9_LOCAL_BEGIN) || (hmm->flags & CPLAN9_LOCAL_END) || (hmm->flags & CPLAN9_EL)) ? TRUE : FALSE;
2047
2048 if(bmx != pmx) GrowCP9Matrix(pmx, errbuf, L, M, kmin, kmax, NULL, NULL, NULL, NULL, NULL);
2049
2050 /* allocations and initializations */
2051 ESL_ALLOC(nset_m, sizeof(int) * (M+1));
2052 ESL_ALLOC(nset_i, sizeof(int) * (M+1));
2053 ESL_ALLOC(nset_d, sizeof(int) * (M+1));
2054 ESL_ALLOC(xset_m, sizeof(int) * (M+1));
2055 ESL_ALLOC(xset_i, sizeof(int) * (M+1));
2056 ESL_ALLOC(xset_d, sizeof(int) * (M+1));
2057 ESL_ALLOC(mass_m, sizeof(int) * (M+1));
2058 ESL_ALLOC(mass_i, sizeof(int) * (M+1));
2059 ESL_ALLOC(mass_d, sizeof(int) * (M+1));
2060 ESL_ALLOC(kthresh_m, sizeof(int) * (M+1));
2061 ESL_ALLOC(kthresh_i, sizeof(int) * (M+1));
2062 ESL_ALLOC(kthresh_d, sizeof(int) * (M+1));
2063
2064 esl_vec_ISet(mass_m, M+1, -INFTY);
2065 esl_vec_ISet(mass_i, M+1, -INFTY);
2066 esl_vec_ISet(mass_d, M+1, -INFTY);
2067 esl_vec_ISet(nset_m, M+1, FALSE);
2068 esl_vec_ISet(nset_i, M+1, FALSE);
2069 esl_vec_ISet(nset_d, M+1, FALSE);
2070 esl_vec_ISet(xset_m, M+1, FALSE);
2071 esl_vec_ISet(xset_i, M+1, FALSE);
2072 esl_vec_ISet(xset_d, M+1, FALSE);
2073
2074 sc = bmx->mmx[0][0]; /* Forward/Backward run in 'align mode' parses must start at 1, end at L */
2075 /* sc is summed log prob of all possible parses of seq 1..L */
2076
2077 /* note boundary conditions, i = 1 */
2078 assert(kmin[0] == 0);
2079 pmx->mmx[0][0] = fmx->mmx[0][0] + bmx->mmx[0][0] - sc; /* fmx->mmx[0][0] is 0, bmx->mmx[1][0] is overall score */
2080 pmx->imx[0][0] = -INFTY; /*need seq to get here*/
2081 pmx->dmx[0][0] = -INFTY; /*D_0 does not exist*/
2082 if((mass_m[0] = pmx->mmx[0][0]) > thresh) {
2083 cp9b->pn_min_m[0] = 0;
2084 nset_m[0] = TRUE;
2085 }
2086 mass_i[0] = -INFTY; /* b/c pmx->imx[0][0] is -INFTY, set above */
2087 mass_d[0] = -INFTY; /* b/c pmx->dmx[0][0] is -INFTY, set above */
2088
2089 i = 0;
2090 kn = ESL_MAX(kmin[i], 1);
2091 kx = kmax[i];
2092 kp = kn - kmin[i];
2093 for (k = kn; k <= kx; k++, kp++) {
2094 pmx->mmx[0][kp] = -INFTY; /*need seq to get here*/
2095 pmx->imx[0][kp] = -INFTY; /*need seq to get here*/
2096 pmx->dmx[0][kp] = fmx->dmx[0][kp] + bmx->dmx[0][kp] - sc;
2097 /* mass_m[k] doesn't change b/c pmx->mmx[0][kp] is -INFTY */
2098 /* mass_i[k] doesn't change b/c pmx->imx[0][kp] is -INFTY */
2099 if((mass_d[k] = pmx->dmx[0][kp]) > thresh) {
2100 cp9b->pn_min_d[k] = 0;
2101 nset_d[k] = TRUE;
2102 }
2103 }
2104
2105 /* Find minimum position in band for each state (M,I,D) of each node (0..M) */
2106 for (i = 1; i <= L; i++) {
2107 k = 0;
2108 if(INBAND(i,0)) {
2109 kp = k - kmin[i];
2110 assert(kp == 0);
2111 pmx->mmx[i][kp] = ESL_MAX(fmx->mmx[i][kp] + bmx->mmx[i][kp] - sc, -INFTY); /* M_0 doesn't emit */
2112 if(! nset_m[0]) {
2113 if((mass_m[0] = ILogsum(mass_m[0], pmx->mmx[i][kp])) > thresh) {
2114 cp9b->pn_min_m[0] = i;
2115 nset_m[0] = TRUE;
2116 }
2117 }
2118
2119 pmx->imx[i][kp] = ESL_MAX(fmx->imx[i][kp] + bmx->imx[i][kp] - hmm->isc[dsq[i]][0] - sc, -INFTY);
2120 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
2121 if(! nset_i[0]) {
2122 if((mass_i[0] = ILogsum(mass_i[0], pmx->imx[i][kp])) > thresh) {
2123 cp9b->pn_min_i[0] = i;
2124 nset_i[0] = TRUE;
2125 }
2126 }
2127 pmx->dmx[i][kp] = -INFTY; /* D_0 doesn't exist */
2128 }
2129
2130 kn = ESL_MAX(kmin[i], 1);
2131 kx = kmax[i];
2132 kp = kn - kmin[i];
2133 for(k = kn; k <= kx; k++, kp++)
2134 {
2135 pmx->mmx[i][kp] = ESL_MAX(fmx->mmx[i][kp] + bmx->mmx[i][kp] - hmm->msc[dsq[i]][k] - sc, -INFTY);
2136 /*hmm->msc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
2137 pmx->imx[i][kp] = ESL_MAX(fmx->imx[i][kp] + bmx->imx[i][kp] - hmm->isc[dsq[i]][k] - sc, -INFTY);
2138 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
2139 pmx->dmx[i][kp] = ESL_MAX(fmx->dmx[i][kp] + bmx->dmx[i][kp] - sc, -INFTY);
2140
2141 if(! nset_m[k]) {
2142 if((mass_m[k] = ILogsum(mass_m[k], pmx->mmx[i][kp])) > thresh) {
2143 cp9b->pn_min_m[k] = i;
2144 nset_m[k] = TRUE;
2145 }
2146 }
2147 if(! nset_i[k]) {
2148 if((mass_i[k] = ILogsum(mass_i[k], pmx->imx[i][kp])) > thresh) {
2149 cp9b->pn_min_i[k] = i;
2150 nset_i[k] = TRUE;
2151 }
2152 }
2153 if(! nset_d[k]) {
2154 if((mass_d[k] = ILogsum(mass_d[k], pmx->dmx[i][kp])) > thresh) {
2155 cp9b->pn_min_d[k] = i;
2156 nset_d[k] = TRUE;
2157 }
2158 }
2159 }
2160 }
2161
2162 esl_vec_ISet(mass_m, M+1, -INFTY);
2163 esl_vec_ISet(mass_i, M+1, -INFTY);
2164 esl_vec_ISet(mass_d, M+1, -INFTY);
2165 /* Find maximum position in band for each state (M,I,D) of each node (0..M)
2166 * by moving from L down to 1 */
2167 for (i = L; i >= 1; i--) /* i is the relative position in the seq */
2168 {
2169 kp = 0;
2170 for(k = kmin[i]; k <= kmax[i]; k++, kp++)
2171 {
2172 if(! xset_m[k]) {
2173 if((mass_m[k] = ILogsum(mass_m[k], pmx->mmx[i][kp])) > thresh) {
2174 cp9b->pn_max_m[k] = i;
2175 xset_m[k] = TRUE;
2176 }
2177 }
2178 if(! xset_i[k]) {
2179 if((mass_i[k] = ILogsum(mass_i[k], pmx->imx[i][kp])) > thresh) {
2180 cp9b->pn_max_i[k] = i;
2181 xset_i[k] = TRUE;
2182 }
2183 }
2184 if(! xset_d[k]) {
2185 if((mass_d[k] = ILogsum(mass_d[k], pmx->dmx[i][kp])) > thresh) {
2186 cp9b->pn_max_d[k] = i;
2187 xset_d[k] = TRUE;
2188 }
2189 }
2190 }
2191 }
2192 /* note boundary conditions, i = 0 */
2193 if(INBAND(0,0)) {
2194 assert(kmin[0] == 0);
2195 if(! xset_m[0]) {
2196 if((mass_m[0] = ILogsum(mass_m[0], pmx->mmx[0][0])) > thresh) {
2197 cp9b->pn_max_m[0] = 0;
2198 xset_m[0] = TRUE;
2199 }
2200 }
2201 }
2202 /* mass_i[0] is unchaged because b/c pmx->imx[0][0] is -INFTY, set above */
2203 /* mass_d[0] is unchaged because b/c pmx->dmx[0][0] is -INFTY, set above */
2204 kn = ESL_MAX(kmin[i], 1);
2205 kx = kmax[i];
2206 kp = kn - kmin[i];
2207 for(k = kn; k <= kx; k++, kp++) {
2208 /* mass_m[k] doesn't change b/c pmx->mmx[0][k] is -INFTY */
2209 /* mass_i[k] doesn't change b/c pmx->mmx[0][k] is -INFTY */
2210 if(!xset_d[k]) {
2211 if((mass_d[k] = ILogsum(mass_d[k], pmx->dmx[0][kp])) > thresh) {
2212 cp9b->pn_max_d[k] = 0;
2213 xset_d[k] = TRUE;
2214 }
2215 }
2216 }
2217
2218 /* new technique as of EPN, Sun Jan 27 08:48:34 2008 */
2219 /* Some states may not have had their min/max set. This occurs if the entire
2220 * state is outside the band (i.e. the summed probability the state is entered for ANY i
2221 * is less than our threshold. Current strategy in this situation is to set the
2222 * pn_min_* and pn_max_* values as special flags, (-2) so the function that
2223 * uses them to derive i and j bands knows this is the case and handles it
2224 * accordingly.
2225 */
2226 int mset;
2227 int dset;
2228 for(k = 0; k <= M; k++) {
2229 mset = dset = TRUE;
2230 /* theoretically either nset_*[k] and xset_*[k] should be either both TRUE or both
2231 * FALSE, but I'm slightly worried about rare precision issues, so we check if one
2232 * or the other is unset, and if so, we set both to argmax position */
2233 if(((! nset_m[k])) || (! xset_m[k]) || (cp9b->pn_max_m[k] < cp9b->pn_min_m[k])) {
2234 cp9b->pn_min_m[k] = cp9b->pn_max_m[k] = -1;
2235 mset = FALSE;
2236 }
2237 if(((! nset_i[k])) || (! xset_i[k]) || (cp9b->pn_max_i[k] < cp9b->pn_min_i[k])) {
2238 cp9b->pn_min_i[k] = cp9b->pn_max_i[k] = -1;
2239 }
2240 if(((! nset_d[k])) || (! xset_d[k]) || (cp9b->pn_max_d[k] < cp9b->pn_min_d[k])) {
2241 cp9b->pn_min_d[k] = cp9b->pn_max_d[k] = -1;
2242 dset = FALSE;
2243 }
2244 if((!hmm_is_localized) && (mset == FALSE && dset == FALSE)) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "node: %d match nor delete HMM state bands were set in non-localized, non-scanning HMM, lower tau (should be << 0.5).\n", k);
2245 }
2246
2247 cp9b->pn_min_d[0] = -1; /* D_0 doesn't exist */
2248 cp9b->pn_max_d[0] = -1; /* D_0 doesn't exist */
2249
2250 if(debug_level > 0) cp9_DebugPrintHMMBands(stdout, L, cp9b, (1.-p_thresh), 1);
2251
2252 free(mass_m);
2253 free(mass_i);
2254 free(mass_d);
2255 free(nset_m);
2256 free(nset_i);
2257 free(nset_d);
2258 free(xset_m);
2259 free(xset_i);
2260 free(xset_d);
2261 free(kthresh_m);
2262 free(kthresh_i);
2263 free(kthresh_d);
2264
2265 return eslOK;
2266
2267 ERROR:
2268 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
2269 }
2270
2271
2272
2273 /* Function: p7_Seq2Bands
2274 * Date : EPN, Fri Aug 15 14:29:01 2008
2275 *
2276 * Purpose: Given a CM with a valid Plan 7 HMM - run the MSV algorithm
2277 * to determine bands to be used on the CP9 HMM parse.
2278 *
2279 * Args: cm - the covariance model
2280 * errbuf - char buffer for reporting errors
2281 * P7_PROFILE - generic profile
2282 * P7_GMX - generic P7 dp matrix
2283 * P7_BG - P7 null model
2284 * P7_TR - P7 trace
2285 * dsq - sequence in digitized form
2286 * L - length of sequence we're aligning (1..L)
2287 * phi - phi array, phi[k][v] is expected number of times (probability)
2288 * state v (0 = match, 1 insert, 2 = delete) in
2289 * node k is *entered*. Node 0 is special, state 0 = B state, state 1 = N_state, state 2 = NULL
2290 * Calculated *without* taking insert->insert transitions into account.
2291 * sc7 - minimum score to allow as a pin, 0. to allow any score
2292 * len7 - min n-mer size, 1 to allow any size
2293 * end7 - min distance from end to allow, prune away any others, 0 to not prune based on end proximity
2294 * mprob7 - min match phi probability to allow in a pin
2295 * mcprob7 - min cumulative match phi probability to allow in a nmer pin
2296 * iprob7 - max insert phi probability to allow in a pin
2297 * ilprob7 - max insert phi probability to allow in a state to the left of a pin
2298 * ret_i2k - [0.i..L] = k, residue i emitted from node k's match state in MSV trace
2299 * ret_kmin - [0.i..L] = k, min node k for residue i
2300 * ret_kmax - [0.i..L] = k, max node k for residue i
2301 * ret_ncells - number of cells within bands, to return
2302 *
2303 * Return: eslOK on success;
2304 *
2305 */
2306 int
2307 p7_Seq2Bands(CM_t *cm, char *errbuf, P7_PROFILE *gm, P7_GMX *gx, P7_BG *bg, P7_TRACE *p7_tr, ESL_DSQ *dsq, int L,
2308 double **phi, float sc7, int len7, int end7, float mprob7, float mcprob7, float iprob7, float ilprob7, int pad7,
2309 int **ret_i2k, int **ret_kmin, int **ret_kmax, int *ret_ncells)
2310 {
2311 int status;
2312 float usc, nullsc;
2313 int *k2i, *i2k;
2314 float *isc;
2315 int *iconflict;
2316 int *kmin, *kmax;
2317 int ncells;
2318
2319 /* setup for all modes */
2320 p7_bg_SetLength(bg, L);
2321 p7_bg_NullOne(bg, dsq, L, &nullsc);
2322
2323 /* generic mode setup */
2324 p7_gmx_GrowTo(gx, cm->mlp7->M, L);
2325 p7_ReconfigLength(gm, L);
2326 gx->M = cm->mlp7->M;
2327 gx->L = L;
2328
2329 /* Step 1: MSV algorithm M->M transitions only
2330 * Step 2: traceback MSV to get pins
2331 * Step 3: prune pins
2332 * Step 4: pins -> bands
2333 */
2334
2335 /* Step 1: MSV algorithm */
2336
2337 /* optimized MSV */
2338 /*
2339 p7_oprofile_ReconfigLength(cm->mlp7_om, L);
2340 esl_stopwatch_Start(watch);
2341 my_p7_MSVFilter(dsq, L, cm->mlp7_om, ox, gx, &usc);
2342 got esl_stopwatch_Stop(watch);
2343 FormatTimeString(time_buf, watch->user, TRUE);
2344 fprintf(stdout, "OMSV %8.2f %11s\n", ((usc -nullsc) / eslCONST_LOG2), time_buf);
2345 */
2346
2347 p7_GMSV(dsq, L, gm, gx, 2.0, &usc);
2348
2349 /* Step 2: traceback MSV */
2350 status = my_p7_GTraceMSV(dsq, L, gm, gx, p7_tr, &i2k, &k2i, &isc, &iconflict);
2351
2352 /* Step 3: prune pins */
2353 if(status == eslOK) { /* trace is valid */
2354 prune_i2k(i2k, iconflict, isc, L, phi, sc7, len7, end7, mprob7, mcprob7, iprob7, ilprob7);
2355 }
2356 else if (status == eslEINCOMPAT) { /* trace was discontiguous, abort! remove all pins */
2357 esl_vec_ISet(k2i, (cm->mlp7->M+1), -1);
2358 esl_vec_ISet(i2k, (L+1), -1);
2359 return status;
2360 }
2361
2362 /* Step 4: pins -> bands */
2363 if((status = p7_pins2bands(i2k, errbuf, L, cm->clen, pad7, &kmin, &kmax, &ncells)) != eslOK) return status;
2364 /*DumpP7Bands(stdout, i2k, kmin, kmax, L); */
2365
2366 /* print gmx in heatmap format */
2367 /*
2368 ESL_DMATRIX *D;
2369 double min;
2370 double max;
2371 FILE *hfp;
2372 p7_gmx_Match2DMatrix(gx, TRUE, &D, &min, &max);
2373 hfp = fopen("cur.ps", "w");
2374 my_dmx_Visualize(hfp, D, 0.01, max, 0.01);
2375 fclose(hfp);
2376 esl_dmatrix_Destroy(D);
2377 */
2378
2379 *ret_i2k = i2k;
2380 *ret_kmin = kmin;
2381 *ret_kmax = kmax;
2382 *ret_ncells = ncells;
2383
2384 free(iconflict);
2385 free(isc);
2386 free(k2i);
2387
2388 return eslOK;
2389 }
2390
2391
2392 /**************************************************************
2393 * Function: CP9NodeForPosnP7B()
2394 * Incept: EPN, Tue Aug 19 14:30:51 2008
2395 *
2396 * Purpose: Given a P7 banded CP9 posterior matrix,
2397 * determine the node of the CP9 HMM that is most likely to
2398 * have emitted (from either its Match or Insert state)
2399 * a given posn in the target sequence.
2400 *
2401 * Args: hmm - the CM plan 9 HMM
2402 * errbuf - for error messages
2403 * x - posn of target subsequence we're interested in
2404 * L - last position of target sequence
2405 * post - the posterior matrix for the hmm
2406 * kn - min node k for residue x
2407 * kx - max node k for residue x
2408 * ret_node - RETURN: index of node with highest probability of emitting x
2409 * ret_type - RETURN: type of state in ret_node with highest probability
2410 * print_flag- TRUE to print out info on most likely node
2411 *
2412 *
2413 * Returns: eslOK on success;
2414 * eslEINVAL on contract violation.
2415 * eslEINCOMPAT if kmin[x] >=
2416 */
2417 int
2418 CP9NodeForPosnP7B(CP9_t *hmm, char *errbuf, int x, CP9_MX *post,
2419 int kn, int kx, int *ret_node, int *ret_type, int print_flag)
2420 {
2421 /* post->mmx[i][kp]: posterior probability that posn i was emitted from node k's
2422 match state, k = kp + kmin[i] */
2423 int max_k; /* node index with highest posterior probability of emitting posn x */
2424 int max_type; /* type of state in max_k node with max probability '0' for match,
2425 '1' for insert */
2426 int max_sc; /* score (log probability) from post matrix for max_k node max_type state type */
2427 int k; /* counter over nodes */
2428 int kp; /* k': k offset in position x's band */
2429
2430 if(kn > kx) ESL_FAIL(eslEINVAL, errbuf, "ERROR in CP9NodeForPosn(), kn (%d) > kx (%d)\n", kn, kx);
2431
2432 kp = 0;
2433 k = kn;
2434 if(post->mmx[x][0] > post->imx[x][0]) {
2435 max_sc = post->mmx[x][0];
2436 max_type = 0; /* match */
2437 }
2438 else {
2439 max_sc = post->imx[x][0];
2440 max_type = 1; /* insert */
2441 }
2442 max_k = k;
2443
2444 /* move left to right through HMM nodes */
2445 for(k = kn+1, kp = 1; k <= kx; k++, kp++) {
2446 if(post->mmx[x][kp] > max_sc) {
2447 max_k = k;
2448 max_sc = post->mmx[x][kp];
2449 max_type = 0; /* match */
2450 }
2451 if(post->imx[x][kp] > max_sc) {
2452 max_k = k;
2453 max_sc = post->imx[x][kp];
2454 max_type = 1; /* insert */
2455 }
2456 }
2457
2458 if(print_flag) {
2459 if(max_type == 0) printf("MATCH | mx->mmx[%3d][%3d]: %9d | %8f\n", x, max_k, post->mmx[x][max_k-kn], Score2Prob(post->mmx[x][max_k-kn], 1.));
2460 else printf("INSERT | mx->imx[%3d][%3d]: %9d | %8f\n", x, max_k, post->imx[x][max_k-kn], Score2Prob(post->imx[x][max_k-kn], 1.));
2461 }
2462 *ret_node = max_k;
2463 *ret_type = max_type;
2464 return eslOK;
2465 }
2466
2467 /* Function: P7BandsAdjustForSubCM()
2468 * Incept: EPN, Tue Aug 19 14:47:55 2008
2469 *
2470 * Purpose: Correct k bands kmin, kmax built from an original CM for it's sub CM model
2471 * that models spos..epos.
2472 *
2473 * Args: kmin - [0.i..L] = k, min node k for residue i
2474 * kmax - [0.i..L] = k, max node k for residue i
2475 * L - length of current sequence
2476 * spos - min k valid in sub CM
2477 * epos - max k valid in sub CM
2478 *
2479 * Return: <eslOK> on success.
2480 *
2481 */
2482 int
2483 P7BandsAdjustForSubCM(int *kmin, int *kmax, int L, int spos, int epos)
2484 {
2485 int i;
2486 int M = epos - spos + 1;
2487 for(i = 0; i <= L; i++) {
2488 kmin[i] = ESL_MAX(kmin[i] - (spos-1), 0);
2489 kmin[i] = ESL_MIN(kmin[i], M);
2490
2491 kmax[i] = ESL_MAX(kmax[i] - (spos-1), 0);
2492 kmax[i] = ESL_MIN(kmax[i], M);
2493 }
2494 kmin[0] = 0; /* hard-coded, M_0 is begin state, it must emit full sequence */
2495
2496 return eslOK;
2497 }