Debian Codegraph @

src/cm_dpalign.c

raw symbols SCIP
1 /* cm_dpalign.c
2 *
3 * DP functions for standard (non-truncated) HMM banded and
4 * non-banded, non-D&C CM alignment of a full target sequence.
5 *
6 * All functions use a DP matrix and or shadow matrix, either
7 * non-banded (CM_MX, CM_SHADOW_MX) or HMM banded (CM_HB_MX,
8 * CM_HB_SHADOW_MX). The HMM banded matrices only have cells within
9 * bands allocated. The bands derived from a HMM Forward/Backward
10 * alignment of the target sequence and are stored in a CP9Bands_t
11 * object, a pointer to which must exist in the cm (CM_t object).
12 *
13 * The non-banded, non-D&C alignment functions are mainly useful for
14 * understanding and/or debugging the HMM banded versions. These are
15 * consistent (same logic/code organization) with their HMM banded
16 * counterparts. They are memory intensive. For small memory
17 * non-banded alignment functions see cm_dpsmall.c. For truncated
18 * alignment functions (both non-banded and HMM banded) see
19 * cm_dpalign_trunc.c.
20 *
21 * List of functions:
22 * non-banded version HMM banded version
23 * ----------------------- ------------------------
24 * cm_alignT() cm_alignT_hb()
25 * cm_AlignSizeNeeded() cm_AlignSizeNeededHB()
26 * cm_Align() cm_AlignHB()
27 * cm_CYKInsideAlign() cm_CYKInsideAlignHB()
28 * cm_InsideAlign() cm_InsideAlignHB()
29 * cm_OptAccAlign() cm_OptAccAlignHB()
30 * cm_CYKOutsideAlign()* cm_CYKOutsideAlignHB()*
31 * cm_OutsideAlign() cm_OutsideAlignHB()
32 * cm_Posterior() cm_PosteriorHB()
33 *
34 * * cm_CYKOutsideAlign() and cm_CYKOutsideAlignHB() are for reference
35 * and debugging only they're not called by any of the main Infernal
36 * programs, only by test programs.
37 *
38 * EPN, Wed Sep 14 05:31:02 2011 Note: post version 1.0.2, the
39 * 'Fast'/'fast_' prefix was dropped from many of these functions and
40 * the cm_ prefix was added. Also 'optimal_accuracy' was shortened to
41 * 'optacc'. At the same time, CM_MX and CM_SHADOW_MX data structures
42 * were introduced to replace the multidimensional float/void arrays
43 * previously used in the non-banded functions.
44 *
45 * EPN, Thu Sep 29 10:01:48 2011 Note: post version 1.0.2, all
46 * functions were simplified to take the target sequence length L
47 * instead of start and end positions i0 and j0. Now, i0 is implicitly
48 * 1 and j0 is implicitly L. To align a subsequence i..j of a larger
49 * sequence the caller need only pass dsq+i as dsq and j-i+1 as L.
50 * The old method of passing i0 and j0 is leftover from the D&C
51 * functions in cm_dpsmall.c upon which many of the functions here
52 * were based.
53 *
54 * EPN, Thu Sep 29 10:44:19 2011
55 */
56
57 #include <esl_config.h>
58 #include <p7_config.h>
59 #include "config.h"
60
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <assert.h>
64 #include <math.h>
65
66 #include "easel.h"
67 #include "esl_sqio.h"
68 #include "esl_stack.h"
69 #include "esl_stopwatch.h"
70 #include "esl_vectorops.h"
71
72 #include "hmmer.h"
73
74 #include "infernal.h"
75
76 static int cm_alignT (CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc, CM_MX *mx, CM_SHADOW_MX *shmx, CM_EMIT_MX *emit_mx, Parsetree_t **ret_tr, float *ret_sc_or_pp);
77 static int cm_alignT_hb(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc, CM_HB_MX *mx, CM_HB_SHADOW_MX *shmx, CM_HB_EMIT_MX *emit_mx, Parsetree_t **ret_tr, float *ret_sc_or_pp);
78
79
80 /* Function: cm_alignT()
81 * Date: EPN, Sun Nov 18 19:21:30 2007
82 *
83 * Note: Based on insideT() [SRE, Fri Aug 11 12:08:18 2000 [Pittsburgh]]
84 * Renamed from fast_alignT() [EPN, Wed Sep 14 06:04:39 2011].
85 *
86 * Purpose: Call either cm_CYKInsideAlign() (if !<do_optacc>),
87 * or cm_OptAccAlign() (if <do_optacc>),
88 * get vjd shadow matrix; then trace back and
89 * append to an existing but empty parsetree tr.
90 * The full sequence 1..L will be aligned.
91 *
92 * If (<do_optacc>) then emit_mx must != NULL.
93 *
94 * Very similar to cm_dpsmall.c:insideT() in case of
95 * CYK alignment, but uses more efficient implementation
96 * of CYK alignment (cm_CYKInsideAlign()) as opposed to
97 * inside()).
98 *
99 * Args: cm - the model
100 * errbuf - char buffer for reporting errors
101 * dsq - the digitized sequence [1..L]
102 * L - length of the dsq to align
103 * size_limit - max size in Mb for DP matrix
104 * do_optacc - TRUE to align with optimal accuracy, else use CYK
105 * mx - the DP matrix to fill in
106 * shmx - the shadow matrix to fill in
107 * emit_mx - the pre-filled emit matrix, must be non-NULL if do_optacc
108 * ret_tr - RETURN: the optimal parsetree
109 * ret_sc_or_pp - RETURN: optimal score (CYK if !do_optacc, else avg PP of all 1..L residues)
110 *
111 * Returns: <eslOK> on success.
112 * Throws: <eslERANGE> if required DP matrix size exceeds <size_limit>, in
113 * this case, alignment has been aborted, ret_* variables are not valid
114 * <eslEINVAL> on traceback problem: bogus state
115 */
116 int
117 cm_alignT(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc,
118 CM_MX *mx, CM_SHADOW_MX *shmx, CM_EMIT_MX *emit_mx, Parsetree_t **ret_tr, float *ret_sc_or_pp)
119 {
120 int status;
121 Parsetree_t *tr = NULL; /* the parsetree */
122 float sc; /* the score of the CYK alignment */
123 float pp; /* avg pp of all emitted residues in optacc alignment */
124 ESL_STACK *pda; /* stack that tracks bifurc parent of a right start */
125 int v,j,d,i; /* indices for state, j, subseq len */
126 int k; /* subseq len for bifurcs */
127 int y, yoffset; /* child state y, it's offset */
128 int bifparent; /* B_st parent */
129 int b; /* local begin state */
130
131 if(do_optacc) { if((status = cm_OptAccAlign (cm, errbuf, dsq, L, size_limit, mx, shmx, emit_mx, &b, &pp)) != eslOK) return status; }
132 else { if((status = cm_CYKInsideAlign(cm, errbuf, dsq, L, size_limit, mx, shmx, &b, &sc)) != eslOK) return status; };
133
134 /* Create and initialize the parsetree */
135 tr = CreateParsetree(100);
136 InsertTraceNode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0); /* init: attach the root S */
137
138 pda = esl_stack_ICreate();
139 if(pda == NULL) goto ERROR;
140 v = 0;
141 i = 1;
142 j = d = L;
143
144 while (1) {
145 if (cm->sttype[v] == B_st) {
146 k = shmx->kshadow[v][j][d]; /* k = len of right fragment */
147
148 /* Store info about the right fragment that we'll retrieve later:
149 */
150 /* remember the end j */
151 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR; /* remember the end j */
152 if((status = esl_stack_IPush(pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
153 if((status = esl_stack_IPush(pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
154
155 /* Deal with attaching left start state.
156 */
157 j = j-k;
158 d = d-k;
159 i = j-d+1;
160 y = cm->cfirst[v];
161 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
162 v = y;
163 } else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
164 /* We don't trace back from an E or EL. Instead, we're done with the
165 * left branch of the tree, and we try to swing over to the right
166 * branch by popping a right start off the stack and attaching
167 * it. If the stack is empty, then we're done with the
168 * traceback altogether. This is the only way to break the
169 * while (1) loop.
170 */
171 if (esl_stack_IPop(pda, &bifparent) == eslEOD) break;
172 esl_stack_IPop(pda, &d);
173 esl_stack_IPop(pda, &j);
174 v = tr->state[bifparent]; /* recover state index of B */
175 y = cm->cnum[v]; /* find state index of right S */
176 i = j-d+1;
177 /* attach the S to the right */
178 InsertTraceNode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y);
179 v = y;
180 } else {
181 yoffset = shmx->yshadow[v][j][d];
182
183 /*printf("v : %d | r : %d | z : %d | i0 : %d | \n", v, r, z, i0);*/
184 /*printf("\tyoffset : %d\n", yoffset);*/
185 switch (cm->sttype[v]) {
186 case D_st: break;
187 case MP_st: i++; j--; break;
188 case ML_st: i++; break;
189 case MR_st: j--; break;
190 case IL_st: i++; break;
191 case IR_st: j--; break;
192 case S_st: break;
193 default: ESL_FAIL(eslEINVAL, errbuf, "bogus state type in cm_alignT()");
194 }
195 d = j-i+1;
196
197 if (yoffset == USED_EL)
198 { /* a local alignment end */
199 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M);
200 v = cm->M; /* now we're in EL. */
201 }
202 else if (yoffset == USED_LOCAL_BEGIN)
203 { /* local begin; can only happen once, from root */
204 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b);
205 v = b;
206 }
207 else
208 {
209 y = cm->cfirst[v] + yoffset;
210 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
211 v = y;
212 }
213 }
214 }
215 esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
216
217 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
218 if(ret_sc_or_pp != NULL) *ret_sc_or_pp = do_optacc ? pp : sc;
219 return eslOK;
220
221 ERROR:
222 ESL_FAIL(status, errbuf, "out of memory");
223 return status; /* NEVERREACHED */
224 }
225
226
227 /* Function: cm_alignT_hb()
228 * Date: EPN 03.29.06
229 *
230 * Note: Based on insideT() [SRE, Fri Aug 11 12:08:18 2000 [Pittsburgh]]
231 * Renamed from fast_alignT_hb() [EPN, Wed Sep 14 06:00:51 2011].
232 *
233 * Purpose: Call either cm_CYKInsideAlignHB() (if !<do_optacc>), or
234 * cm_OptAccAlignHB() (if <do_optacc>), fill banded vjd
235 * shadow matrix in <shmx>; then trace back. Append the
236 * trace to a given traceback, which already has state 0 at
237 * tr->n-1.
238 *
239 * If (<do_optacc>) then emit_mx must != NULL.
240 *
241 * Args: cm - the model
242 * errbuf - char buffer for reporting errors
243 * dsq - the digitized sequence [1..L]
244 * L - length of the dsq to align
245 * size_limit - max size in Mb for DP matrix
246 * do_optacc - TRUE to align with optimal accuracy, else use CYK
247 * mx - the DP matrix to fill in
248 * shmx - the shadow matrix to fill in
249 * emit_mx - the pre-filled emit matrix, must be non-NULL if do_optacc
250 * ret_tr - RETURN: the optimal parsetree
251 * ret_sc_or_pp - RETURN: optimal score (CYK if !do_optacc, else avg PP of all 1..L residues)
252 *
253 *
254 * Throws: <eslOK> on success
255 * <eslERANGE> if required CM_HB_MX exceeds <size_limit>
256 * <eslEINVAL> on traceback problem: bogus state
257 */
258 int
259 cm_alignT_hb(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc,
260 CM_HB_MX *mx, CM_HB_SHADOW_MX *shmx, CM_HB_EMIT_MX *emit_mx, Parsetree_t **ret_tr, float *ret_sc_or_pp)
261 {
262 int status;
263 Parsetree_t *tr = NULL; /* the parsetree */
264 float sc; /* the score of the CYK alignment */
265 float pp; /* avg pp of all emitted residues in optacc alignment */
266 ESL_STACK *pda; /* stack that tracks bifurc parent of a right start */
267 int v,j,d,i; /* indices for state, j, subseq len */
268 int k; /* subseq len for bifurcs */
269 /*int z;*/ /* state index */
270 int y, yoffset; /* child state y, it's offset */
271 int bifparent; /* B_st parent */
272 int b; /* local begin state */
273 int jp_v; /* j-jmin[v] for current j, and current v */
274 int dp_v; /* d-hdmin[v][jp_v] for current j, current v, current d*/
275 int allow_S_local_end; /* set to true to allow d==0 BEGL_S and BEGR_S local ends if(do_optacc) */
276
277 /* pointers to cp9b data for convenience */
278 CP9Bands_t *cp9b = cm->cp9b;
279 int *jmin = cp9b->jmin;
280 int *jmax = cp9b->jmax;
281 int **hdmin = cp9b->hdmin;
282 int **hdmax = cp9b->hdmax;
283
284 if(do_optacc) { if((status = cm_OptAccAlignHB (cm, errbuf, dsq, L, size_limit, mx, shmx, emit_mx, &b, &pp)) != eslOK) return status; }
285 else { if((status = cm_CYKInsideAlignHB(cm, errbuf, dsq, L, size_limit, mx, shmx, &b, &sc)) != eslOK) return status; }
286
287 /* Create and initialize the parsetree */
288 tr = CreateParsetree(100);
289 InsertTraceNode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0); /* init: attach the root S */
290
291 pda = esl_stack_ICreate();
292 if(pda == NULL) goto ERROR;
293 v = 0;
294 i = 1;
295 j = d = L;
296
297 while (1) {
298 /* special case for HMM banded optimal accuracy, explained below, after the crazy if */
299 if(do_optacc && d == 0 && (cm->stid[v] == BEGL_S || cm->stid[v] == BEGR_S) &&
300 ((j < jmin[v] || j > jmax[v]) || /* j is outside v's j band */
301 (d < hdmin[v][j-jmin[v]] || d > hdmax[v][j-jmin[v]]))) { /* j is within v's j band, but d is outside j's d band */
302 /* special case: doing optimal accuracy and v is a BEGL_S or
303 * BEGR_S and d is 0 and j is outside v's j band or j is within
304 * the band but d is outside j's d band. We allow this case
305 * because although this implies a cell outside the bands, in
306 * optimal accuracy only emissions add to the score and we to
307 * initialize all cells to IMPOSSIBLE. This means when d==0, we
308 * have no way of distinguishing those cells that have been
309 * reset to IMPOSSIBLE because they correspond to a valid cell
310 * (with valid cells in the B deck, BEGL_S and BEGR_S decks) and
311 * those that do not correspond to a valid cell and were never
312 * changed since initialization (i.e. this case). So we allow it
313 * to prevent an out-of-bounds error. We have to catch it though
314 * so we don't try to determine jp_v and dp_v below. We even use
315 * USED_EL here if we're not in local mode. You could argue
316 * either way whether we should or shouldn't allow this (e.g. we
317 * already allow illegal parsetrees in optimal accuracy), but a
318 * big reason I decided to allow it is that it is difficult
319 * implement a way of disallowing it. Plus the goal of optimal
320 * accuracy is to show the alignment that has the maximum
321 * average PP on emitted residues within the bands. By allowing
322 * this, we also consider a few possible alignments that violate
323 * the bands, which I think is okay.
324 */
325 allow_S_local_end = TRUE; /* this sets yoffset to USED_LOCAL_END in the final 'else' of below code block */
326 }
327 else if (cm->sttype[v] != EL_st) { /* normal case, determine jp_v, dp_v, j, d offset values given bands */
328 jp_v = j - jmin[v];
329 dp_v = d - hdmin[v][jp_v];
330 allow_S_local_end = FALSE;
331 assert(j >= jmin[v] && j <= jmax[v]);
332 assert(d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]);
333 ESL_DASSERT1((j >= jmin[v] && j <= jmax[v]));
334 ESL_DASSERT1((d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
335 }
336
337 if (cm->sttype[v] == B_st) {
338 k = shmx->kshadow[v][jp_v][dp_v]; /* k = offset len of right fragment */
339 /*z = cm->cnum[v];*/
340
341 /* Store info about the right fragment that we'll retrieve later:
342 */
343 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR; /* remember the end j */
344 if((status = esl_stack_IPush(pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
345 if((status = esl_stack_IPush(pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
346 /* Deal with attaching left start state.
347 */
348 j = j-k;
349 d = d-k;
350 i = j-d+1;
351 y = cm->cfirst[v];
352 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
353 v = y;
354 }
355 else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
356 /* We don't trace back from an E or EL. Instead, we're done with the
357 * left branch of the tree, and we try to swing over to the right
358 * branch by popping a right start off the stack and attaching
359 * it. If the stack is empty, then we're done with the
360 * traceback altogether. This is the only way to break the
361 * while (1) loop.
362 */
363 if (esl_stack_IPop(pda, &bifparent) == eslEOD) break;
364 esl_stack_IPop(pda, &d);
365 esl_stack_IPop(pda, &j);
366 v = tr->state[bifparent]; /* recover state index of B */
367 y = cm->cnum[v]; /* find state index of right S */
368 i = j-d+1;
369 /* attach the S to the right */
370 InsertTraceNode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y);
371 v = y;
372 }
373 else {
374 /* get yoffset */
375 if (allow_S_local_end) {
376 yoffset = USED_EL;
377 }
378 else {
379 yoffset = shmx->yshadow[v][jp_v][dp_v];
380 }
381 switch (cm->sttype[v]) {
382 case D_st: break;
383 case MP_st: i++; j--; break;
384 case ML_st: i++; break;
385 case MR_st: j--; break;
386 case IL_st: i++; break;
387 case IR_st: j--; break;
388 case S_st: break;
389 default: ESL_FAIL(eslEINVAL, errbuf, "Bogus state type in cm_alignT_hb()");
390 }
391 d = j-i+1;
392
393 if (yoffset == USED_EL)
394 { /* a local alignment end */
395 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M);
396 v = cm->M; /* now we're in EL. */
397 }
398 else if (yoffset == USED_LOCAL_BEGIN)
399 { /* local begin; can only happen once, from root */
400 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b);
401 v = b;
402 }
403 else
404 {
405 y = cm->cfirst[v] + yoffset;
406 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
407 v = y;
408 }
409 /*ParsetreeDump(stdout, tr, cm, dsq);*/
410 }
411 }
412 esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
413
414 /*ParsetreeDump(stdout, tr, cm, dsq);*/
415
416 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
417 if(ret_sc_or_pp != NULL) *ret_sc_or_pp = do_optacc ? pp : sc;
418 return eslOK;
419
420 ERROR:
421 ESL_FAIL(eslEMEM, errbuf, "out of memory");
422 return status; /* NEVERREACHED */
423 }
424
425 /* Function: cm_AlignSizeNeeded()
426 * Date: EPN, Thu Jan 12 09:51:11 2012
427 *
428 * Purpose: Determine size in Mb required to successfully call
429 * cm_Align() for a given model <cm>, sequence length
430 * <L> and alignment options in <do_sample> and <do_post>.
431 *
432 * Return <eslERANGE> if required size exceeds size_limit.
433 *
434 * Args: cm - the covariance model
435 * errbuf - char buffer for reporting errors
436 * L - length of sequence
437 * size_limit - max size in Mb for all required matrices, return eslERANGE if exceeded
438 * do_sample - TRUE to sample a parsetree from the Inside matrix
439 * do_post - TRUE to do posteriors
440 * ret_mxmb - RETURN: size in Mb of required CM_MX (we'll need 2 of these if do_post)
441 * ret_emxmb - RETURN: size in Mb of required CM_EMIT_MX (0. if we won't need one)
442 * ret_shmxmb - RETURN: size in Mb of required CM_SHADOW_MX (0. if we won't need one)
443 * ret_totmb - RETURN: size in Mb of all required matrices
444 *
445 * Returns: <eslOK> on success.
446 *
447 * Throws: <eslEINVAL> on contract violation
448 * <eslERANGE> if total size of all matrices exceeds <size_limit>
449 */
450 int
451 cm_AlignSizeNeeded(CM_t *cm, char *errbuf, int L, float size_limit, int do_sample, int do_post,
452 float *ret_mxmb, float *ret_emxmb, float *ret_shmxmb, float *ret_totmb)
453 {
454 int status;
455 float totmb = 0.; /* total Mb required for all matrices (that must be simultaneously in memory) */
456 float mxmb = 0.; /* Mb required for CM_MX */
457 float emxmb = 0.; /* Mb required for CM_EMIT_MX */
458 float shmxmb = 0.; /* Mb required for CM_SHADOW_MX */
459
460 /* we pass NULL values to the *_mx_SizeNeeded() functions because we don't care about cell counts */
461
462 /* we will always need an Inside or CYK matrix */
463 if((status = cm_mx_SizeNeeded(cm, errbuf, L, NULL, &mxmb)) != eslOK) return status;
464 totmb = mxmb;
465
466 /* if calc'ing posteriors, we'll also need an Outside matrix (which
467 * we'll reuse as the Posterior matrix, so only count it once) and
468 * an emit matrix.
469 */
470 if(do_post) {
471 totmb += mxmb;
472 if((status = cm_emit_mx_SizeNeeded(cm, errbuf, L, NULL, NULL, &emxmb)) != eslOK) return status;
473 totmb += emxmb;
474 }
475
476 /* if we're not sampling an alignment, we'll also need a shadow
477 * matrix for the traceback.
478 */
479 if(! do_sample) { /* if do_sample, we won't need a shadow matrix */
480 if((status = cm_shadow_mx_SizeNeeded(cm, errbuf, L, NULL, NULL, &shmxmb)) != eslOK) return status;
481 totmb += shmxmb;
482 }
483
484 if (ret_mxmb != NULL) *ret_mxmb = mxmb;
485 if (ret_emxmb != NULL) *ret_emxmb = emxmb;
486 if (ret_shmxmb != NULL) *ret_shmxmb = shmxmb;
487 if (ret_totmb != NULL) *ret_totmb = totmb;
488
489 if(totmb > size_limit) ESL_FAIL(eslERANGE, errbuf, "non-banded standard alignment mxes need %.2f Mb > %.2f Mb limit.\nUse --mxsize, --maxtau or --tau.", totmb, (float) size_limit);
490
491 return eslOK;
492 }
493
494 /* Function: cm_AlignSizeNeededHB()
495 * Date: EPN, Thu Jan 12 10:06:20 2012
496 *
497 * Purpose: Determine size in Mb required to successfully call
498 * cm_AlignHB() for a given model <cm>, sequence length
499 * <L>, HMM bands <cm->cp9b> and alignment options
500 * in <do_sample> and <do_post>.
501 *
502 * Return <eslERANGE> if required size exceeds size_limit.
503 *
504 * Args: cm - the covariance model
505 * errbuf - char buffer for reporting errors
506 * L - length of sequence
507 * size_limit - max size in Mb for all required matrices, return eslERANGE if exceeded
508 * do_sample - TRUE to sample a parsetree from the Inside matrix
509 * do_post - TRUE to do posteriors
510 * ret_mxmb - RETURN: size in Mb of required CM_HB_MX (we'll need 2 of these if do_post)
511 * ret_emxmb - RETURN: size in Mb of required CM_HB_EMIT_MX (0. if we won't need one)
512 * ret_shmxmb - RETURN: size in Mb of required CM_HB_SHADOW_MX (0. if we won't need one)
513 * ret_cp9mxmb - RETURN: size in Mb of all CP9 matrices needed (fwd and possibly bck)
514 * ret_cmtotmb - RETURN: size in Mb of all CM matrices (ret_mxmb + ret_emxmb + ret_shmxmb)
515 * ret_totmb - RETURN: size in Mb of all required matrices
516 *
517 * Returns: <eslOK> on success.
518 *
519 * Throws: <eslEINVAL> on contract violation
520 * <eslERANGE> if total size of all matrices exceeds <size_limit>
521 */
522 int
523 cm_AlignSizeNeededHB(CM_t *cm, char *errbuf, int L, float size_limit, int do_sample, int do_post,
524 float *ret_mxmb, float *ret_emxmb, float *ret_shmxmb, float *ret_cp9mxmb,
525 float *ret_cmtotmb, float *ret_totmb)
526 {
527 int status;
528 float totmb = 0.; /* total Mb required for all matrices including cp9 matrices (that must be simultaneously in memory) */
529 float cmtotmb = 0.; /* total Mb required for all CM matrices */
530 float mxmb = 0.; /* Mb required for CM_MX */
531 float emxmb = 0.; /* Mb required for CM_EMIT_MX */
532 float shmxmb = 0.; /* Mb required for CM_SHADOW_MX */
533 float cp9mxmb = 0.; /* Mb required for two CP9_MX */
534
535 /* we pass NULL values to the *_mx_SizeNeeded() functions because we don't care about cell counts */
536
537 /* we will always need an Inside or CYK matrix */
538 if((status = cm_hb_mx_SizeNeeded(cm, errbuf, cm->cp9b, L, NULL, &mxmb)) != eslOK) return status;
539 cmtotmb = mxmb;
540
541 /* if calc'ing posteriors, we'll also need an Outside matrix (which
542 * we'll reuse as the Posterior matrix, so only count it once) and
543 * an emit matrix.
544 */
545 if(do_post) {
546 cmtotmb += mxmb;
547 if((status = cm_hb_emit_mx_SizeNeeded(cm, errbuf, cm->cp9b, L, NULL, NULL, &emxmb)) != eslOK) return status;
548 cmtotmb += emxmb;
549 }
550
551 /* if we're not sampling an alignment, we'll also need a shadow
552 * matrix for the traceback.
553 */
554 if(! do_sample) {
555 if((status = cm_hb_shadow_mx_SizeNeeded(cm, errbuf, cm->cp9b, NULL, NULL, &shmxmb)) != eslOK) return status;
556 cmtotmb += shmxmb;
557 }
558
559 cp9mxmb = SizeNeededCP9Matrix(L, cm->cp9->M, NULL, NULL);
560 cp9mxmb += cp9mxmb; /* add size of bck matrix */
561
562 totmb = cmtotmb + cp9mxmb;
563
564 if (ret_mxmb != NULL) *ret_mxmb = mxmb;
565 if (ret_emxmb != NULL) *ret_emxmb = emxmb;
566 if (ret_shmxmb != NULL) *ret_shmxmb = shmxmb;
567 if (ret_cp9mxmb != NULL) *ret_cp9mxmb = cp9mxmb;
568 if (ret_cmtotmb != NULL) *ret_cmtotmb = cmtotmb;
569 if (ret_totmb != NULL) *ret_totmb = totmb;
570
571 #if eslDEBUGLEVEL >= 1
572 printf("#DEBUG: cm_AlignSizeNeededHB()\n");
573 printf("#DEBUG: \t mxmb: %.2f\n", mxmb);
574 printf("#DEBUG: \t emxmb: %.2f\n", emxmb);
575 printf("#DEBUG: \t shmxmb: %.2f\n", shmxmb);
576 printf("#DEBUG: \t cp9mxmb: %.2f\n", cp9mxmb);
577 printf("#DEBUG: \t cmtotmb: %.2f\n", cmtotmb);
578 printf("#DEBUG: \t totmb: %.2f\n", totmb);
579 printf("#DEBUG: \t limit: %.2f\n", size_limit);
580 #endif
581
582 if(cmtotmb > size_limit) ESL_FAIL(eslERANGE, errbuf, "HMM banded std DP mxes need %.1f>%.1f Mb limit (HMM mxes need an extra %.1f Mb).\nUse --mxsize, --maxtau or --tau.", cmtotmb, (float) size_limit, cp9mxmb);
583
584 return eslOK;
585 }
586
587 /* Function: cm_Align()
588 * Date: EPN, Sun Nov 18 19:26:45 2007
589 *
590 * Note: Very similar to cm_dpsmall.c:CYKInside() for case
591 * of CYK alignment, but uses slightly more efficient
592 * implementation (cm_CYKInsideAlign() instead of inside()).
593 * Renamed from FastAlign() [EPN, Wed Sep 14 06:12:46 2011].
594 *
595 * Purpose: Wrapper for the cm_alignT() routine - solve a full
596 * alignment problem either by CYK, using optimal accuracy,
597 * or sampling, and return the traceback and the score,
598 * without dividing & conquering. Optionally return a
599 * posterior code string.
600 *
601 * Input arguments allow this function to be run in 6 'modes':
602 *
603 * mode returns arguments
604 * ---- --------------- ----------------------------------------
605 * tr ppstr do_optacc do_sample post_mx ret_ppstr
606 * --------------- ----------------------------------------
607 * 1. CYK no FALSE FALSE NULL NULL
608 * 2. CYK yes FALSE FALSE !NULL !NULL
609 * 3. Opt acc no TRUE FALSE !NULL NULL
610 * 4. Opt acc yes TRUE FALSE !NULL !NULL
611 * 5. sampled no FALSE TRUE NULL NULL
612 * 6. sampled yes FALSE TRUE !NULL !NULL
613 *
614 * CYK parsetrees are most the likely parsetree, 'Opt acc'
615 * parsetrees are Holmes/Durbin optimally accurate
616 * parsetrees, the parse that maximizes the summed posterior
617 * probability of emitted residues. A sampled parsetree
618 * is a parsetree sampled from an Inside matrix based on
619 * it's probability.
620 *
621 * Args: cm - the covariance model
622 * errbuf - char buffer for reporting errors
623 * dsq - the digitized sequence, 1..L
624 * L - length of sequence
625 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
626 * do_optacc - TRUE: do optimal accuracy alignment, not CYK, requires post_mx != NULL
627 * do_sample - TRUE to sample a parsetree from the Inside matrix
628 * mx - the main dp matrix, grown and filled here, must be non-NULL
629 * shmx - the shadow matrix, grown and filled here
630 * post_mx - dp matrix for posterior calculation, grown and filled here, can be NULL only if !do_optacc
631 * emit_mx - emit matrix to fill
632 * r - source of randomness, must be non-NULL only if do_sample==TRUE
633 * ret_ppstr - RETURN: posterior code 1, (pass NULL if not wanted, must be NULL if post_mx == NULL)
634 * ret_tr - RETURN: traceback (pass NULL if trace isn't wanted)
635 * ret_avgpp - RETURN: avg PP of emitted residues in parsetree (CYK or optacc) if ret_ppstr == NULL, set as 0.
636 * ret_sc - RETURN: score of the alignment in bits (Inside score if do_optacc)
637 *
638 * Returns: <eslOK> on success.
639 *
640 * Throws: <eslEINVAL> on contract violation
641 * <eslERANGE> if required CM_MX for Inside/Outside/CYK/Posterior exceeds <size_limit>
642 */
643 int
644 cm_Align(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc, int do_sample,
645 CM_MX *mx, CM_SHADOW_MX *shmx, CM_MX *post_mx, CM_EMIT_MX *emit_mx, ESL_RANDOMNESS *r,
646 char **ret_ppstr, Parsetree_t **ret_tr, float *ret_avgpp, float *ret_sc)
647 {
648 int status;
649 Parsetree_t *tr = NULL;
650 float sc = 0.;
651 float avgpp = 0.;
652 float ins_sc = 0.;
653 int do_post;
654 char *ppstr = NULL;
655 int have_ppstr;
656
657 have_ppstr = (ret_ppstr != NULL) ? TRUE : FALSE;
658 do_post = (do_optacc || have_ppstr) ? TRUE : FALSE;
659
660 /* Contract check */
661 if(do_optacc && do_sample) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_Align(), do_optacc and do_sample are both TRUE.");
662 if(do_optacc && post_mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_Align(), do_optacc is TRUE, but post_mx == NULL.\n");
663 if(do_sample && r == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_Align(), do_sample but r is NULL.");
664
665 /* if do_post: fill Inside, Outside, Posterior matrices, in that order.
666 * if do_sample: fill Inside and sample from it.
667 */
668 if(do_post || do_sample) {
669 if((status = cm_InsideAlign (cm, errbuf, dsq, L, size_limit, mx, &ins_sc)) != eslOK) return status;
670 if(do_sample) {
671 if((status = cm_StochasticParsetree(cm, errbuf, dsq, L, mx, r, &tr, &sc)) != eslOK) return status;
672 }
673 if(do_post) { /* Inside was called above, now do Outside, then Posterior */
674 if((status = cm_OutsideAlign(cm, errbuf, dsq, L, size_limit, ((cm->align_opts & CM_ALIGN_CHECKINOUT) && (! (cm->flags & CMH_LOCAL_END))), post_mx, mx, NULL)) != eslOK) return status;
675 /* Note: we can only check the posteriors in cm_OutsideAlign() if local begin/ends are off */
676 if((status = cm_Posterior (cm, errbuf, L, size_limit, mx, post_mx, post_mx)) != eslOK) return status;
677 if((status = cm_EmitterPosterior(cm, errbuf, L, size_limit, post_mx, emit_mx, (cm->align_opts & CM_ALIGN_CHECKINOUT))) != eslOK) return status;
678 }
679 }
680
681 if(!do_sample) { /* if do_sample, we already have a parsetree */
682 if((status = cm_alignT(cm, errbuf, dsq, L, size_limit, do_optacc, mx, shmx, emit_mx, &tr, (do_optacc) ? NULL : &sc)) != eslOK) return status;
683 }
684
685 if(have_ppstr || do_optacc) { /* call cm_PostCode to get average PP and optionally a PP string (if have_ppstr) */
686 if((status = cm_PostCode(cm, errbuf, L, emit_mx, tr, (have_ppstr) ? &ppstr : NULL, &avgpp)) != eslOK) return status;
687 }
688
689 if (ret_ppstr != NULL) *ret_ppstr = ppstr; else free(ppstr);
690 if (ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
691 if (ret_avgpp != NULL) *ret_avgpp = avgpp;
692 if (ret_sc != NULL) *ret_sc = (do_optacc) ? ins_sc : sc;
693
694 ESL_DPRINTF1(("#DEBUG: returning from cm_Align() sc : %f\n", sc));
695 return eslOK;
696 }
697
698
699
700 /* Function: cm_AlignHB()
701 * Incept: EPN, Fri Oct 26 09:31:43 2007
702 *
703 * Note: Based on CYKInside_b_jd() [11.04.05] which was based on CYKInside_b()
704 * which was based on CYKInside() [SRE, Sun Jun 3 19:48:33 2001 [St. Louis]]
705 * Renamed from cm_AlignHB() [EPN, Wed Sep 14 06:09:51 2011].
706 *
707 * Purpose: Wrapper for the cm_alignT() routine - solve a full
708 * alignment problem either by CYK, using optimal accuracy,
709 * or sampling, and return the traceback and the score,
710 * without dividing & conquering. Optionally return a
711 * posterior code string.
712 *
713 * Identical to cm_Align() but HMM bands are used here.
714 * See that function's 'Purpose' for more details.
715 *
716 * Args: cm - the covariance model
717 * errbuf - char buffer for reporting errors
718 * dsq - the digitized sequence, 1..L
719 * L - length of sequence
720 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
721 * do_optacc - TRUE: do optimal accuracy alignment, not CYK, requires post_mx != NULL
722 * do_sample - TRUE: sample a parsetree from the Inside matrix
723 * mx - the main dp matrix, grown and filled here, must be non-NULL
724 * shmx - the shadow matrix, grown and filled here
725 * post_mx - dp matrix for posterior calculation, grown and filled here, can be NULL only if !do_optacc
726 * emit_mx - emit matrix to fill
727 * r - source of randomness, must be non-NULL only if do_sample==TRUE
728 * ret_ppstr - RETURN: posterior code 1, (pass NULL if not wanted, must be NULL if post_mx == NULL)
729 * ret_tr - RETURN: traceback (pass NULL if trace isn't wanted)
730 * ret_avgpp - RETURN: avg PP of emitted residues in parsetree (CYK or optacc) if ret_ppstr == NULL, set as 0.
731 * ret_sc - RETURN: score of the alignment in bits (Inside score if do_optacc)
732 *
733 * Returns: <eslOK> on success
734 *
735 * Throws: <eslEINVAL> on contract violation
736 * <eslERANGE> if required CM_HB_MX for Inside/Outside/CYK/Posterior exceeds <size_limit>
737 */
738
739 int
740 cm_AlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_optacc, int do_sample,
741 CM_HB_MX *mx, CM_HB_SHADOW_MX *shmx, CM_HB_MX *post_mx, CM_HB_EMIT_MX *emit_mx, ESL_RANDOMNESS *r,
742 char **ret_ppstr, Parsetree_t **ret_tr, float *ret_avgpp, float *ret_sc)
743 {
744 int status;
745 Parsetree_t *tr = NULL;
746 float sc = 0.;
747 float avgpp = 0.;
748 float ins_sc = 0.;
749 int do_post;
750 char *ppstr = NULL;
751 int have_ppstr;
752
753 have_ppstr = (ret_ppstr != NULL) ? TRUE : FALSE;
754 do_post = (do_optacc || have_ppstr) ? TRUE : FALSE;
755
756 /* Contract check */
757 if(do_optacc && do_sample) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_AlignHB(), do_optacc and do_sample are both TRUE.");
758 if(do_optacc && post_mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_AlignHB(), do_optacc is TRUE, but post_mx == NULL.\n");
759 if(do_sample && r == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_AlignHB(), do_sample but r is NULL.");
760
761 /* PrintDPCellsSaved_jd(cm, cm->cp9b->jmin, cm->cp9b->jmax, cm->cp9b->hdmin, cm->cp9b->hdmax, L); */
762
763 /* if do_post: fill Inside, Outside, Posterior matrices, in that order.
764 * if do_sample: fill Inside and sample from it.
765 */
766 if(do_post || do_sample) {
767 if((status = cm_InsideAlignHB (cm, errbuf, dsq, L, size_limit, mx, &ins_sc)) != eslOK) return status;
768 if(do_sample) {
769 if((status = cm_StochasticParsetreeHB(cm, errbuf, dsq, L, mx, r, &tr, &sc)) != eslOK) return status;
770 }
771 if(do_post) { /* Inside was called above, now do Outside, then Posterior */
772 if((status = cm_OutsideAlignHB(cm, errbuf, dsq, L, size_limit, ((cm->align_opts & CM_ALIGN_CHECKINOUT) && (! (cm->flags & CMH_LOCAL_END))), post_mx, mx, NULL)) != eslOK) return status;
773 /* Note: we can only check the posteriors in cm_OutsideAlignHB() if local begin/ends are off */
774 if((status = cm_PosteriorHB (cm, errbuf, L, size_limit, mx, post_mx, post_mx)) != eslOK) return status;
775 if((status = cm_EmitterPosteriorHB(cm, errbuf, L, size_limit, post_mx, emit_mx, (cm->align_opts & CM_ALIGN_CHECKINOUT))) != eslOK) return status;
776 }
777 }
778
779 if(!do_sample) { /* if do_sample, we already have a parsetree */
780 if((status = cm_alignT_hb(cm, errbuf, dsq, L, size_limit, do_optacc, mx, shmx, emit_mx, &tr, (do_optacc) ? NULL : &sc)) != eslOK) return status;
781 }
782
783 if(have_ppstr || do_optacc) {
784 if((status = cm_PostCodeHB(cm, errbuf, L, emit_mx, tr, (have_ppstr) ? &ppstr : NULL, &avgpp)) != eslOK) return status;
785 }
786
787 /* Uncomment to dump emit map and parse tree */
788 /* CMEmitMap_t *emap;
789 emap = CreateEmitMap(cm);
790 DumpEmitMap(stdout, emap, cm);
791 FreeEmitMap(emap);
792 ParsetreeDump(stdout, tr, cm, dsq);
793 */
794
795 if (ret_ppstr != NULL) *ret_ppstr = ppstr; else free(ppstr);
796 if (ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
797 if (ret_avgpp != NULL) *ret_avgpp = avgpp;
798 if (ret_sc != NULL) *ret_sc = (do_optacc) ? ins_sc : sc;
799
800 ESL_DPRINTF1(("#DEBUG: returning from cm_AlignHB() sc : %f\n", sc));
801 return eslOK;
802 }
803
804 /* Function: cm_CYKInsideAlign()
805 * Date: EPN, Sun Nov 18 19:37:39 2007
806 *
807 * Purpose: Run the inside phase of a CYK alignment. Non-banded
808 * version. See cm_CYKInsideAlignHB() for HMM banded version.
809 *
810 * This function must perform a complete alignment, aligning
811 * the full sequence 1..L to the ROOT_S state 0 of the model.
812 *
813 * We deal with local begins by keeping track of the optimal
814 * state that we could enter and account for the whole target
815 * sequence: b = argmax_v alpha_v(1,L) + log t_0(v),
816 * and bsc is the score for that.
817 *
818 * If local begins are on (cm->flags & CMH_LOCAL_BEGIN), the
819 * optimal alignment must use a local begin transition,
820 * 0->b, and we have to be able to trace that back. If local
821 * begins are on, we return a valid b (the optimal 0->b
822 * choice), yshad[0][L][L] will be USE_LOCAL_BEGIN, telling
823 * cm_alignT() to check b and start with a local 0->b entry
824 * transition.
825 *
826 * Note on history of this function: It was previously
827 * fast_cyk_align() (up to Infernal 1.0.2), which was
828 * based on inside() from cm_dpsmall.c.
829 *
830 * Args: cm - the model
831 * errbuf - char buffer for reporting errors
832 * dsq - the digitized sequence [1..L]
833 * L - length of the dsq to align
834 * size_limit- max size in Mb for DP matrix
835 * mx - the DP matrix to fill in
836 * shmx - the shadow matrix to fill in
837 * ret_b - RETURN: local begin state if local begins are on
838 * ret_sc - RETURN: score of optimal, CYK parsetree
839 *
840 * Returns: <eslOK> on success.
841 *
842 * Throws: <eslERANGE> if required mx or shmx size exceeds <size_limit>
843 * In this case alignment has been aborted, <ret_*> variables are not valid
844 */
845 int
846 cm_CYKInsideAlign(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit,
847 CM_MX *mx, CM_SHADOW_MX *shmx, int *ret_b, float *ret_sc)
848 {
849 int status;
850 int v,y,z; /* indices for states */
851 int j,d,i,k; /* indices in sequence dimensions */
852 float sc; /* a temporary variable holding a score */
853 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
854 int b; /* best local begin state */
855 float bsc; /* score for using the best local begin state */
856 float *el_scA; /* [0..d..W-1] probability of local end emissions of length d */
857 int sd; /* StateDelta(cm->sttype[v]) */
858 int sdr; /* StateRightDelta(cm->sttype[v] */
859 int j_sdr; /* j - sdr */
860 int d_sd; /* d - sd */
861 float tsc; /* a transition score */
862 int64_t c; /* 64-bit int counter */
863
864 /* the DP matrix */
865 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
866 char ***yshadow = shmx->yshadow; /* pointer to the yshadow matrix */
867 int ***kshadow = shmx->kshadow; /* pointer to the kshadow matrix */
868
869 /* Allocations and initializations */
870 b = -1;
871 bsc = IMPOSSIBLE;
872
873 /* grow the matrices based on the current sequence */
874 if((status = cm_mx_GrowTo (cm, mx, errbuf, L, size_limit)) != eslOK) return status;
875 if((status = cm_shadow_mx_GrowTo(cm, shmx, errbuf, L, size_limit)) != eslOK) return status;
876
877 /* initialize all cells of the matrix to IMPOSSIBLE, all cells of shadow matrix to USED_EL */
878 esl_vec_FSet(mx->dp_mem, mx->ncells_valid, IMPOSSIBLE);
879 for(c = 0; c < shmx->y_ncells_valid; c++) shmx->yshadow_mem[c] = USED_EL;
880 esl_vec_ISet(shmx->kshadow_mem, shmx->k_ncells_valid, USED_EL);
881
882 /* precalcuate all possible local end scores, for local end emits of 1..L residues */
883 ESL_ALLOC(el_scA, sizeof(float) * (L+1));
884 for(d = 0; d <= L; d++) el_scA[d] = cm->el_selfsc * d;
885
886 /* if local ends are on, replace the EL deck IMPOSSIBLEs with EL scores */
887 if(cm->flags & CMH_LOCAL_END) {
888 for (j = 0; j <= L; j++) {
889 for (d = 0; d <= j; d++) alpha[cm->M][j][d] = el_scA[d];
890 }
891 }
892
893 /* Main recursion */
894 for (v = cm->M-1; v >= 0; v--) {
895 float const *esc_v = cm->oesc[v]; /* emission scores for state v */
896 float const *tsc_v = cm->tsc[v]; /* transition scores for state v */
897 sd = StateDelta(cm->sttype[v]);
898 sdr = StateRightDelta(cm->sttype[v]);
899
900 /* re-initialize the J deck if we can do a local end from v */
901 if(NOT_IMPOSSIBLE(cm->endsc[v])) {
902 for (j = 0; j <= L; j++) {
903 for (d = sd; d <= j; d++) {
904 alpha[v][j][d] = el_scA[d-sd] + cm->endsc[v];
905 }
906 }
907 }
908 /* otherwise this state's deck has already been initialized to IMPOSSIBLE */
909
910 if(cm->sttype[v] == E_st) {
911 for (j = 0; j <= L; j++) {
912 alpha[v][j][0] = 0.;
913 /* rest of deck remains IMPOSSIBLE */
914 }
915 }
916 else if(cm->sttype[v] == IL_st) {
917 /* update alpha[v][j][d] cells, for IL states, loop nesting order is:
918 * for j { for d { for y { } } } because they can self transit, and a
919 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
920 * before can start calc'ing for alpha[v][j][d+1] */
921 for (j = sdr; j <= L; j++) {
922 j_sdr = j - sdr;
923 for (d = sd; d <= j; d++) {
924 d_sd = d - sd;
925 i = j - d + 1;
926 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
927 y = cm->cfirst[v] + yoffset;
928 if ((sc = alpha[y][j_sdr][d_sd] + tsc_v[yoffset]) > alpha[v][j][d]) {
929 alpha[v][j][d] = sc;
930 yshadow[v][j][d] = yoffset;
931 }
932 }
933 alpha[v][j][d] += esc_v[dsq[i--]];
934 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
935 }
936 }
937 }
938 else if(cm->sttype[v] == IR_st) {
939 /* update alpha[v][j][d] cells, for IR states, loop nesting order is:
940 * for j { for d { for y { } } } because they can self transit, and a
941 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
942 * before can start calc'ing for alpha[v][j][d+1] */
943 for (j = sdr; j <= L; j++) {
944 j_sdr = j - sdr;
945 for (d = sd; d <= j; d++) {
946 d_sd = d - sd;
947 i = j - d + 1;
948 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
949 y = cm->cfirst[v] + yoffset;
950 if ((sc = alpha[y][j_sdr][d_sd] + tsc_v[yoffset]) > alpha[v][j][d]) {
951 alpha[v][j][d] = sc;
952 yshadow[v][j][d] = yoffset;
953 }
954 }
955 alpha[v][j][d] += esc_v[dsq[j]];
956 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
957 }
958 }
959 }
960 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
961 /* ML, MP, MR, D, S, E states cannot self transit, this means that all cells
962 * in alpha[v] are independent of each other, only depending on alpha[y] for previously calc'ed y.
963 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
964 * for y { for j { for d { } } }
965 */
966 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
967 yoffset = y - cm->cfirst[v];
968 tsc = tsc_v[yoffset];
969
970 for (j = sdr; j <= L; j++) {
971 j_sdr = j - sdr;
972
973 for (d = sd; d <= j; d++) {
974 if((sc = alpha[y][j_sdr][d - sd] + tsc) > alpha[v][j][d]) {
975 alpha[v][j][d] = sc;
976 yshadow[v][j][d] = yoffset;
977 }
978 }
979 }
980 }
981 /* add in emission score, if any */
982 switch(cm->sttype[v]) {
983 case ML_st:
984 for (j = 0; j <= L; j++) {
985 i = j - 1;
986 for (d = sd; d <= j; d++)
987 alpha[v][j][d] += esc_v[dsq[j-d+1]];
988 }
989 break;
990 case MR_st:
991 for (j = 0; j <= L; j++) {
992 for (d = sd; d <= j; d++)
993 alpha[v][j][d] += esc_v[dsq[j]];
994 }
995 break;
996 case MP_st:
997 for (j = 0; j <= L; j++) {
998 i = j - 1;
999 for (d = sd; d <= j; d++)
1000 alpha[v][j][d] += esc_v[dsq[i--]*cm->abc->Kp+dsq[j]];
1001 }
1002 default:
1003 break;
1004 }
1005 /* ensure all cells are >= IMPOSSIBLE */
1006 for (j = 0; j <= L; j++) {
1007 for (d = 0; d <= j; d++)
1008 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
1009 }
1010 }
1011 else { /* B_st */
1012 y = cm->cfirst[v]; /* left subtree */
1013 z = cm->cnum[v]; /* right subtree */
1014
1015 for (j = 0; j <= L; j++) {
1016 for (d = 0; d <= j; d++) {
1017 for (k = 0; k <= d; k++) {
1018 if ((sc = alpha[y][j-k][d-k] + alpha[z][j][k]) > alpha[v][j][d]) {
1019 alpha[v][j][d] = sc;
1020 kshadow[v][j][d] = k;
1021 }
1022 }
1023 }
1024 }
1025 }
1026
1027 /* allow local begins, if nec */
1028 if ((cm->flags & CMH_LOCAL_BEGIN) &&
1029 (NOT_IMPOSSIBLE(cm->beginsc[v])) &&
1030 (alpha[v][L][L] + cm->beginsc[v] > bsc)) {
1031 b = v;
1032 bsc = alpha[v][L][L] + cm->beginsc[v];
1033 }
1034 } /* finished calculating deck v. */
1035
1036 /* Check for whether we need to store an optimal local begin score
1037 * as the optimal overall score, and if we need to put a flag
1038 * in the shadow matrix telling cm_alignT() to use the b we return.
1039 */
1040 if (bsc > alpha[0][L][L]) {
1041 alpha[0][L][L] = bsc;
1042 yshadow[0][L][L] = USED_LOCAL_BEGIN;
1043 }
1044
1045 #if eslDEBUGLEVEL >= 3
1046 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
1047 /* FILE *fp1; fp1 = fopen("tmp.std_cykmx", "w"); cm_mx_Dump(fp1, mx); fclose(fp1); */
1048 /* FILE *fp2; fp2 = fopen("tmp.std_cykshmx", "w"); cm_shadow_mx_Dump(fp2, cm, shmx); fclose(fp2); */
1049 #endif
1050
1051 sc = alpha[0][L][L];
1052
1053 free(el_scA);
1054
1055 if (ret_b != NULL) *ret_b = b; /* b is -1 if local begins are off */
1056 if (ret_sc != NULL) *ret_sc = sc;
1057
1058 ESL_DPRINTF1(("#DEBUG: cm_CYKInsideAlign return sc: %f\n", sc));
1059 return eslOK;
1060
1061 ERROR:
1062 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
1063 }
1064
1065 /* Function: cm_CYKInsideAlignHB()
1066 * Date: EPN 03.29.06 [EPN started]
1067 * SRE, Mon Aug 7 13:15:37 2000 [St. Louis]
1068 *
1069 * Purpose: Run the inside phase of a CYK alignment using bands
1070 * in the j and d dimensions of the DP matrix. Bands
1071 * were obtained from an HMM Forward-Backward parse
1072 * of the target sequence. Uses float log odds scores.
1073 * Otherwise, (meant to be) identical to cm_CYKInsideAlign()
1074 * see that function for more information.
1075 *
1076 * A CM_HB_MX DP matrix must be passed in. Only cells valid
1077 * within the bands given in the CP9Bands_t <cm->cp9b> will
1078 * be valid.
1079 *
1080 * Note on history of this function: It was previously
1081 * fast_cyk_align_hb() (up to Infernal 1.0.2), which was
1082 * based on inside_b_me() which was based on inside().
1083 *
1084 * Args: cm - the model
1085 * errbuf - char buffer for reporting errors
1086 * dsq - the digitized sequence [1..L]
1087 * L - length of the dsq to align
1088 * size_limit- max size in Mb for DP matrix
1089 * mx - the DP matrix to fill in, only cells within bands are valid
1090 * shmx - the shadow matrix to fill in, only cells within bands are valid
1091 * ret_b - RETURN: best local begin state, or NULL if unwanted
1092 * ret_sc - RETURN: score of optimal, CYK parsetree
1093 *
1094 * Returns: <eslOK> on success.
1095 *
1096 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
1097 * <eslEINVAL> if the full sequence is not within the bands for state 0
1098 * In either case alignment has been aborted, ret_* variables are not valid
1099 *
1100 */
1101 int
1102 cm_CYKInsideAlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit,
1103 CM_HB_MX *mx, CM_HB_SHADOW_MX *shmx, int *ret_b, float *ret_sc)
1104 {
1105 int status;
1106 int v,y,z; /* indices for states */
1107 int j,d,i,k; /* indices in sequence dimensions */
1108 float sc; /* a temporary variable holding a score */
1109 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
1110 int b; /* best local begin state */
1111 float bsc; /* score for using the best local begin state */
1112 int *yvalidA; /* [0..MAXCONNECT-1] TRUE if v->yoffset is legal transition (within bands) */
1113 float *el_scA; /* [0..d..L-1] probability of local end emissions of length d */
1114 int sd; /* StateDelta(cm->sttype[v]) */
1115 int sdr; /* StateRightDelta(cm->sttype[v] */
1116 int j_sdr; /* j - sdr */
1117 int c; /* 64-bit int counter */
1118
1119 /* indices used for handling band-offset issues, and in the depths of the DP recursion */
1120 int jp_v, jp_y, jp_z; /* offset j index for states v, y, z */
1121 int jp_y_sdr; /* jp_y - sdr */
1122 int jn, jx; /* current minimum/maximum j allowed */
1123 int jpn, jpx; /* minimum/maximum jp_v */
1124 int dp_v, dp_y; /* d index for state v/y in alpha w/mem eff bands */
1125 int dn, dx; /* current minimum/maximum d allowed */
1126 int dp_y_sd; /* dp_y - sd */
1127 int dpn, dpx; /* minimum/maximum dp_v */
1128 int kp_z; /* k (in the d dim) index for state z in alpha w/mem eff bands */
1129 int kn, kx; /* current minimum/maximum k value */
1130 int Lp; /* L index also changes depending on state */
1131 float tsc; /* a transition score */
1132 int yvalid_idx; /* for keeping track of which children are valid */
1133 int yvalid_ct; /* for keeping track of which children are valid */
1134 int jp_0; /* L offset in ROOT_S's (v==0) j band */
1135 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
1136
1137 /* variables used for memory efficient bands */
1138 /* ptrs to cp9b info, for convenience */
1139 CP9Bands_t *cp9b = cm->cp9b;
1140 int *jmin = cp9b->jmin;
1141 int *jmax = cp9b->jmax;
1142 int **hdmin = cp9b->hdmin;
1143 int **hdmax = cp9b->hdmax;
1144 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
1145 char ***yshadow = shmx->yshadow; /* pointer to the yshadow matrix */
1146 int ***kshadow = shmx->kshadow; /* pointer to the kshadow matrix */
1147
1148 /* Allocations and initializations */
1149 b = -1;
1150 bsc = IMPOSSIBLE;
1151 /* ensure a full alignment to ROOT_S (v==0) is allowed by the bands */
1152 if (cp9b->jmin[0] > L || cp9b->jmax[0] < L)
1153 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cp9b->jmin[0], cp9b->jmax[0]);
1154 jp_0 = L - jmin[0];
1155 if (cp9b->hdmin[0][jp_0] > L || cp9b->hdmax[0][jp_0] < L)
1156 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cp9b->hdmin[0][jp_0], cp9b->hdmax[0][jp_0]);
1157 Lp_0 = L - hdmin[0][jp_0];
1158
1159 /* grow the matrices based on the current sequence and bands */
1160 if((status = cm_hb_mx_GrowTo (cm, mx, errbuf, cp9b, L, size_limit)) != eslOK) return status;
1161 if((status = cm_hb_shadow_mx_GrowTo(cm, shmx, errbuf, cp9b, L, size_limit)) != eslOK) return status;
1162
1163 /* precalcuate all possible local end scores, for local end emits of 1..L residues */
1164 ESL_ALLOC(el_scA, sizeof(float) * (L+1));
1165 for(d = 0; d <= L; d++) el_scA[d] = cm->el_selfsc * d;
1166
1167 /* yvalidA[0..cnum[v]] will hold TRUE for states y for which a transition is legal
1168 * (some transitions are impossible due to the bands)
1169 */
1170 ESL_ALLOC(yvalidA, sizeof(int) * MAXCONNECT);
1171 esl_vec_ISet(yvalidA, MAXCONNECT, FALSE);
1172
1173 /* initialize all cells of the matrix to IMPOSSIBLE */
1174 esl_vec_FSet(alpha[0][0], mx->ncells_valid, IMPOSSIBLE);
1175 if(shmx->y_ncells_valid > 0) for(c = 0; c < shmx->y_ncells_valid; c++) shmx->yshadow_mem[c] = USED_EL;
1176 /* for B states, shadow matrix holds k, length of right fragment, this will be overwritten */
1177 if(shmx->k_ncells_valid > 0) esl_vec_ISet(shmx->kshadow_mem, shmx->k_ncells_valid, 0);
1178
1179 /* if local ends are on, replace the EL deck IMPOSSIBLEs with EL scores,
1180 * Note: we could optimize by skipping this step and using el_scA[d] to
1181 * initialize ELs for each state in the first step of the main recursion
1182 * below. We fill in the EL deck here for completeness and so that
1183 * a check of this alpha matrix with a CYKOutside matrix will pass.
1184 */
1185 if(cm->flags & CMH_LOCAL_END) {
1186 for (j = 0; j <= L; j++) {
1187 for (d = 0; d <= j; d++) alpha[cm->M][j][d] = el_scA[d];
1188 }
1189 }
1190
1191 /* Main recursion */
1192 for (v = cm->M-1; v >= 0; v--) {
1193 float const *esc_v = cm->oesc[v]; /* emission scores for state v */
1194 float const *tsc_v = cm->tsc[v]; /* transition scores for state v */
1195 sd = StateDelta(cm->sttype[v]);
1196 sdr = StateRightDelta(cm->sttype[v]);
1197 jn = jmin[v];
1198 jx = jmax[v];
1199
1200 /* re-initialize if we can do a local end from v */
1201 if(NOT_IMPOSSIBLE(cm->endsc[v])) {
1202 for (j = jmin[v]; j <= jmax[v]; j++) {
1203 jp_v = j - jmin[v];
1204 if(hdmin[v][jp_v] >= sd) {
1205 d = hdmin[v][jp_v];
1206 dp_v = 0;
1207 }
1208 else {
1209 d = sd;
1210 dp_v = sd - hdmin[v][jp_v];
1211 }
1212 for (; d <= hdmax[v][jp_v]; dp_v++, d++) {
1213 if(d >= sd) {
1214 alpha[v][jp_v][dp_v] = alpha[cm->M][j][d-sd] + cm->endsc[v];
1215 /* If we optimize by skipping the filling of the
1216 * EL deck the above line would become:
1217 * 'alpha[v][jp_v][dp_v] = el_scA[d-sd] + cm->endsc[v];'
1218 */
1219 }
1220 }
1221 }
1222 }
1223 /* otherwise this state's deck has already been initialized to IMPOSSIBLE */
1224
1225 if(cm->sttype[v] == E_st) {
1226 for (j = jmin[v]; j <= jmax[v]; j++) {
1227 jp_v = j-jmin[v];
1228 ESL_DASSERT1((hdmin[v][jp_v] == 0));
1229 ESL_DASSERT1((hdmax[v][jp_v] == 0));
1230 alpha[v][jp_v][0] = 0.; /* for End states, d must be 0 */
1231 }
1232 }
1233 else if(cm->sttype[v] == IL_st) {
1234 /* update alpha[v][jp_v][dp_v] cells, for IL states, loop nesting order is:
1235 * for j { for d { for y { } } } because they can self transit, and a
1236 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1237 * before can start calc'ing for alpha[v][j][d+1] */
1238 for (j = jmin[v]; j <= jmax[v]; j++) {
1239 ESL_DASSERT1((j >= 0 && j <= L));
1240 jp_v = j - jmin[v];
1241 yvalid_ct = 0;
1242 j_sdr = j - sdr;
1243
1244 /* determine which children y we can legally transit to for v, j */
1245 for (y = cm->cfirst[v], yoffset = 0; y < (cm->cfirst[v] + cm->cnum[v]); y++, yoffset++)
1246 if((j_sdr) >= jmin[y] && ((j_sdr) <= jmax[y])) yvalidA[yvalid_ct++] = yoffset; /* is j-sdr valid for state y? */
1247
1248 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) { /* for each valid d for v, j */
1249 i = j - d + 1;
1250 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha */
1251 for (yvalid_idx = 0; yvalid_idx < yvalid_ct; yvalid_idx++) { /* for each valid child y, for v, j */
1252 yoffset = yvalidA[yvalid_idx];
1253 y = cm->cfirst[v] + yoffset;
1254 jp_y_sdr = j - jmin[y] - sdr;
1255
1256 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) { /* make sure d is valid for this v, j and y */
1257 dp_y_sd = d - sd - hdmin[y][jp_y_sdr];
1258 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1259 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1260 if ((sc = alpha[y][jp_y_sdr][dp_y_sd] + tsc_v[yoffset]) > alpha[v][jp_v][dp_v])
1261 {
1262 alpha[v][jp_v][dp_v] = sc;
1263 yshadow[v][jp_v][dp_v] = yoffset;
1264 }
1265 }
1266 }
1267 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]];
1268 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
1269 }
1270 }
1271 }
1272 else if(cm->sttype[v] == IR_st) {
1273 /* update alpha[v][jp_v][dp_v] cells, for IR states, loop nesting order is:
1274 * for j { for d { for y { } } } because they can self transit, and a
1275 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1276 * before can start calc'ing for alpha[v][j][d+1] */
1277 for (j = jmin[v]; j <= jmax[v]; j++) {
1278 ESL_DASSERT1((j >= 0 && j <= L));
1279 jp_v = j - jmin[v];
1280 yvalid_ct = 0;
1281 j_sdr = j - sdr;
1282
1283 /* determine which children y we can legally transit to for v, j */
1284 for (y = cm->cfirst[v], yoffset = 0; y < (cm->cfirst[v] + cm->cnum[v]); y++, yoffset++)
1285 if((j_sdr) >= jmin[y] && ((j_sdr) <= jmax[y])) yvalidA[yvalid_ct++] = yoffset; /* is j-sdr is valid for state y? */
1286
1287 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) { /* for each valid d for v, j */
1288 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha */
1289 for (yvalid_idx = 0; yvalid_idx < yvalid_ct; yvalid_idx++) { /* for each valid child y, for v, j */
1290 yoffset = yvalidA[yvalid_idx];
1291 y = cm->cfirst[v] + yoffset;
1292 jp_y_sdr = j - jmin[y] - sdr;
1293
1294 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) { /* make sure d is valid for this v, j and y */
1295 dp_y_sd = d - sd - hdmin[y][jp_y_sdr];
1296 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1297 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1298 if ((sc = alpha[y][jp_y_sdr][dp_y_sd] + tsc_v[yoffset]) > alpha[v][jp_v][dp_v])
1299 {
1300 alpha[v][jp_v][dp_v] = sc;
1301 yshadow[v][jp_v][dp_v] = yoffset;
1302 }
1303 }
1304 }
1305 alpha[v][jp_v][dp_v] += esc_v[dsq[j]];
1306 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
1307 }
1308 }
1309 }
1310 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
1311 /* ML, MP, MR, D, S, E states cannot self transit, this means that all cells
1312 * in alpha[v] are independent of each other, only depending on alpha[y] for previously calc'ed y.
1313 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
1314 * for y { for j { for d { } } }
1315 */
1316 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
1317 yoffset = y - cm->cfirst[v];
1318 tsc = tsc_v[yoffset];
1319
1320 /* j must satisfy:
1321 * j >= jmin[v]
1322 * j >= jmin[y]+sdr (follows from (j-sdr >= jmin[y]))
1323 * j <= jmax[v]
1324 * j <= jmax[y]+sdr (follows from (j-sdr <= jmax[y]))
1325 * this reduces to two ESL_MAX calls
1326 */
1327 jn = ESL_MAX(jmin[v], jmin[y]+sdr);
1328 jx = ESL_MIN(jmax[v], jmax[y]+sdr);
1329
1330 jpn = jn - jmin[v];
1331 jpx = jx - jmin[v];
1332 jp_y_sdr = jn - jmin[y] - sdr;
1333
1334 for (jp_v = jpn; jp_v <= jpx; jp_v++, jp_y_sdr++) {
1335 ESL_DASSERT1((jp_v >= 0 && jp_v <= (jmax[v]-jmin[v])));
1336 ESL_DASSERT1((jp_y_sdr >= 0 && jp_y_sdr <= (jmax[y]-jmin[y])));
1337
1338 /* d must satisfy:
1339 * d >= hdmin[v][jp_v]
1340 * d >= hdmin[y][jp_y_sdr]+sd (follows from (d-sd >= hdmin[y][jp_y_sdr]))
1341 * d <= hdmax[v][jp_v]
1342 * d <= hdmax[y][jp_y_sdr]+sd (follows from (d-sd <= hdmax[y][jp_y_sdr]))
1343 * this reduces to two ESL_MAX calls
1344 */
1345 dn = ESL_MAX(hdmin[v][jp_v], hdmin[y][jp_y_sdr] + sd);
1346 dx = ESL_MIN(hdmax[v][jp_v], hdmax[y][jp_y_sdr] + sd);
1347 dpn = dn - hdmin[v][jp_v];
1348 dpx = dx - hdmin[v][jp_v];
1349 dp_y_sd = dn - hdmin[y][jp_y_sdr] - sd;
1350
1351 for (dp_v = dpn; dp_v <= dpx; dp_v++, dp_y_sd++) {
1352 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1353 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1354 if((sc = alpha[y][jp_y_sdr][dp_y_sd] + tsc) > alpha[v][jp_v][dp_v]) {
1355 alpha[v][jp_v][dp_v] = sc;
1356 yshadow[v][jp_v][dp_v] = yoffset;
1357 }
1358 }
1359 }
1360 }
1361 /* add in emission score, if any */
1362 switch(cm->sttype[v]) {
1363 case ML_st:
1364 for (j = jmin[v]; j <= jmax[v]; j++) {
1365 jp_v = j - jmin[v];
1366 i = j - hdmin[v][jp_v] + 1;
1367 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
1368 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]];
1369 }
1370 break;
1371 case MR_st:
1372 for (j = jmin[v]; j <= jmax[v]; j++) {
1373 jp_v = j - jmin[v];
1374 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
1375 alpha[v][jp_v][dp_v] += esc_v[dsq[j]];
1376 }
1377 break;
1378 case MP_st:
1379 for (j = jmin[v]; j <= jmax[v]; j++) {
1380 jp_v = j - jmin[v];
1381 i = j - hdmin[v][jp_v] + 1;
1382 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
1383 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]*cm->abc->Kp+dsq[j]];
1384 }
1385 default:
1386 break;
1387 }
1388 /* ensure all cells are >= IMPOSSIBLE */
1389 for (j = jmin[v]; j <= jmax[v]; j++) {
1390 jp_v = j - jmin[v];
1391 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
1392 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
1393 }
1394 }
1395 else { /* B_st */
1396 y = cm->cfirst[v]; /* left subtree */
1397 z = cm->cnum[v]; /* right subtree */
1398
1399 /* Any valid j must be within both state v and state z's j band
1400 * I think jmin[v] <= jmin[z] is guaranteed by the way bands are
1401 * constructed, but we'll check anyway.
1402 */
1403 jn = (jmin[v] > jmin[z]) ? jmin[v] : jmin[z];
1404 jx = (jmax[v] < jmax[z]) ? jmax[v] : jmax[z];
1405 /* the main j loop */
1406 for (j = jn; j <= jx; j++) {
1407 jp_v = j - jmin[v];
1408 jp_y = j - jmin[y];
1409 jp_z = j - jmin[z];
1410 kn = ((j-jmax[y]) > (hdmin[z][jp_z])) ? (j-jmax[y]) : hdmin[z][jp_z];
1411 kn = ESL_MAX(kn, 0); /* kn must be non-negative, added with fix to bug i36 */
1412 /* kn satisfies inequalities (1) and (3) (listed below)*/
1413 kx = ( jp_y < (hdmax[z][jp_z])) ? jp_y : hdmax[z][jp_z];
1414 /* kn satisfies inequalities (2) and (4) (listed below)*/
1415 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
1416 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
1417
1418 /* Find the first k value that implies a valid cell in the y and z decks.
1419 * This k must satisfy the following 6 inequalities (some may be redundant):
1420 * (1) k >= j-jmax[y];
1421 * (2) k <= j-jmin[y];
1422 * 1 and 2 guarantee (j-k) is within state y's j band
1423 *
1424 * (3) k >= hdmin[z][j-jmin[z]];
1425 * (4) k <= hdmax[z][j-jmin[z]];
1426 * 3 and 4 guarantee k is within z's j=(j), d band
1427 *
1428 * (5) k >= d-hdmax[y][j-jmin[y]-k];
1429 * (6) k <= d-hdmin[y][j-jmin[y]-k];
1430 * 5 and 6 guarantee (d-k) is within state y's j=(j-k) d band
1431 *
1432 * kn and kx were set above (outside (for (dp_v...) loop) that
1433 * satisfy 1-4 (b/c 1-4 are d-independent and k-independent)
1434 * RHS of inequalities 5 and 6 are dependent on k, so we check
1435 * for these within the next for loop.
1436 */
1437 for(k = kn; k <= kx; k++) {
1438 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
1439 /* for current k, all 6 inequalities have been satisified
1440 * so we know the cells corresponding to the platonic
1441 * matrix cells alpha[v][j][d], alpha[y][j-k][d-k], and
1442 * alpha[z][j][k] are all within the bands. These
1443 * cells correspond to alpha[v][jp_v][dp_v],
1444 * alpha[y][jp_y-k][d-hdmin[jp_y-k]-k],
1445 * and alpha[z][jp_z][k-hdmin[jp_z]];
1446 */
1447 kp_z = k-hdmin[z][jp_z];
1448 dp_y = d-hdmin[y][jp_y-k];
1449
1450 if ((sc = alpha[y][jp_y-k][dp_y - k] + alpha[z][jp_z][kp_z])
1451 > alpha[v][jp_v][dp_v]) {
1452 alpha[v][jp_v][dp_v] = sc;
1453 kshadow[v][jp_v][dp_v] = k;
1454 }
1455 }
1456 }
1457 }
1458 }
1459 } /* finished calculating deck v. */
1460
1461 /* allow local begins, if nec */
1462 if(cm->flags & CMH_LOCAL_BEGIN) {
1463 if(L >= jmin[v] && L <= jmax[v]) {
1464 jp_v = L - jmin[v];
1465 Lp = L - hdmin[v][jp_v];
1466 if(L >= hdmin[v][jp_v] && L <= hdmax[v][jp_v]) {
1467 /* If we get here alpha[v][jp_v][Lp] is a valid cell
1468 * in the banded alpha matrix, corresponding to
1469 * alpha[v][L][L] in the platonic matrix.
1470 */
1471 /* Check for local begin getting us to the root.
1472 * This is "off-shadow": if/when we trace back, we'll handle this
1473 * case separately (and we'll know to do it because we'll immediately
1474 * see a USED_LOCAL_BEGIN flag in the shadow matrix, telling us
1475 * to jump right to state b; see below)
1476 */
1477 if (NOT_IMPOSSIBLE(cm->beginsc[v]) &&
1478 (alpha[v][jp_v][Lp] + cm->beginsc[v] > bsc)) {
1479 b = v;
1480 bsc = alpha[v][jp_v][Lp] + cm->beginsc[v];
1481 }
1482 }
1483 }
1484 }
1485 } /* end loop over all v */
1486 /* Check for whether we need to store an optimal local begin score
1487 * as the optimal overall score, and if we need to put a flag
1488 * in the shadow matrix telling cm_alignT() to use the b we return.
1489 */
1490 if (NOT_IMPOSSIBLE(bsc) && (bsc > alpha[0][jp_0][Lp_0])) {
1491 alpha[0][jp_0][Lp_0] = bsc;
1492 yshadow[0][jp_0][Lp_0] = USED_LOCAL_BEGIN;
1493 }
1494
1495 #if eslDEBUGLEVEL >= 3
1496 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
1497 /* FILE *fp1; fp1 = fopen("tmp.std_cykhbmx", "w"); cm_hb_mx_Dump(fp1, mx); fclose(fp1); */
1498 /* FILE *fp2; fp2 = fopen("tmp.std_cykhbshmx", "w"); cm_hb_shadow_mx_Dump(fp2, cm, shmx); fclose(fp2); */
1499 #endif
1500
1501 sc = alpha[0][jp_0][Lp_0];
1502
1503 free(el_scA);
1504 free(yvalidA);
1505
1506 if (ret_b != NULL) *ret_b = b; /* b is -1 if local begins are off */
1507 if (ret_sc != NULL) *ret_sc = sc;
1508
1509 ESL_DPRINTF1(("#DEBUG: cm_CYKInsideAlignHB return sc: %f\n", sc));
1510 return eslOK;
1511
1512 ERROR:
1513 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
1514 }
1515
1516 /* Function: cm_InsideAlign()
1517 * Date: EPN, Mon Nov 19 06:21:51 2007
1518 *
1519 * Purpose: Run the inside algorithm on a target sequence
1520 * without using bands. The full target sequence
1521 * 1..L is aligned (only full alignments will
1522 * contribute to the Inside score).
1523 *
1524 * Identical to cm_InsideAlignHB() but no bands
1525 * are used.
1526 *
1527 * Very similar to cm_CYKInsideAlign(), see 'Purpose'
1528 * of that function for more details. Only differences with
1529 * that function is:
1530 * - we do Inside, not CYK
1531 * - can't return a shadow matrix (we're not aligning)
1532 * - doesn't return bsc, b info about local begins
1533 *
1534 * This function complements cm_OutsideAlign().
1535 *
1536 * Note: renamed from FastInsideAlign() [EPN, Wed Sep 14 06:13:37 2011].
1537 *
1538 * Args: cm - the model
1539 * errbuf - char buffer for reporting errors
1540 * dsq - the digitized sequence
1541 * L - target sequence length
1542 * size_limit - max number of Mb for DP matrix, if matrix is bigger return eslERANGE
1543 * mx - the dp matrix, grown and filled here
1544 * ret_sc - RETURN: log P(S|M)/P(S|R), as a bit score
1545 *
1546 * Returns: <eslOK> on success.
1547 *
1548 * Throws: <eslERANGE> if required CM_MX size exceeds <size_limit>
1549 * In this case alignment has been aborted, ret_sc is not valid
1550 */
1551 int
1552 cm_InsideAlign(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, CM_MX *mx, float *ret_sc)
1553 {
1554 int status;
1555 int v,y,z; /* indices for states */
1556 int j,d,i,k; /* indices in sequence dimensions */
1557 float sc; /* the final score */
1558 float tsc; /* a temporary variable holding a transition score */
1559 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
1560 float bsc; /* summed score for using all local begins */
1561 float *el_scA; /* [0..d..L-1] probability of local end emissions of length d */
1562 int sd; /* StateDelta(cm->sttype[v]) */
1563 int sdl; /* StateLeftDelta(cm->sttype[v] */
1564 int sdr; /* StateRightDelta(cm->sttype[v] */
1565 int j_sdr; /* j - sdr */
1566 int d_sd; /* d - sd */
1567
1568 /* the DP matrix */
1569 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
1570
1571 /* Allocations and initializations */
1572 bsc = IMPOSSIBLE;
1573
1574 /* grow the matrix based on the current sequence */
1575 if((status = cm_mx_GrowTo(cm, mx, errbuf, L, size_limit)) != eslOK) return status;
1576
1577 /* initialize all cells of the matrix to IMPOSSIBLE */
1578 esl_vec_FSet(alpha[0][0], mx->ncells_valid, IMPOSSIBLE);
1579
1580 /* precalcuate all possible local end scores, for local end emits of 1..L residues */
1581 ESL_ALLOC(el_scA, sizeof(float) * (L+1));
1582 for(d = 0; d <= L; d++) el_scA[d] = cm->el_selfsc * d;
1583
1584 /* if local ends are on, replace the EL deck IMPOSSIBLEs with EL scores */
1585 if(cm->flags & CMH_LOCAL_END) {
1586 for (j = 0; j <= L; j++) {
1587 for (d = 0; d <= j; d++) alpha[cm->M][j][d] = el_scA[d];
1588 }
1589 }
1590
1591 /* Main recursion */
1592 for (v = cm->M-1; v >= 0; v--) {
1593 float const *esc_v = cm->oesc[v];
1594 float const *tsc_v = cm->tsc[v];
1595 sd = StateDelta(cm->sttype[v]);
1596 sdl = StateLeftDelta(cm->sttype[v]);
1597 sdr = StateRightDelta(cm->sttype[v]);
1598
1599 /* re-initialize the J deck if we can do a local end from v */
1600 if(NOT_IMPOSSIBLE(cm->endsc[v])) {
1601 for (j = 0; j <= L; j++) {
1602 for (d = sd; d <= j; d++) alpha[v][j][d] = el_scA[d-sd] + cm->endsc[v];
1603 }
1604 }
1605 /* otherwise this state's deck has already been initialized to IMPOSSIBLE */
1606
1607 /* E_st: easy, no children, and d must be 0 for all valid j */
1608 if(cm->sttype[v] == E_st) {
1609 for (j = 0; j <= L; j++) {
1610 alpha[v][j][0] = 0.;
1611 /* rest of deck remains IMPOSSIBLE */
1612 }
1613 }
1614 else if(cm->sttype[v] == IL_st) {
1615 /* update alpha[v][jp_v][dp_v] cells, for IL states, loop nesting order is:
1616 * for j { for d { for y { } } } because they can self transit, and a
1617 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1618 * before can start calc'ing for alpha[v][j][d+1] */
1619 for (j = sdr; j <= L; j++) {
1620 j_sdr = j - sdr;
1621 for (d = sd; d <= j; d++) {
1622 d_sd = d - sd;
1623 i = j - d + 1;
1624 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
1625 y = cm->cfirst[v] + yoffset;
1626 alpha[v][j][d] = FLogsum(alpha[v][j][d], alpha[y][j_sdr][d_sd] + tsc_v[yoffset]);
1627 }
1628 alpha[v][j][d] += esc_v[dsq[i--]];
1629 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
1630 }
1631 }
1632 }
1633 else if(cm->sttype[v] == IR_st) {
1634 /* update alpha[v][jp_v][dp_v] cells, for IR states, loop nesting order is:
1635 * for j { for d { for y { } } } because they can self transit, and a
1636 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1637 * before can start calc'ing for alpha[v][j][d+1] */
1638 for (j = sdr; j <= L; j++) {
1639 j_sdr = j - sdr;
1640 for (d = sd; d <= j; d++) {
1641 d_sd = d - sd;
1642 i = j - d + 1;
1643 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
1644 y = cm->cfirst[v] + yoffset;
1645 alpha[v][j][d] = FLogsum(alpha[v][j][d], alpha[y][j_sdr][d_sd] + tsc_v[yoffset]);
1646 }
1647 alpha[v][j][d] += esc_v[dsq[j]];
1648 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
1649 }
1650 }
1651 }
1652 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
1653 /* ML, MP, MR, D, S, E states cannot self transit, this means that all cells
1654 * in alpha[v] are independent of each other, only depending on alpha[y] for previously calc'ed y.
1655 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
1656 * for y { for j { for d { } } }
1657 */
1658 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
1659 yoffset = y - cm->cfirst[v];
1660 tsc = tsc_v[yoffset];
1661
1662 for (j = sdr; j <= L; j++) {
1663 j_sdr = j - sdr;
1664 for (d = sd; d <= j; d++) {
1665 alpha[v][j][d] = FLogsum(alpha[v][j][d], (alpha[y][j_sdr][d-sd] + tsc));;
1666 }
1667 }
1668 }
1669 /* add in emission score, if any */
1670 switch(cm->sttype[v]) {
1671 case ML_st:
1672 for (j = 0; j <= L; j++) {
1673 i = j - sdl;
1674 for (d = sd; d <= j; d++)
1675 alpha[v][j][d] += esc_v[dsq[j-d+1]];
1676 }
1677 break;
1678 case MR_st:
1679 for (j = 0; j <= L; j++) {
1680 for (d = sd; d <= j; d++)
1681 alpha[v][j][d] += esc_v[dsq[j]];
1682 }
1683 break;
1684 case MP_st:
1685 for (j = 0; j <= L; j++) {
1686 i = j - sdl;
1687 for (d = sd; d <= j; d++)
1688 alpha[v][j][d] += esc_v[dsq[i--]*cm->abc->Kp+dsq[j]];
1689 }
1690 default:
1691 break;
1692 }
1693 /* ensure all cells are >= IMPOSSIBLE */
1694 for (j = 0; j <= L; j++) {
1695 for (d = 0; d <= j; d++)
1696 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
1697 }
1698 }
1699 else { /* B_st */
1700 y = cm->cfirst[v]; /* left subtree */
1701 z = cm->cnum[v]; /* right subtree */
1702
1703 for (j = 0; j <= L; j++) {
1704 for (d = 0; d <= j; d++) {
1705 for (k = 0; k <= d; k++) {
1706 alpha[v][j][d] = FLogsum(alpha[v][j][d], alpha[y][j-k][d-k] + alpha[z][j][k]);
1707 }
1708 }
1709 }
1710 }
1711
1712 /* allow local begins, if nec */
1713 if ((cm->flags & CMH_LOCAL_BEGIN) &&
1714 (NOT_IMPOSSIBLE(cm->beginsc[v]))) {
1715 /* add in score for local begin getting us to the root. */
1716 bsc = FLogsum(bsc, alpha[v][L][L] + cm->beginsc[v]);
1717 }
1718 } /* finished calculating deck v. */
1719
1720 /* include the bsc as part of alpha[0][L][L] */
1721 alpha[0][L][L] = FLogsum(alpha[0][L][L], bsc);
1722
1723 #if eslDEBUGLEVEL >= 3
1724 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
1725 /* FILE *fp1; fp1 = fopen("tmp.std_imx", "w"); cm_mx_Dump(fp1, mx); fclose(fp1); */
1726 #endif
1727
1728 sc = alpha[0][L][L];
1729
1730 free(el_scA);
1731
1732 if(ret_sc != NULL) *ret_sc = sc;
1733
1734 ESL_DPRINTF1(("#DEBUG: cm_InsideAlign() return sc: %f\n", sc));
1735 return eslOK;
1736
1737 ERROR:
1738 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
1739 }
1740
1741 /* Function: cm_InsideAlignHB()
1742 * Date: EPN, Thu Nov 8 18:24:41 2007
1743 *
1744 * Purpose: Run the inside algorithm on a target sequence using bands
1745 * in the j and d dimensions of the DP matrix. Bands
1746 * were obtained from an HMM Forward-Backward parse
1747 * of the target sequence. Uses float log odds scores.
1748 * The full target sequence 1..L is aligned (only full
1749 * alignments will contribute to the Inside score).
1750 *
1751 * Very similar to cm_CYKInsideAlignHB(), see 'Purpose'
1752 * of that function for more details. Only differences with
1753 * that function is:
1754 * - we do Inside, not CYK
1755 * - can't return a shadow matrix (we're not aligning)
1756 * - doesn't return bsc, b info about local begins
1757 *
1758 * This function complements cm_OutsideAlignHB().
1759 *
1760 * Note: renamed from FastInsideAlignHB() [EPN, Wed Sep 14 06:13:08 2011].
1761 *
1762 * Args: cm - the model
1763 * errbuf - char buffer for reporting errors
1764 * dsq - the digitized sequence
1765 * L - target sequence length
1766 * size_limit - max number of Mb for DP matrix, if matrix is bigger return eslERANGE
1767 * mx - the dp matrix, only cells within bands in cp9b will be valid
1768 * ret_sc - RETURN: log P(S|M)/P(S|R) (given bands), as a bit score
1769 *
1770 * Returns: <eslOK> on success.
1771 *
1772 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
1773 * <eslEINVAL> if the full sequence is not within the bands for state 0
1774 * In either case alignment has been aborted, ret_sc is not valid
1775 */
1776 int
1777 cm_InsideAlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, CM_HB_MX *mx, float *ret_sc)
1778 {
1779 int status;
1780 int v,y,z; /* indices for states */
1781 int j,d,i,k; /* indices in sequence dimensions */
1782 float sc; /* the final score */
1783 float tsc; /* a temporary variable holding a transition score */
1784 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
1785 float bsc; /* summed score for using all local begins */
1786 float *el_scA; /* [0..d..L-1] probability of local end emissions of length d */
1787 int sd; /* StateDelta(cm->sttype[v]) */
1788 int sdr; /* StateRightDelta(cm->sttype[v] */
1789 int j_sdr; /* j - sdr */
1790
1791 /* indices used for handling band-offset issues, and in the depths of the DP recursion */
1792 int *yvalidA; /* [0..MAXCONNECT-1] TRUE if v->yoffset is legal transition (within bands) */
1793 int jp_v, jp_y, jp_z; /* offset j index for states v, y, z */
1794 int jp_y_sdr; /* jp_y - sdr */
1795 int jn, jx; /* current minimum/maximum j allowed */
1796 int jpn, jpx; /* minimum/maximum jp_v */
1797 int dp_v, dp_y; /* d index for state v/y in alpha w/mem eff bands */
1798 int dn, dx; /* current minimum/maximum d allowed */
1799 int dp_y_sd; /* dp_y - sd */
1800 int dpn, dpx; /* minimum/maximum dp_v */
1801 int kp_z; /* k (in the d dim) index for state z in alpha w/mem eff bands */
1802 int kn, kx; /* current minimum/maximum k value */
1803 int Lp; /* L also changes depending on state */
1804 int yvalid_idx; /* for keeping track of which children are valid */
1805 int yvalid_ct; /* for keeping track of which children are valid */
1806 int jp_0; /* L offset in ROOT_S's (v==0) j band */
1807 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
1808
1809 /* ptrs to cp9b info, for convenience */
1810 CP9Bands_t *cp9b = cm->cp9b;
1811 int *jmin = cp9b->jmin;
1812 int *jmax = cp9b->jmax;
1813 int **hdmin = cp9b->hdmin;
1814 int **hdmax = cp9b->hdmax;
1815
1816 /* the DP matrix */
1817 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
1818
1819 /* Allocations and initializations */
1820 bsc = IMPOSSIBLE;
1821 /* ensure a full alignment to ROOT_S (v==0) is allowed by the bands */
1822 if (cp9b->jmin[0] > L || cp9b->jmax[0] < L)
1823 ESL_FAIL(eslEINVAL, errbuf, "cm_InsideAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cp9b->jmin[0], cp9b->jmax[0]);
1824 jp_0 = L - jmin[0];
1825 if (cp9b->hdmin[0][jp_0] > L || cp9b->hdmax[0][jp_0] < L)
1826 ESL_FAIL(eslEINVAL, errbuf, "cm_InsideAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cp9b->hdmin[0][jp_0], cp9b->hdmax[0][jp_0]);
1827 Lp_0 = L - hdmin[0][jp_0];
1828
1829 /* grow the matrix based on the current sequence and bands */
1830 if((status = cm_hb_mx_GrowTo(cm, mx, errbuf, cp9b, L, size_limit)) != eslOK) return status;
1831
1832 /* initialize all cells of the matrix to IMPOSSIBLE */
1833 esl_vec_FSet(alpha[0][0], mx->ncells_valid, IMPOSSIBLE);
1834
1835 /* precalcuate all possible local end scores, for local end emits of 1..W residues */
1836 ESL_ALLOC(el_scA, sizeof(float) * (L+1));
1837 for(d = 0; d <= L; d++) el_scA[d] = cm->el_selfsc * d;
1838
1839 /* yvalidA[0..cnum[v]] will hold TRUE for states y for which a transition is legal
1840 * (some transitions are impossible due to the bands)
1841 */
1842 ESL_ALLOC(yvalidA, sizeof(int) * MAXCONNECT);
1843 esl_vec_ISet(yvalidA, MAXCONNECT, FALSE);
1844
1845
1846 /* if local ends are on, replace the EL deck IMPOSSIBLEs with EL scores,
1847 * Note: we could optimize by skipping this step and using el_scA[d] to
1848 * initialize ELs for each state in the first step of the main recursion
1849 * below. We fill in the EL deck here for completeness and so that
1850 * a check of this alpha matrix with a CYKOutside matrix will pass.
1851 */
1852 if(cm->flags & CMH_LOCAL_END) {
1853 for (j = 0; j <= L; j++) {
1854 for (d = 0; d <= j; d++) alpha[cm->M][j][d] = el_scA[d];
1855 }
1856 }
1857
1858 /* Main recursion */
1859 for (v = cm->M-1; v >= 0; v--) {
1860 float const *esc_v = cm->oesc[v];
1861 float const *tsc_v = cm->tsc[v];
1862 sd = StateDelta(cm->sttype[v]);
1863 sdr = StateRightDelta(cm->sttype[v]);
1864 jn = jmin[v];
1865 jx = jmax[v];
1866
1867 /* re-initialize the J deck if we can do a local end from v */
1868 if(NOT_IMPOSSIBLE(cm->endsc[v])) {
1869 for (j = jmin[v]; j <= jmax[v]; j++) {
1870 ESL_DASSERT1((j >= 0 && j <= L));
1871 jp_v = j - jmin[v];
1872 for (dp_v = 0, d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; dp_v++, d++)
1873 alpha[v][jp_v][dp_v] = el_scA[d-sd] + cm->endsc[v];
1874 }
1875 }
1876 /* otherwise this state's deck has already been initialized to IMPOSSIBLE */
1877
1878 /* E_st: easy, no children, and d must be 0 for all valid j */
1879 if(cm->sttype[v] == E_st) {
1880 for (j = jmin[v]; j <= jmax[v]; j++) {
1881 jp_v = j-jmin[v];
1882 ESL_DASSERT1((hdmin[v][jp_v] == 0));
1883 ESL_DASSERT1((hdmax[v][jp_v] == 0));
1884 alpha[v][jp_v][0] = 0.; /* for End states, d must be 0 */
1885 /* rest of deck remains IMPOSSIBLE */
1886 }
1887 }
1888 else if(cm->sttype[v] == IL_st) {
1889 /* update alpha[v][jp_v][dp_v] cells, for IL states, loop nesting order is:
1890 * for j { for d { for y { } } } because they can self transit, and a
1891 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1892 * before can start calc'ing for alpha[v][j][d+1] */
1893 for (j = jmin[v]; j <= jmax[v]; j++) {
1894 ESL_DASSERT1((j >= 0 && j <= L));
1895 jp_v = j - jmin[v];
1896 yvalid_ct = 0;
1897 j_sdr = j - sdr;
1898
1899 /* determine which children y we can legally transit to for v, j */
1900 for (y = cm->cfirst[v], yoffset = 0; y < (cm->cfirst[v] + cm->cnum[v]); y++, yoffset++)
1901 if((j_sdr) >= jmin[y] && ((j_sdr) <= jmax[y])) yvalidA[yvalid_ct++] = yoffset; /* is j-sdr is valid for state y? */
1902
1903 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) { /* for each valid d for v, j */
1904 i = j - d + 1;
1905 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha */
1906 for (yvalid_idx = 0; yvalid_idx < yvalid_ct; yvalid_idx++) { /* for each valid child y, for v, j */
1907 yoffset = yvalidA[yvalid_idx];
1908 y = cm->cfirst[v] + yoffset;
1909 jp_y_sdr = j - jmin[y] - sdr;
1910
1911 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) { /* make sure d is valid for this v, j and y */
1912 dp_y_sd = d - sd - hdmin[y][jp_y_sdr];
1913 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1914 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1915 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], alpha[y][jp_y_sdr][dp_y_sd] + tsc_v[yoffset]);
1916 }
1917 }
1918 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]];
1919 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
1920 }
1921 }
1922 }
1923 else if(cm->sttype[v] == IR_st) {
1924 /* update alpha[v][jp_v][dp_v] cells, for IR states, loop nesting order is:
1925 * for j { for d { for y { } } } because they can self transit, and a
1926 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
1927 * before can start calc'ing for alpha[v][j][d+1] */
1928 for (j = jmin[v]; j <= jmax[v]; j++) {
1929 ESL_DASSERT1((j >= 0 && j <= L));
1930 jp_v = j - jmin[v];
1931 yvalid_ct = 0;
1932 j_sdr = j - sdr;
1933
1934 /* determine which children y we can legally transit to for v, j */
1935 for (y = cm->cfirst[v], yoffset = 0; y < (cm->cfirst[v] + cm->cnum[v]); y++, yoffset++)
1936 if((j_sdr) >= jmin[y] && ((j_sdr) <= jmax[y])) yvalidA[yvalid_ct++] = yoffset; /* is j-sdr is valid for state y? */
1937
1938 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) { /* for each valid d for v, j */
1939 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha */
1940 for (yvalid_idx = 0; yvalid_idx < yvalid_ct; yvalid_idx++) { /* for each valid child y, for v, j */
1941 yoffset = yvalidA[yvalid_idx];
1942 y = cm->cfirst[v] + yoffset;
1943 jp_y_sdr = j - jmin[y] - sdr;
1944
1945 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) { /* make sure d is valid for this v, j and y */
1946 dp_y_sd = d - sd - hdmin[y][jp_y_sdr];
1947 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1948 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1949 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], alpha[y][jp_y_sdr][dp_y_sd] + tsc_v[yoffset]);
1950 }
1951 }
1952 alpha[v][jp_v][dp_v] += esc_v[dsq[j]];
1953 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
1954 }
1955 }
1956 }
1957 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
1958 /* ML, MP, MR, D, S, E states cannot self transit, this means that all cells
1959 * in alpha[v] are independent of each other, only depending on alpha[y] for previously calc'ed y.
1960 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
1961 * for y { for j { for d { } } }
1962 */
1963 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
1964 yoffset = y - cm->cfirst[v];
1965 tsc = tsc_v[yoffset];
1966
1967 jn = ESL_MAX(jmin[v], jmin[y]+sdr);
1968 jx = ESL_MIN(jmax[v], jmax[y]+sdr);
1969 jpn = jn - jmin[v];
1970 jpx = jx - jmin[v];
1971 jp_y_sdr = jn - jmin[y] - sdr;
1972
1973 for (jp_v = jpn; jp_v <= jpx; jp_v++, jp_y_sdr++) {
1974 ESL_DASSERT1((jp_v >= 0 && jp_v <= (jmax[v]-jmin[v])));
1975 ESL_DASSERT1((jp_y_sdr >= 0 && jp_y_sdr <= (jmax[y]-jmin[y])));
1976
1977 dn = ESL_MAX(hdmin[v][jp_v], hdmin[y][jp_y_sdr] + sd);
1978 dx = ESL_MIN(hdmax[v][jp_v], hdmax[y][jp_y_sdr] + sd);
1979 dpn = dn - hdmin[v][jp_v];
1980 dpx = dx - hdmin[v][jp_v];
1981 dp_y_sd = dn - hdmin[y][jp_y_sdr] - sd;
1982
1983 for (dp_v = dpn; dp_v <= dpx; dp_v++, dp_y_sd++) {
1984 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
1985 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
1986 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], (alpha[y][jp_y_sdr][dp_y_sd] + tsc));;
1987 }
1988 }
1989 }
1990 /* add in emission score, if any */
1991 switch(cm->sttype[v]) {
1992 case ML_st:
1993 for (j = jmin[v]; j <= jmax[v]; j++) {
1994 jp_v = j - jmin[v];
1995 i = j - hdmin[v][jp_v] + 1;
1996 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
1997 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]];
1998 }
1999 break;
2000 case MR_st:
2001 for (j = jmin[v]; j <= jmax[v]; j++) {
2002 jp_v = j - jmin[v];
2003 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
2004 alpha[v][jp_v][dp_v] += esc_v[dsq[j]];
2005 }
2006 break;
2007 case MP_st:
2008 for (j = jmin[v]; j <= jmax[v]; j++) {
2009 jp_v = j - jmin[v];
2010 i = j - hdmin[v][jp_v] + 1;
2011 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
2012 alpha[v][jp_v][dp_v] += esc_v[dsq[i--]*cm->abc->Kp+dsq[j]];
2013 }
2014 default: /* no emission */
2015 break;
2016 }
2017 /* ensure all cells are >= IMPOSSIBLE */
2018 for (j = jmin[v]; j <= jmax[v]; j++) {
2019 ESL_DASSERT1((j >= 0 && j <= L));
2020 jp_v = j - jmin[v];
2021 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
2022 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
2023 }
2024 }
2025 else { /* B_st */
2026 y = cm->cfirst[v]; /* left subtree */
2027 z = cm->cnum[v]; /* right subtree */
2028
2029 /* Any valid j must be within both state v and state z's j band
2030 * I think jmin[v] <= jmin[z] is guaranteed by the way bands are
2031 * constructed, but we'll check anyway.
2032 */
2033 jn = (jmin[v] > jmin[z]) ? jmin[v] : jmin[z];
2034 jx = (jmax[v] < jmax[z]) ? jmax[v] : jmax[z];
2035 /* the main j loop */
2036 for (j = jn; j <= jx; j++) {
2037 ESL_DASSERT1((j >= 0 && j <= L));
2038 jp_v = j - jmin[v];
2039 jp_y = j - jmin[y];
2040 jp_z = j - jmin[z];
2041 kn = ((j-jmax[y]) > (hdmin[z][jp_z])) ? (j-jmax[y]) : hdmin[z][jp_z];
2042 kn = ESL_MAX(kn, 0); /* kn must be non-negative, added with fix to bug i36 */
2043 /* kn satisfies inequalities (1) and (3) (listed below)*/
2044 kx = ( jp_y < (hdmax[z][jp_z])) ? jp_y : hdmax[z][jp_z];
2045 /* kn satisfies inequalities (2) and (4) (listed below)*/
2046 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
2047 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
2048
2049 /* Find the first k value that implies a valid cell in the y and z decks.
2050 * This k must satisfy the following 6 inequalities (some may be redundant):
2051 * (1) k >= j-jmax[y];
2052 * (2) k <= j-jmin[y];
2053 * 1 and 2 guarantee (j-k) is within state y's j band
2054 *
2055 * (3) k >= hdmin[z][j-jmin[z]];
2056 * (4) k <= hdmax[z][j-jmin[z]];
2057 * 3 and 4 guarantee k is within z's j=(j), d band
2058 *
2059 * (5) k >= d-hdmax[y][j-jmin[y]-k];
2060 * (6) k <= d-hdmin[y][j-jmin[y]-k];
2061 * 5 and 6 guarantee (d-k) is within state y's j=(j-k) d band
2062 *
2063 * kn and kx were set above (outside (for (dp_v...) loop) that
2064 * satisfy 1-4 (b/c 1-4 are d-independent and k-independent)
2065 * RHS of inequalities 5 and 6 are dependent on k, so we check
2066 * for these within the next for loop.
2067 */
2068 for(k = kn; k <= kx; k++) {
2069 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
2070 /* for current k, all 6 inequalities have been satisified
2071 * so we know the cells corresponding to the platonic
2072 * matrix cells alpha[v][j][d], alpha[y][j-k][d-k], and
2073 * alpha[z][j][k] are all within the bands. These
2074 * cells correspond to alpha[v][jp_v][dp_v],
2075 * alpha[y][jp_y-k][d-hdmin[jp_y-k]-k],
2076 * and alpha[z][jp_z][k-hdmin[jp_z]];
2077 */
2078 kp_z = k-hdmin[z][jp_z];
2079 dp_y = d-hdmin[y][jp_y-k];
2080
2081 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], alpha[y][jp_y-k][dp_y - k] + alpha[z][jp_z][kp_z]);
2082 }
2083 }
2084 }
2085 }
2086 }
2087
2088 /* allow local begins, if nec */
2089 if((cm->flags & CMH_LOCAL_BEGIN) &&
2090 NOT_IMPOSSIBLE(cm->beginsc[v])) {
2091 if(L >= jmin[v] && L <= jmax[v]) {
2092 jp_v = L - jmin[v];
2093 Lp = L - hdmin[v][jp_v];
2094 if(L >= hdmin[v][jp_v] && L <= hdmax[v][jp_v]) {
2095 /* If we get here alpha[v][jp_v][Lp] is a valid cell
2096 * in the banded alpha matrix, corresponding to
2097 * alpha[v][L][L] in the platonic matrix.
2098 */
2099 /* Check for local begin getting us to the root.
2100 */
2101 bsc = FLogsum(bsc, (alpha[v][jp_v][Lp] + cm->beginsc[v]));
2102 }
2103 }
2104 }
2105 } /* end loop over all v */
2106
2107 /* include the bsc as part of alpha[0][jp_0][Lp_0] */
2108 if (NOT_IMPOSSIBLE(bsc)) {
2109 alpha[0][jp_0][Lp_0] = FLogsum(alpha[0][jp_0][Lp_0], bsc);
2110 }
2111
2112 #if eslDEBUGLEVEL >= 3
2113 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
2114 /* FILE *fp; fp = fopen("tmp.std_ihbmx", "w"); cm_hb_mx_Dump(fp, mx); fclose(fp); */
2115 #endif
2116
2117 sc = alpha[0][jp_0][Lp_0];
2118
2119 free(el_scA);
2120 free(yvalidA);
2121
2122 if(ret_sc != NULL) *ret_sc = sc;
2123
2124 ESL_DPRINTF1(("#DEBUG: cm_InsideAlignHB() return sc: %f\n", sc));
2125 return eslOK;
2126
2127 ERROR:
2128 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
2129 }
2130
2131 /* Function: cm_OptAccAlign()
2132 * Date: EPN, Sun Nov 18 20:45:22 2007
2133 * EPN, Sat Oct 1 05:57:49 2011 (updated to use emit matrices)
2134 *
2135 * Purpose: Run the Holmes/Durbin optimal accuracy algorithm
2136 * on a full target sequence 1..L, given a pre-filled
2137 * posterior matrix. Uses float log odds scores.
2138 * Non-banded version. See cm_OptAccAlignHB() for
2139 * HMM banded version.
2140 *
2141 * A CM_EMIT_MX matrix <emit_mx> must be passed in, filled by
2142 * cm_EmitterPosterior(), with values:
2143 *
2144 * l_pp[v][i]: log of the posterior probability that state v
2145 * emitted residue i leftwise either at (if a match state)
2146 * or *after* (if an insert state) the left consensus
2147 * position modeled by state v's node.
2148 *
2149 * r_pp[v][i]: log of the posterior probability that state v
2150 * emitted residue i rightwise either at (if a match
2151 * state) or *before* (if an insert state) the right
2152 * consensus position modeled by state v's node.
2153 *
2154 * l_pp[v] is NULL for states that do not emit leftwise
2155 * r_pp[v] is NULL for states that do not emit rightwise
2156 *
2157 * Additionally, a CM_MX DP matrix <mx> and CM_SHADOW_MX
2158 * <shmx> must be passed in. <shmx> will be expanded and
2159 * filled here with traceback pointers to allow the
2160 * optimally accurate parsetree to be recovered in
2161 * cm_alignT() and <mx> will be expanded and filled with the
2162 * optimal accuracy scores, where:
2163 *
2164 * mx->dp[v][j][d]: log of the sum of the posterior
2165 * probabilities of emitting residues i..j in the subtree
2166 * rooted at v.
2167 *
2168 * The optimally accurate parsetree, i.e. the parsetree that
2169 * maximizes the sum of the posterior probabilities of all
2170 * 1..L emitted residues, will be found.
2171 *
2172 * Previously (infernal versions 1.0->1.0.2) this function
2173 * (then named optimal_accuracy_align()) used the posterior
2174 * matrix instead of the emit matrices used here, and thus
2175 * did not determine (or at least was not guaranteed to
2176 * determine) the optimally accurate parsetree as defined
2177 * above. Instead it determined the parsetree that maximized
2178 * the probability mass that passed through emitting states.
2179 *
2180 * Local begins are handled the same as they are in
2181 * cm_CYKInsideAlign(), see that function's purpose for specifics.
2182 *
2183 * Note: Renamed from optimal_accuracy_align() [EPN, Wed Sep
2184 * 14 06:16:38 2011]. Corrected to use emit matrices
2185 * instead of a posterior matrix [EPN, Sat Oct 1 06:04:34
2186 * 2011].
2187 *
2188 * Args: cm - the model
2189 * errbuf - char buffer for reporting errors
2190 * dsq - the digitaized sequence [i0..j0]
2191 * L - length of the dsq
2192 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
2193 * mx - the DP matrix to fill in
2194 * shmx - the shadow matrix to fill in
2195 * emit_mx - pre-filled emit matrix
2196 * ret_b - RETURN: local begin state if local begins are on
2197 * ret_pp - RETURN: average posterior probability of aligned residues
2198 * in the optimally accurate parsetree
2199 *
2200 * Returns: <eslOK> on success.
2201 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
2202 * If !eslOK: alignment has been aborted, ret_* variables are not valid
2203 */
2204 int
2205 cm_OptAccAlign(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, CM_MX *mx, CM_SHADOW_MX *shmx,
2206 CM_EMIT_MX *emit_mx, int *ret_b, float *ret_pp)
2207 {
2208 int status;
2209 int v,y,z; /* indices for states */
2210 int j,d,i,k; /* indices in sequence dimensions */
2211 float sc; /* a temporary variable holding a score */
2212 float pp; /* average posterior probability of all emitted residues */
2213 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
2214 int b; /* best local begin state */
2215 float bsc; /* score for using the best local begin state */
2216 int sd; /* StateDelta(cm->sttype[v]) */
2217 int sdr; /* StateRightDelta(cm->sttype[v] */
2218 int j_sdr; /* j - sdr */
2219 int d_sd; /* d - sd */
2220 int have_el; /* TRUE if CM has local ends on, otherwise FALSE */
2221 int c; /* 64-bit counter */
2222
2223 /* the DP matrices */
2224 float ***alpha = mx->dp; /* pointer to the alpha DP matrix, we'll store optimal parse in */
2225 float **l_pp = emit_mx->l_pp; /* pointer to the prefilled posterior values for left emitters */
2226 float **r_pp = emit_mx->r_pp; /* pointer to the prefilled posterior values for right emitters */
2227 char ***yshadow = shmx->yshadow; /* pointer to the yshadow matrix */
2228 int ***kshadow = shmx->kshadow; /* pointer to the kshadow matrix */
2229
2230 /* Allocations and initializations */
2231 b = -1;
2232 bsc = IMPOSSIBLE;
2233
2234 /* grow the matrices based on the current sequence and bands */
2235 if((status = cm_mx_GrowTo (cm, mx, errbuf, L, size_limit)) != eslOK) return status;
2236 if((status = cm_shadow_mx_GrowTo(cm, shmx, errbuf, L, size_limit)) != eslOK) return status;
2237
2238 /* initialize all cells of the matrix */
2239 if( mx->ncells_valid > 0) esl_vec_FSet(mx->dp_mem, mx->ncells_valid, IMPOSSIBLE);
2240 if(shmx->y_ncells_valid > 0) for(c = 0; c < shmx->y_ncells_valid; c++) shmx->yshadow_mem[c] = USED_EL;
2241 /* for B states, shadow matrix holds k, length of right fragment, this will almost certainly be overwritten */
2242 if(shmx->k_ncells_valid > 0) esl_vec_ISet(shmx->kshadow_mem, shmx->k_ncells_valid, 0);
2243
2244 /* a special optimal accuracy specific step, initialize yshadow intelligently for d == 0
2245 * (necessary b/c zero length parsetees have 0 emits and so always score IMPOSSIBLE)
2246 */
2247 if((status = cm_InitializeOptAccShadowDZero(cm, errbuf, yshadow, L)) != eslOK) return status;
2248
2249 /* start with the EL state */
2250 have_el = (cm->flags & CMH_LOCAL_END) ? TRUE : FALSE;
2251 if(have_el && l_pp[cm->M] != NULL) {
2252 for (j = 0; j <= L; j++) {
2253 alpha[cm->M][j][0] = l_pp[cm->M][0];
2254 i = j;
2255 for (d = 1; d <= j; d++) {
2256 alpha[cm->M][j][d] = FLogsum(alpha[cm->M][j][d-1], l_pp[cm->M][i--]);
2257 }
2258 }
2259 }
2260
2261 /* Main recursion */
2262 for (v = cm->M-1; v >= 0; v--) {
2263 sd = StateDelta(cm->sttype[v]);
2264 sdr = StateRightDelta(cm->sttype[v]);
2265
2266 /* re-initialize if we can do a local end from v */
2267 if(have_el && NOT_IMPOSSIBLE(cm->endsc[v])) {
2268 for (j = 0; j <= L; j++) {
2269 /* copy values from saved EL deck */
2270 for (d = sd; d <= j; d++) {
2271 alpha[v][j][d] = alpha[cm->M][j-sdr][d-sd];
2272 /* yshadow[v][j][d] remains USED_EL */
2273 }
2274 }
2275 }
2276 /* note there's no E state update here, those cells all remain IMPOSSIBLE */
2277
2278 /* we have to separate out IL_st and IR_st because IL use emit_mx->l_pp and IR use emit_mx->r_pp */
2279 if(cm->sttype[v] == IL_st) {
2280 /* update alpha[v][j][d] cells, for IL states, loop nesting order is:
2281 * for j { for d { for y { } } } because they can self transit, and a
2282 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
2283 * before can start calc'ing for alpha[v][j][d+1] */
2284 for (j = 1; j <= L; j++) {
2285 i = j;
2286 d_sd = 0;
2287 for (d = 1; d <= j; d++, d_sd++, i--) {
2288 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
2289 y = cm->cfirst[v] + yoffset;
2290 if ((sc = alpha[y][j][d_sd]) > alpha[v][j][d]) {
2291 alpha[v][j][d] = sc;
2292 yshadow[v][j][d] = yoffset;
2293 }
2294 }
2295 alpha[v][j][d] = FLogsum(alpha[v][j][d], l_pp[v][i]);
2296 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
2297 /* special case if local ends are off: explicitly disallow transitions to EL that require EL emissions
2298 * (we do allow an 'illegal' transition to EL in OptAcc but only if no EL emissions are req'd)
2299 */
2300 if((! have_el) && yshadow[v][j][d] == USED_EL && d > sd) {
2301 alpha[v][j][d] = IMPOSSIBLE;
2302 }
2303 }
2304 }
2305 }
2306 if(cm->sttype[v] == IR_st) {
2307 /* IR: same loop nesting order as for IL for same reason, see IL comment above */
2308 j_sdr = 0;
2309 for (j = 1; j <= L; j++, j_sdr++) {
2310 d_sd = 0;
2311 for (d = 1; d <= j; d++, d_sd++) {
2312 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
2313 y = cm->cfirst[v] + yoffset;
2314 if ((sc = alpha[y][j_sdr][d_sd]) > alpha[v][j][d]) {
2315 alpha[v][j][d] = sc;
2316 yshadow[v][j][d] = yoffset;
2317 }
2318 }
2319 alpha[v][j][d] = FLogsum(alpha[v][j][d], r_pp[v][j]);
2320 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
2321 /* special case if local ends are off: explicitly disallow transitions to EL that require EL emissions
2322 * (we do allow an 'illegal' transition to EL in OptAcc but only if no EL emissions are req'd)
2323 */
2324 if((! have_el) && yshadow[v][j][d] == USED_EL && d > sd) {
2325 alpha[v][j][d] = IMPOSSIBLE;
2326 }
2327 }
2328 }
2329 }
2330 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
2331 /* ML, MP, MR, D, S, E states cannot self transit, so all cells
2332 * in alpha[v] are independent of each other, only depending on
2333 * alpha[y] for previously calc'ed y. We can do the for loops
2334 * in any nesting order, this implementation does what I think
2335 * is most efficient: for y { for j { for d { } } }.
2336 */
2337 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
2338 yoffset = y - cm->cfirst[v];
2339 j_sdr = 0;
2340 for (j = sdr; j <= L; j++, j_sdr++) {
2341 d_sd = 0;
2342 for (d = sd; d <= j; d++, d_sd++) {
2343 if((sc = alpha[y][j_sdr][d_sd]) > alpha[v][j][d]) {
2344 alpha[v][j][d] = sc;
2345 yshadow[v][j][d] = yoffset;
2346 }
2347 }
2348 }
2349 }
2350 /* add in emission score, if any */
2351 switch(cm->sttype[v]) {
2352 case ML_st:
2353 for (j = 1; j <= L; j++) {
2354 i = j;
2355 for (d = sd; d <= j; d++, i--) {
2356 alpha[v][j][d] = FLogsum(alpha[v][j][d], l_pp[v][i]);
2357 }
2358 }
2359 break;
2360 case MR_st:
2361 for (j = 1; j <= L; j++) {
2362 for (d = sd; d <= j; d++) {
2363 alpha[v][j][d] = FLogsum(alpha[v][j][d], r_pp[v][j]);
2364 }
2365 }
2366 break;
2367 case MP_st:
2368 for (j = 2; j <= L; j++) {
2369 i = j-1;
2370 for (d = sd; d <= j; d++, i--) {
2371 alpha[v][j][d] = FLogsum(alpha[v][j][d], FLogsum(l_pp[v][i], r_pp[v][j]));
2372 }
2373 }
2374 break;
2375 default:
2376 break;
2377 }
2378 /* ensure all cells are >= IMPOSSIBLE */
2379 for (j = 0; j <= L; j++) {
2380 for (d = 0; d <= j; d++)
2381 alpha[v][j][d] = ESL_MAX(alpha[v][j][d], IMPOSSIBLE);
2382 }
2383 /* special case if local ends are off: explicitly disallow transitions to EL that require EL emissions
2384 * (we do allow an 'illegal' transition to EL in OptAcc but only if no EL emissions are req'd)
2385 */
2386 if(! have_el && sd > 0) { /* this is only necessary for emitters (MP, ML, MR in this context) */
2387 for (j = 0; j <= L; j++) {
2388 for (d = sd+1; d <= j; d++) {
2389 if(yshadow[v][j][d] == USED_EL) alpha[v][j][d] = IMPOSSIBLE;
2390 }
2391 }
2392 }
2393 }
2394 else { /* B_st */
2395 y = cm->cfirst[v]; /* left subtree */
2396 z = cm->cnum[v]; /* right subtree */
2397 for (j = 0; j <= L; j++) {
2398 for (d = 0; d <= j; d++) {
2399 for (k = 0; k <= d; k++) {
2400 if ((sc = FLogsum(alpha[y][j-k][d-k], alpha[z][j][k])) > alpha[v][j][d])
2401 {
2402 if(((d == k) || (NOT_IMPOSSIBLE(alpha[y][j-k][d-k]))) && /* left subtree can only be IMPOSSIBLE if it has length 0 (in which case d==k, and d-k=0) */
2403 ((k == 0) || (NOT_IMPOSSIBLE(alpha[z][j][k])))) /* right subtree can only be IMPOSSIBLE if it has length 0 (in which case k==0) */
2404 {
2405 alpha[v][j][d] = sc;
2406 kshadow[v][j][d] = k;
2407
2408 /* Note: we take the logsum here, because we're keeping track of the
2409 * log of the summed probability of emitting all residues up to this
2410 * point, (from i..j) from left subtree (i=j-d+1..j-k) and from the
2411 * right subtree. (j-k+1..j)
2412 *
2413 * EPN, Tue Nov 17 10:53:13 2009 Bug fix post infernal-1.0.2 release in "if(((sc = FLogsum..."
2414 * statement above. This is i15 in BUGTRAX, fixed as of svn revision 3056 in infernal 1.0 release
2415 * branch, and revision 3057 in infernal trunk. Bug description: See analogous section and comment
2416 * in cm_OptAccAlignHB() above. In that function, in very rare cases (1 case in the 1.1 million SSU
2417 * sequences in release 10_15 of RDP), this step will add two alpha values (alpha[y][j-k][d-k] for
2418 * left subtree, and alpha[z][j][k] for right subtree) where one of them is IMPOSSIBLE and the
2419 * corresponding subtree length ('d-k' in left subtree, or 'k' if right subtree) is non-zero, yet
2420 * their FLogsum (which equals the value of the non-IMPOSSIBLE cell) is sufficiently high to be part
2421 * of the optimally accurate traceback. This will probably cause a seg fault later b/c it implies a
2422 * left or right subtree that is IMPOSSIBLE. It is okay if an IMPOSSIBLE scoring subtree has length
2423 * 0 b/c 0 residues will contribute nothing to the summed log probability (nothing corresponds to a
2424 * score of IMPOSSIBLE). We handle this case here by explicitly checking if either left or right
2425 * subtree cell is IMPOSSIBLE with non-zero length before reassigning alpha[v][j][d]. I'm not sure
2426 * if this is even possible in the non-banded function (this function), but I included the analogous
2427 * fix here (the NOT_IMPOSSIBLE() calls) in case it was ever possible. This will slow down the
2428 * implementation, but I'd rather err on the side of caution here, since we don't care so much about
2429 * speed in the non-banded function, and b/c finding this bug again if the non-banded function can
2430 * have the bug would be a pain in the ass.
2431 */
2432 }
2433 }
2434 }
2435 }
2436 }
2437 }
2438 /* allow local begins, if nec */
2439 if((cm->flags & CMH_LOCAL_BEGIN) && (NOT_IMPOSSIBLE(cm->beginsc[v]))) {
2440 if (alpha[v][L][L] > bsc) {
2441 b = v;
2442 bsc = alpha[v][L][L];
2443 }
2444 }
2445 } /* finished calculating deck v. */
2446
2447 /* If local begins are on, the only way out of ROOT_S is via a local
2448 * begin, so update the optimal score and put a flag in the shadow
2449 * matrix telling cm_alignT() to use the b we return.
2450 *
2451 * Note that because we're in OptAcc alpha[0][L][L] will already be
2452 * equal to bsc because transition scores (and thus impossible
2453 * transitions out of ROOT_S) have no effect on the score, so
2454 * whereas we can check to see if 'bsc > alpha[0][L][L]' at an
2455 * analogous point in CYK before setting the USED_LOCAL_BEGIN
2456 * flag, we can't here because it would be FALSE.
2457 */
2458 if(NOT_IMPOSSIBLE(bsc) && (cm->flags & CMH_LOCAL_BEGIN)) {
2459 alpha[0][L][L] = bsc;
2460 yshadow[0][L][L] = USED_LOCAL_BEGIN;
2461 }
2462
2463 #if eslDEBUGLEVEL >= 3
2464 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
2465 /* FILE *fp1; fp1 = fopen("tmp.std_oamx", "w"); cm_mx_Dump(fp1, mx); fclose(fp1); */
2466 /* FILE *fp2; fp2 = fopen("tmp.std_oashmx", "w"); cm_shadow_mx_Dump(fp2, cm, shmx); fclose(fp2); */
2467 #endif
2468
2469 sc = alpha[0][L][L];
2470
2471 /* convert sc, a log probability, into the average posterior probability of all L aligned residues */
2472 pp = sreEXP2(sc) / (float) L;
2473
2474 if(ret_b != NULL) *ret_b = b; /* b is -1 if local ends are off */
2475 if(ret_pp != NULL) *ret_pp = pp;
2476
2477 ESL_DPRINTF1(("#DEBUG: cm_OptAccAlign return pp: %f\n", pp));
2478 return eslOK;
2479 }
2480
2481
2482 /* Function: cm_OptAccAlignHB()
2483 * Date: EPN, Thu Nov 15 10:48:37 2007
2484 *
2485 * Purpose: Same as cm_OptAccAlign() but HMM bands are used.
2486 * See cm_OptAccAlign()'s Purpose for more information.
2487 *
2488 * Note: Renamed from optimal_accuracy_align_hb() [EPN, Wed Sep 14 06:16:06 2011].
2489 *
2490 * Args: cm - the model
2491 * errbuf - char buffer for reporting errors
2492 * dsq - the digitaized sequence [i0..j0]
2493 * L - length of the dsq
2494 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
2495 * mx - the DP matrix to fill in
2496 * shmx - the shadow matrix to fill in
2497 * emit_mx - pre-filled emit matrix
2498 * ret_b - RETURN: local begin state if local begins are on
2499 * ret_pp - RETURN: average posterior probability of aligned residues
2500 * in the optimally accurate parsetree
2501 *
2502 * Returns: <eslOK> on success.
2503 *
2504 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
2505 * If !eslOK: alignment has been aborted, ret_* variables are not valid
2506 */
2507 int
2508 cm_OptAccAlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, CM_HB_MX *mx, CM_HB_SHADOW_MX *shmx,
2509 CM_HB_EMIT_MX *emit_mx, int *ret_b, float *ret_pp)
2510 {
2511 int status;
2512 int v,y,z; /* indices for states */
2513 int j,d,i,k; /* indices in sequence dimensions */
2514 float sc; /* a temporary variable holding a score */
2515 float pp; /* average posterior probability of all emitted residues */
2516 int yoffset; /* y=base+offset -- counter in child states that v can transit to */
2517 int b; /* best local begin state */
2518 float bsc; /* score for using the best local begin state */
2519 int *yvalidA; /* [0..MAXCONNECT-1] TRUE if v->yoffset is legal transition (within bands) */
2520 int jp_0; /* L offset in ROOT_S's (v==0) j band */
2521 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
2522 int Lp; /* L offset in any state v's d band */
2523 int sd; /* StateDelta(cm->sttype[v]) */
2524 int sdr; /* StateRightDelta(cm->sttype[v] */
2525 int have_el; /* TRUE if CM has local ends on, otherwise FALSE */
2526 int64_t c; /* 64-bit int counter */
2527
2528 /* indices used for handling band-offset issues, and in the depths of the DP recursion */
2529 int ip_v; /* offset i index for state v */
2530 int jp_v, jp_y, jp_z; /* offset j index for states v, y, z */
2531 int jp_y_sdr; /* jp_y - sdr */
2532 int j_sdr; /* j - sdr */
2533 int jn, jx; /* current minimum/maximum j allowed */
2534 int jpn, jpx; /* minimum/maximum jp_v */
2535 int dp_v, dp_y; /* d index for state v/y in alpha w/mem eff bands */
2536 int dn, dx; /* current minimum/maximum d allowed */
2537 int dp_y_sd; /* dp_y - sd */
2538 int dpn, dpx; /* minimum/maximum dp_v */
2539 int kp_z; /* k (in the d dim) index for state z in alpha w/mem eff bands */
2540 int jp_y_minus_k; /* jp_y - k, used in one loop, stored to avoid calc'ing twice */
2541 int dp_y_minus_k; /* dp_y - k, used in one loop, stored to avoid calc'ing twice */
2542 int kn, kx; /* current minimum/maximum k value */
2543 int yvalid_idx; /* for keeping track of which children are valid */
2544 int yvalid_ct; /* for keeping track of which children are valid */
2545
2546 /* variables used for memory efficient bands */
2547 /* ptrs to cp9b info, for convenience */
2548 CP9Bands_t *cp9b = cm->cp9b;
2549 int *imin = cp9b->imin;
2550 int *imax = cp9b->imax;
2551 int *jmin = cp9b->jmin;
2552 int *jmax = cp9b->jmax;
2553 int **hdmin = cp9b->hdmin;
2554 int **hdmax = cp9b->hdmax;
2555
2556 /* the DP matrices */
2557 float ***alpha = mx->dp; /* pointer to the alpha DP matrix, we'll store optimal parse in */
2558 float **l_pp = emit_mx->l_pp; /* pointer to the prefilled posterior values for left emitters */
2559 float **r_pp = emit_mx->r_pp; /* pointer to the prefilled posterior values for right emitters */
2560 char ***yshadow = shmx->yshadow; /* pointer to the yshadow matrix */
2561 int ***kshadow = shmx->kshadow; /* pointer to the kshadow matrix */
2562
2563 /* Allocations and initializations */
2564 b = -1;
2565 bsc = IMPOSSIBLE;
2566 if (cp9b->jmin[0] > L || cp9b->jmax[0] < L)
2567 ESL_FAIL(eslEINVAL, errbuf, "cm_OptAccAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cp9b->jmin[0], cp9b->jmax[0]);
2568 jp_0 = L - jmin[0];
2569 if (cp9b->hdmin[0][jp_0] > L || cp9b->hdmax[0][jp_0] < L)
2570 ESL_FAIL(eslEINVAL, errbuf, "cm_OptAccAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cp9b->hdmin[0][jp_0], cp9b->hdmax[0][jp_0]);
2571 Lp_0 = L - hdmin[0][jp_0];
2572
2573 /* grow the matrices based on the current sequence and bands */
2574 if((status = cm_hb_mx_GrowTo (cm, mx, errbuf, cp9b, L, size_limit)) != eslOK) return status;
2575 if((status = cm_hb_shadow_mx_GrowTo(cm, shmx, errbuf, cp9b, L, size_limit)) != eslOK) return status;
2576
2577 /* initialize all cells of the matrix */
2578 if( mx->ncells_valid > 0) esl_vec_FSet(mx->dp_mem, mx->ncells_valid, IMPOSSIBLE);
2579 if(shmx->y_ncells_valid > 0) for(c = 0; c < shmx->y_ncells_valid; c++) shmx->yshadow_mem[c] = USED_EL;
2580 /* for B states, shadow matrix holds k, length of right fragment, this will almost certainly be overwritten */
2581 if(shmx->k_ncells_valid > 0) esl_vec_ISet(shmx->kshadow_mem, shmx->k_ncells_valid, 0);
2582
2583 /* a special optimal accuracy specific step, initialize yshadow intelligently for d == 0
2584 * (necessary b/c zero length parsetees have 0 emits and so always score IMPOSSIBLE)
2585 */
2586 if((status = cm_InitializeOptAccShadowDZeroHB(cm, cp9b, errbuf, yshadow, L)) != eslOK) return status;
2587
2588 /* start with the EL state (remember, cm->M deck is non-banded) */
2589 have_el = (cm->flags & CMH_LOCAL_END) ? TRUE : FALSE;
2590 if(have_el && l_pp[cm->M] != NULL) {
2591 for (j = 0; j <= L; j++) {
2592 alpha[cm->M][j][0] = l_pp[cm->M][0];
2593 i = j;
2594 for (d = 1; d <= j; d++) {
2595 alpha[cm->M][j][d] = FLogsum(alpha[cm->M][j][d-1], l_pp[cm->M][i--]);
2596 }
2597 }
2598 }
2599
2600 /* yvalidA[0..cnum[v]] will hold TRUE for states y for which a transition is legal
2601 * (some transitions are impossible due to the bands) */
2602 ESL_ALLOC(yvalidA, sizeof(int) * MAXCONNECT);
2603 esl_vec_ISet(yvalidA, MAXCONNECT, FALSE);
2604
2605 /* Main recursion */
2606 for (v = cm->M-1; v >= 0; v--) {
2607 sd = StateDelta(cm->sttype[v]);
2608 sdr = StateRightDelta(cm->sttype[v]);
2609
2610 /* re-initialize if we can do a local end from v */
2611 if(have_el && NOT_IMPOSSIBLE(cm->endsc[v])) {
2612 for (j = jmin[v]; j <= jmax[v]; j++) {
2613 jp_v = j - jmin[v];
2614 /* copy values from saved EL deck */
2615 for(d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
2616 dp_v = d - hdmin[v][jp_v];
2617 alpha[v][jp_v][dp_v] = alpha[cm->M][j-sdr][d-sd];
2618 /* yshadow[v][jp_v][dp_v] remains USED_EL */
2619 }
2620 }
2621 }
2622 /* note there's no E state update here, those cells all remain IMPOSSIBLE */
2623
2624 /* we could separate out IL_st and IR_st, but I don't it makes a significant difference in run time */
2625 if(cm->sttype[v] == IL_st || cm->sttype[v] == IR_st) {
2626 /* update alpha[v][jp_v][dp_v] cells, for IL/IR states, loop nesting order is:
2627 * for j { for d { for y { } } } because they can self transit, and a
2628 * alpha[v][j][d] cell must be complete (that is we must have looked at all children y)
2629 * before can start calc'ing for alpha[v][j][d+1] */
2630 for (j = jmin[v]; j <= jmax[v]; j++) {
2631 jp_v = j - jmin[v];
2632 yvalid_ct = 0;
2633 j_sdr = j - sdr;
2634
2635 /* determine which children y we can legally transit to for v, j */
2636 for (y = cm->cfirst[v], yoffset = 0; y < (cm->cfirst[v] + cm->cnum[v]); y++, yoffset++)
2637 if((j_sdr) >= jmin[y] && ((j_sdr) <= jmax[y])) yvalidA[yvalid_ct++] = yoffset; /* is j-sdr valid for state y? */
2638
2639 i = j - hdmin[v][jp_v] + 1;
2640 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++, i--) { /* for each valid d for v, j */
2641 /*printf("v: %4d j: %4d (%4d..%4d) d: %4d (%4d..%4d) i: %4d (%4d..%4d)\n",
2642 v, j, jmin[v], jmax[v], d, hdmin[v][jp_v], hdmax[v][jp_v], i, imin[v], imax[v]);*/
2643 assert(i >= imin[v] && i <= imax[v]);
2644 ESL_DASSERT1((i >= imin[v] && i <= imax[v]));
2645 ip_v = i - imin[v]; /* i index for state v in emit_mx->l_pp */
2646 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha */
2647 for (yvalid_idx = 0; yvalid_idx < yvalid_ct; yvalid_idx++) { /* for each valid child y, for v, j */
2648 yoffset = yvalidA[yvalid_idx];
2649 y = cm->cfirst[v] + yoffset;
2650 jp_y_sdr = j - jmin[y] - sdr;
2651
2652 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) { /* make sure d is valid for this v, j and y */
2653 dp_y_sd = d - sd - hdmin[y][jp_y_sdr];
2654 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
2655 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
2656 if ((sc = alpha[y][jp_y_sdr][dp_y_sd]) > alpha[v][jp_v][dp_v])
2657 {
2658 alpha[v][jp_v][dp_v] = sc;
2659 yshadow[v][jp_v][dp_v] = yoffset;
2660 }
2661 }
2662 }
2663 if(cm->sttype[v] == IL_st) alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], l_pp[v][ip_v]);
2664 else alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], r_pp[v][jp_v]);
2665 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
2666 /* special case if local ends are off: explicitly disallow transitions to EL that require EL emissions
2667 * (we do allow an 'illegal' transition to EL in OptAcc but only if no EL emissions are req'd)
2668 */
2669 if((! have_el) && yshadow[v][jp_v][dp_v] == USED_EL && d > sd) {
2670 alpha[v][jp_v][dp_v] = IMPOSSIBLE;
2671 }
2672 }
2673 }
2674 }
2675 else if(cm->sttype[v] != B_st) { /* entered if state v is (! IL && ! IR && ! B) */
2676 /* ML, MP, MR, D, S, E states cannot self transit, this means that all cells
2677 * in alpha[v] are independent of each other, only depending on alpha[y] for previously calc'ed y.
2678 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
2679 * for y { for j { for d { } } }
2680 */
2681 for (y = cm->cfirst[v]; y < (cm->cfirst[v] + cm->cnum[v]); y++) {
2682 yoffset = y - cm->cfirst[v];
2683
2684 jn = ESL_MAX(jmin[v], jmin[y]+sdr);
2685 jx = ESL_MIN(jmax[v], jmax[y]+sdr);
2686 jpn = jn - jmin[v];
2687 jpx = jx - jmin[v];
2688 jp_y_sdr = jn - jmin[y] - sdr;
2689
2690 for (jp_v = jpn; jp_v <= jpx; jp_v++, jp_y_sdr++) {
2691 ESL_DASSERT1((jp_v >= 0 && jp_v <= (jmax[v]-jmin[v])));
2692 ESL_DASSERT1((jp_y_sdr >= 0 && jp_y_sdr <= (jmax[y]-jmin[y])));
2693
2694 dn = ESL_MAX(hdmin[v][jp_v], hdmin[y][jp_y_sdr] + sd);
2695 dx = ESL_MIN(hdmax[v][jp_v], hdmax[y][jp_y_sdr] + sd);
2696 dpn = dn - hdmin[v][jp_v];
2697 dpx = dx - hdmin[v][jp_v];
2698 dp_y_sd = dn - hdmin[y][jp_y_sdr] - sd;
2699
2700 for (dp_v = dpn; dp_v <= dpx; dp_v++, dp_y_sd++) {
2701 ESL_DASSERT1((dp_v >= 0 && dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v])));
2702 ESL_DASSERT1((dp_y_sd >= 0 && dp_y_sd <= (hdmax[y][jp_y_sdr] - hdmin[y][jp_y_sdr])));
2703 if((sc = alpha[y][jp_y_sdr][dp_y_sd]) > alpha[v][jp_v][dp_v]) {
2704 alpha[v][jp_v][dp_v] = sc;
2705 yshadow[v][jp_v][dp_v] = yoffset;
2706 }
2707 }
2708 }
2709 }
2710 /* add in emission score, if any */
2711 switch(cm->sttype[v]) {
2712 case ML_st:
2713 for (j = jmin[v]; j <= jmax[v]; j++) {
2714 jp_v = j - jmin[v];
2715 i = j - hdmin[v][jp_v] + 1;
2716 ip_v = i - imin[v];
2717 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++, ip_v--) {
2718 /*printf("v: %4d j: %4d (%4d..%4d) d: %4d (%4d..%4d) i: %4d (%4d..%4d)\n",
2719 v, j, jmin[v], jmax[v], d, hdmin[v][jp_v], hdmax[v][jp_v], i, imin[v], imax[v]);*/
2720 assert(ip_v >= 0 && ip_v <= (imax[v] - imin[v]));
2721 ESL_DASSERT1((ip_v >= 0 && ip_v <= (imax[v] - imin[v])));
2722 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], l_pp[v][ip_v]);
2723 }
2724 }
2725 break;
2726 case MR_st:
2727 for (j = jmin[v]; j <= jmax[v]; j++) {
2728 jp_v = j - jmin[v];
2729 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++) {
2730 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], r_pp[v][jp_v]);
2731 }
2732 }
2733 break;
2734 case MP_st:
2735 for (j = jmin[v]; j <= jmax[v]; j++) {
2736 jp_v = j - jmin[v];
2737 i = j - hdmin[v][jp_v] + 1;
2738 ip_v = i - imin[v];
2739 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++, ip_v--) {
2740 assert(ip_v >= 0 && ip_v <= (imax[v] - imin[v]));
2741 ESL_DASSERT1((ip_v >= 0 && ip_v <= (imax[v] - imin[v])));
2742 alpha[v][jp_v][dp_v] = FLogsum(alpha[v][jp_v][dp_v], FLogsum(l_pp[v][ip_v], r_pp[v][jp_v]));
2743 }
2744 }
2745 break;
2746 default:
2747 break;
2748 }
2749 /* ensure all cells are >= IMPOSSIBLE */
2750 for (j = jmin[v]; j <= jmax[v]; j++) {
2751 jp_v = j - jmin[v];
2752 for (dp_v = 0; dp_v <= (hdmax[v][jp_v] - hdmin[v][jp_v]); dp_v++)
2753 alpha[v][jp_v][dp_v] = ESL_MAX(alpha[v][jp_v][dp_v], IMPOSSIBLE);
2754 }
2755 /* special case if local ends are off: explicitly disallow transitions to EL that require EL emissions
2756 * (we do allow an 'illegal' transition to EL in OptAcc but only if no EL emissions are req'd)
2757 */
2758 if(! have_el && sd > 0) { /* this is only necessary for emitters (MP, ML, MR in this context) */
2759 for (j = jmin[v]; j <= jmax[v]; j++) {
2760 jp_v = j - jmin[v];
2761 d = ESL_MAX(sd+1, hdmin[v][jp_v]);
2762 dp_v = d - hdmin[v][jp_v];
2763 for (; d <= hdmax[v][jp_v]; d++) {
2764 if(yshadow[v][jp_v][dp_v] == USED_EL) alpha[v][jp_v][dp_v] = IMPOSSIBLE;
2765 dp_v++;
2766 }
2767 }
2768 }
2769 }
2770 else { /* B_st */
2771 y = cm->cfirst[v]; /* left subtree */
2772 z = cm->cnum[v]; /* right subtree */
2773
2774 /* Any valid j must be within both state v and state z's j band
2775 * I think jmin[v] <= jmin[z] is guaranteed by the way bands are
2776 * constructed, but we'll check anyway.
2777 */
2778 jn = (jmin[v] > jmin[z]) ? jmin[v] : jmin[z];
2779 jx = (jmax[v] < jmax[z]) ? jmax[v] : jmax[z];
2780 /* the main j loop */
2781 for (j = jn; j <= jx; j++) {
2782 jp_v = j - jmin[v];
2783 jp_y = j - jmin[y];
2784 jp_z = j - jmin[z];
2785 kn = ((j-jmax[y]) > (hdmin[z][jp_z])) ? (j-jmax[y]) : hdmin[z][jp_z];
2786 kn = ESL_MAX(kn, 0); /* kn must be non-negative, added with fix to bug i36 */
2787 /* kn satisfies inequalities (1) and (3) (listed below)*/
2788 kx = ( jp_y < (hdmax[z][jp_z])) ? jp_y : hdmax[z][jp_z];
2789 /* kn satisfies inequalities (2) and (4) (listed below)*/
2790 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
2791 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
2792
2793 /* Find the first k value that implies a valid cell in the y and z decks.
2794 * This k must satisfy the following 6 inequalities (some may be redundant):
2795 * (1) k >= j-jmax[y];
2796 * (2) k <= j-jmin[y];
2797 * 1 and 2 guarantee (j-k) is within state y's j band
2798 *
2799 * (3) k >= hdmin[z][j-jmin[z]];
2800 * (4) k <= hdmax[z][j-jmin[z]];
2801 * 3 and 4 guarantee k is within z's j=(j), d band
2802 *
2803 * (5) k >= d-hdmax[y][j-jmin[y]-k];
2804 * (6) k <= d-hdmin[y][j-jmin[y]-k];
2805 * 5 and 6 guarantee (d-k) is within state y's j=(j-k) d band
2806 *
2807 * kn and kx were set above (outside (for (dp_v...) loop) that
2808 * satisfy 1-4 (b/c 1-4 are d-independent and k-independent)
2809 * RHS of inequalities 5 and 6 are dependent on k, so we check
2810 * for these within the next for loop.
2811 */
2812 for(k = kn; k <= kx; k++) {
2813 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
2814 /* for current k, all 6 inequalities have been satisified
2815 * so we know the cells corresponding to the platonic
2816 * matrix cells alpha[v][j][d], alpha[y][j-k][d-k], and
2817 * alpha[z][j][k] are all within the bands. These
2818 * cells correspond to alpha[v][jp_v][dp_v],
2819 * alpha[y][jp_y-k][d-hdmin[jp_y-k]-k],
2820 * and alpha[z][jp_z][k-hdmin[jp_z]];
2821 */
2822 kp_z = k-hdmin[z][jp_z];
2823 dp_y = d-hdmin[y][jp_y-k];
2824 jp_y_minus_k = jp_y-k;
2825 dp_y_minus_k = dp_y-k;
2826
2827 if((sc = FLogsum(alpha[y][jp_y_minus_k][dp_y_minus_k], alpha[z][jp_z][kp_z])) > alpha[v][jp_v][dp_v])
2828 {
2829 if(((d == k) || (NOT_IMPOSSIBLE(alpha[y][jp_y_minus_k][dp_y_minus_k]))) && /* left subtree can only be IMPOSSIBLE if it has length 0 (in which case d==k, and d-k=0) */
2830 ((k == 0) || (NOT_IMPOSSIBLE(alpha[z][jp_z][kp_z])))) /* right subtree can only be IMPOSSIBLE if it has length 0 (in which case k==0) */
2831 {
2832 alpha[v][jp_v][dp_v] = sc;
2833 kshadow[v][jp_v][dp_v] = k;
2834 /* Note: we take the logsum here, because we're
2835 * keeping track of the log of the summed probability
2836 * of emitting all residues up to this point, (from
2837 * i..j) from left subtree (i=j-d+1..j-k) and from the
2838 * right subtree. (j-k+1..j).
2839 *
2840 * EPN, Tue Nov 17 09:57:59 2009:
2841 * Bug fix post infernal-1.0.2 release.
2842 * Addition of 2-line if statement beginning
2843 * "if(((d == k...)" This is i15 in BUGTRAX,
2844 * fixed as of svn revision 3056 in infernal 1.0
2845 * release branch, and revision 3057 in infernal
2846 * trunk.
2847 * Bug description: In very rare cases (1 case
2848 * in the 1.1 million SSU sequences in release
2849 * 10_15 of RDP), this step will add two alpha
2850 * values (alpha[y][jp_y_minus_k][dp_y_minus_k]
2851 * for left subtree, and alpha[z][jp_z][kp_z]
2852 * for right subtree) where one of them is
2853 * IMPOSSIBLE and the corresponding subtree
2854 * length ('d-k' in left subtree, or 'k' if right
2855 * subtree) is non-zero, yet their FLogsum
2856 * (which equals the value of the non-IMPOSSIBLE
2857 * cell) is sufficiently high to be part of the
2858 * optimally accurate traceback. This will
2859 * probably cause a seg fault later b/c it
2860 * implies a left or right subtree that is
2861 * IMPOSSIBLE. It is okay if an IMPOSSIBLE
2862 * scoring subtree has length 0 b/c 0 residues
2863 * will contribute nothing to the summed log
2864 * probability (nothing corresponds to a score
2865 * of IMPOSSIBLE). We handle this case here by
2866 * explicitly checking if either left or right
2867 * subtree cell is IMPOSSIBLE with non-zero
2868 * length before reassigning
2869 * alpha[v][jp_v][dp_v].
2870 */
2871 }
2872 }
2873 }
2874 }
2875 }
2876 }
2877 }
2878 /* allow local begins, if nec */
2879 if((cm->flags & CMH_LOCAL_BEGIN) && (NOT_IMPOSSIBLE(cm->beginsc[v]))) {
2880 if(L >= jmin[v] && L <= jmax[v]) {
2881 jp_v = L - jmin[v];
2882 Lp = L - hdmin[v][jp_v];
2883 if(L >= hdmin[v][jp_v] && L <= hdmax[v][jp_v]) {
2884 /* If we get here alpha[v][jp_v][Wp] is a valid cell
2885 * in the banded alpha matrix, corresponding to
2886 * alpha[v][j0][W] in the platonic matrix.
2887 */
2888 /* Check for local begin getting us to the root.
2889 * This is "off-shadow": if/when we trace back, we'll handle this
2890 * case separately (and we'll know to do it because we'll immediately
2891 * see a USED_LOCAL_BEGIN flag in the shadow matrix, telling us
2892 * to jump right to state b; see below)
2893 */
2894 if (alpha[v][jp_v][Lp] > bsc) {
2895 b = v;
2896 bsc = alpha[v][jp_v][Lp];
2897 }
2898 }
2899 }
2900 }
2901 } /* end loop over all v */
2902
2903 /* If local begins are on, the only way out of ROOT_S is via a local
2904 * begin, so update the optimal score and put a flag in the shadow
2905 * matrix telling cm_alignT() to use the b we return.
2906 *
2907 * Note that because we're in OptAcc alpha[0][L][L] will already be
2908 * equal to bsc because transition scores (and thus impossible
2909 * transitions out of ROOT_S) have no effect on the score, so
2910 * whereas we can check to see if 'bsc > alpha[0][L][L]' at an
2911 * analogous point in CYK before setting the USED_LOCAL_BEGIN
2912 * flag, we can't here because it would be FALSE.
2913 */
2914 if(NOT_IMPOSSIBLE(bsc) && (cm->flags & CMH_LOCAL_BEGIN)) {
2915 alpha[0][jp_0][Lp_0] = bsc;
2916 yshadow[0][jp_0][Lp_0] = USED_LOCAL_BEGIN;
2917 }
2918
2919 #if eslDEBUGLEVEL >= 3
2920 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
2921 /* FILE *fp1; fp1 = fopen("tmp.std_oahbmx", "w"); cm_hb_mx_Dump(fp1, mx); fclose(fp1); */
2922 /* FILE *fp2; fp2 = fopen("tmp.std_oahbshmx", "w"); cm_hb_shadow_mx_Dump(fp2, cm, shmx); fclose(fp2); */
2923 #endif
2924
2925 sc = alpha[0][jp_0][Lp_0];
2926
2927 /* convert sc, a log probability, into the average posterior probability of all L aligned residues */
2928 pp = sreEXP2(sc) / (float) L;
2929
2930 free(yvalidA);
2931
2932 if (ret_b != NULL) *ret_b = b; /* b is -1 if local begins are off */
2933 if (ret_pp != NULL) *ret_pp = pp;
2934
2935 ESL_DPRINTF1(("#DEBUG: cm_OptAccAlignHB return pp: %f\n", pp));
2936 return eslOK;
2937
2938 ERROR:
2939 ESL_FAIL(status, errbuf, "Memory allocation error.\n");
2940 return status; /* never reached */
2941 }
2942
2943 /* Function: cm_CYKOutsideAlign()
2944 * Date: EPN, Wed Sep 14 14:01:36 2011
2945 *
2946 * Purpose: Run the outside CYK algorithm on a target sequence.
2947 * Non-banded version. See cm_CYKOutsideAlignHB() for
2948 * the HMM banded version. The full target sequence
2949 * 1..L is aligned.
2950 *
2951 * Very similar to cm_OutsideAlign() but calculates
2952 * beta[v][j][d]: log probability of the most likely parse
2953 * that emits 1..i-1 and j+1..L and passes through v at j,d
2954 * (where i = j-d+1) instead of the log of the summed
2955 * probability of all such parses. This means max operations
2956 * are used instead of logsums.
2957 *
2958 * This function complements cm_CYKInsideAlign() but is
2959 * mainly useful for testing and reference. It can be used
2960 * with do_check=TRUE to verify that the implementation of
2961 * CYKInside and CYKOutside are consistent. Because the
2962 * structure of CYKInside and Inside, and CYKOutside and
2963 * Outside are so similar and the CYK variants are easier to
2964 * debug (because only the optimal parsetree is considered
2965 * instead of all possible parsetrees) this function can be
2966 * useful for finding bugs in Outside. It is currently not
2967 * hooked up to any of the main Infernal programs.
2968 *
2969 * Args: cm - the model
2970 * errbuf - char buffer for reporting errors
2971 * dsq - the digitized sequence
2972 * L - length of the dsq to align
2973 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
2974 * do_check - TRUE to attempt to check
2975 * mx - the dp matrix, grown and filled here
2976 * inscyk_mx - the pre-filled dp matrix from the CYK Inside calculation
2977 * (performed by cm_CYKInsideAlign(), required)
2978 * ret_sc - RETURN: log P(S|M)/P(S|R), as a bit score, this is from
2979 * inscyk_mx IF local ends are on (see comments towards
2980 * end of function).
2981 *
2982 * Returns: <eslOK> on success.
2983 *
2984 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
2985 * <eslEMEM> if we run out of memory
2986 * <eslFAIL> if <do_check>==TRUE and we fail a test
2987 * In any of these cases, alignment has been aborted, ret_sc is not valid.
2988 */
2989 int
2990 cm_CYKOutsideAlign(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_check,
2991 CM_MX *mx, CM_MX *inscyk_mx, float *ret_sc)
2992 {
2993 int status;
2994 int v,y,z; /* indices for states */
2995 int j,d,i,k; /* indices in sequence dimensions */
2996 float sc; /* a temporary score */
2997 float **esc_vAA; /* ptr to cm->oesc, optimized emission scores */
2998 float escore; /* an emission score, tmp variable */
2999 int voffset; /* index of v in t_v(y) transition scores */
3000 int sd; /* StateDelta(cm->sttype[y]) */
3001 int sdr; /* StateRightDelta(cm->sttype[y] */
3002
3003 /* variables used only if do_check==TRUE */
3004 int fail1_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 1*/
3005 int fail2_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 2*/
3006 int fail3_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 3*/
3007 int n; /* counter over nodes, used only if do_check = TRUE */
3008 int num_split_states; /* temp variable used only if do_check = TRUE */
3009 float diff; /* temp variable used only if do_check = TRUE */
3010 int vmax; /* i, offset in the matrix */
3011 float tol; /* tolerance for differences in bit scores */
3012 int *optseen = NULL; /* [1..i..W] TRUE is residue i is accounted for in optimal parse */
3013
3014 /* the DP matrices */
3015 float ***beta = mx->dp; /* pointer to the Oustide DP mx */
3016 float ***alpha = inscyk_mx->dp; /* pointer to the CYK Inside DP mx (already calc'ed and passed in) */
3017
3018 /* Allocations and initializations */
3019 esc_vAA = cm->oesc; /* a ptr to the optimized emission scores */
3020
3021 /* grow the matrix based on the current sequence */
3022 if((status = cm_mx_GrowTo(cm, mx, errbuf, L, size_limit)) != eslOK) return status;
3023
3024 /* initialize all cells of the matrix to IMPOSSIBLE */
3025 esl_vec_FSet(beta[0][0], mx->ncells_valid, IMPOSSIBLE);
3026
3027 /* now set beta[0][L][L] to 0., all (valid) parses must end there */
3028 beta[0][L][L] = 0.;
3029
3030 /* initialize local begin cells for emitting full seq (j==L && d == L) */
3031 if (cm->flags & CMH_LOCAL_BEGIN) {
3032 for (v = 1; v < cm->M; v++)
3033 beta[v][L][L] = cm->beginsc[v];
3034 }
3035
3036 /* Main recursion */
3037 for (v = 1; v < cm->M; v++) { /* start at state 1 because we set all values for ROOT_S state 0 above */
3038 sd = StateDelta(cm->sttype[v]);
3039 sdr = StateRightDelta(cm->sttype[v]);
3040
3041 if (cm->stid[v] == BEGL_S) { /* BEGL_S */
3042 y = cm->plast[v]; /* the parent bifurcation */
3043 z = cm->cnum[y]; /* the other (right) S state */
3044 for(j = 0; j <= L; j++) {
3045 for (d = 0; d <= j; d++) {
3046 for (k = 0; k <= (L-j); k++) {
3047 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j+k][d+k] + alpha[z][j+k][k]));
3048 }
3049 }
3050 }
3051 } /* end of 'if (cm->stid[v] == BEGL_S */
3052 else if (cm->stid[v] == BEGR_S) {
3053 y = cm->plast[v]; /* the parent bifurcation */
3054 z = cm->cfirst[y]; /* the other (left) S state */
3055 for(j = 0; j <= L; j++) {
3056 for (d = 0; d <= j; d++) {
3057 for (k = 0; k <= (j-d); k++) {
3058 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j][d+k] + alpha[z][j-d][k]));
3059 }
3060 }
3061 }
3062 } /* end of 'else if (cm->stid[v] == BEGR_S */
3063 else { /* (cm->sttype[v] != BEGL_S && cm->sttype[v] != BEGR_S */
3064 for (j = L; j >= 0; j--) {
3065 i = 1;
3066 for (d = j; d >= 0; d--, i++) {
3067 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
3068 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
3069 sd = StateDelta(cm->sttype[y]);
3070 sdr = StateRightDelta(cm->sttype[y]);
3071 switch(cm->sttype[y]) {
3072 case MP_st:
3073 if (j == L || d == j) continue; /* boundary condition */
3074 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
3075 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
3076 break;
3077
3078 case ML_st:
3079 case IL_st:
3080 if (d == j) continue; /* boundary condition (note when j=0, d=0*/
3081 escore = esc_vAA[y][dsq[i-1]];
3082 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
3083 break;
3084
3085 case MR_st:
3086 case IR_st:
3087 if (j == L) continue;
3088 escore = esc_vAA[y][dsq[j+1]];
3089 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
3090 break;
3091
3092 case S_st:
3093 case E_st:
3094 case D_st:
3095 beta[v][j][d] = ESL_MAX(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset]));
3096 break;
3097 } /* end of switch(cm->sttype[y] */
3098 } /* ends for loop over parent states. we now know beta[v][j][d] for this d */
3099 if (beta[v][j][d] < IMPOSSIBLE) beta[v][j][d] = IMPOSSIBLE;
3100 } /* ends loop over d. We know all beta[v][j][d] in this row j and state v */
3101 } /* end loop over j. We know beta for this whole state */
3102 } /* end of 'else if cm->sttype[v] != BEGL_S, BEGR_S */
3103 /* we're done calculating deck v for everything but local begins */
3104
3105 /* deal with local alignment end transitions v->EL (EL = deck at M.) */
3106 if ((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
3107 sdr = StateRightDelta(cm->sttype[v]); /* note sdr is for state v */
3108 sd = StateDelta(cm->sttype[v]); /* note sd is for state v */
3109
3110 for (j = 0; j <= L; j++) {
3111 for (d = 0; d <= j; d++) {
3112 i = j-d+1;
3113 switch (cm->sttype[v]) {
3114 case MP_st:
3115 if (j == L || d == j) continue; /* boundary condition */
3116 escore = esc_vAA[v][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
3117 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
3118 + escore));
3119 break;
3120 case ML_st:
3121 case IL_st:
3122 if (d == j) continue;
3123 escore = esc_vAA[v][dsq[i-1]];
3124 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
3125 + escore));
3126 break;
3127 case MR_st:
3128 case IR_st:
3129 if (j == L) continue;
3130 escore = esc_vAA[v][dsq[j+1]];
3131 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
3132 + escore));
3133 break;
3134 case S_st:
3135 case D_st:
3136 case B_st:
3137 case E_st:
3138 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]));
3139 break;
3140 }
3141 }
3142 }
3143 }
3144 }
3145 /* Deal with last step needed for local alignment
3146 * w.r.t. ends: left-emitting, EL->EL transitions. (EL = deck at M.)
3147 */
3148 if (cm->flags & CMH_LOCAL_END) {
3149 for (j = L; j > 0; j--) { /* careful w/ boundary here */
3150 for (d = j-1; d >= 0; d--) /* careful w/ boundary here */
3151 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[cm->M][j][d+1] + cm->el_selfsc));
3152 }
3153 }
3154
3155 #if eslDEBUGLEVEL >= 3
3156 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
3157 /* FILE *fp1; fp1 = fopen("tmp.std_ocykmx", "w"); cm_mx_Dump(fp1, mx); fclose(fp1); */
3158 #endif
3159
3160 fail1_flag = FALSE;
3161 fail2_flag = FALSE;
3162 fail3_flag = FALSE;
3163 if(do_check) {
3164 /* Check for consistency between the Inside alpha matrix and the
3165 * Outside beta matrix. We assume the Inside CYK parse score
3166 * (optsc) is the optimal score, so for all v,j,d:
3167 *
3168 * Jalpha[v][j][d] + Jbeta[v][j][d] <= optsc
3169 *
3170 * Further, we know that each residue must be emitted by a state
3171 * in the optimal parse. So as we do the above check, we determine
3172 * when we're in a cell that may be involved in the optimal parse
3173 * (the sum of the Inside and Outside scores are equal to the
3174 * optimal parse score), if that cell corresponds to a left
3175 * emitter emitting position i, we know an emitted i has been
3176 * observed in an optimal parse and set optseen[i] to TRUE.
3177 * Likewise, if that cell corresponds to a right emitter emitting
3178 * position j, we update optseen[j] to TRUE. At the end of the
3179 * check optseen[i] should be TRUE for all i in the range
3180 * [1..L].
3181 *
3182 * Note that we don't ensure that all of our presumed optimal
3183 * cells make up a valid parse, so it is possible we could pass
3184 * this check even if the Inside and Outside matrices are
3185 * inconsistent (i.e. there's a bug in the implementation of one
3186 * and or the other) but that should be extremely unlikely. If we
3187 * do this test many times for many different models and pass, we
3188 * should be confident we have consistent implementations.
3189 *
3190 * This is an expensive check and should only be done while
3191 * debugging.
3192 *
3193 * Another test we could do but do not is to determine the CYK
3194 * parse by tracing back the CYK Inside matrix, then ensure that
3195 * for each cell in that parse alpha[v][j][d]+beta[v][j][d] ==
3196 * optsc.
3197 */
3198 ESL_ALLOC(optseen, sizeof(int) * (L+1));
3199 esl_vec_ISet(optseen, L+1, FALSE);
3200 vmax = (cm->flags & CMH_LOCAL_END) ? cm->M : cm->M-1;
3201 /* define bit score difference tolerance, somewhat arbitrarily:
3202 * clen <= 200: tolerance is 0.001; then a function of clen:
3203 * clen == 1000 tolerance is 0.005,
3204 * clen == 2000, tolerance is 0.01.
3205 *
3206 * I did this b/c with tests with SSU_rRNA_eukarya I noticed
3207 * failures with bit score differences up to 0.004 or so. This
3208 * could mean a bug, but I couldn't get any average sized model to
3209 * fail with a difference above 0.001, so I blamed it on
3210 * precision. I'm not entirely convinced it isn't a bug but
3211 * until I see a failure on a smaller model it seems precision
3212 * is the most likely explanation, right?
3213 */
3214 tol = ESL_MAX(1e-3, (float) cm->clen / 200000.);
3215 for(v = 0; v <= vmax; v++) {
3216 for(j = 1; j <= L; j++) {
3217 for(d = 0; d <= j; d++) {
3218 sc = (alpha[v][j][d] + beta[v][j][d]) - alpha[0][L][L];
3219 if(sc > tol) {
3220 printf("Check 1 failure: v: %4d j: %4d d: %4d (%.4f + %.4f) %.4f > %.4f\n",
3221 v, j, d, alpha[v][j][d], beta[v][j][d], alpha[v][j][d] + beta[v][j][d], alpha[0][L][L]);
3222 fail1_flag = TRUE;
3223 }
3224 if(fabs(sc) < tol) { /* this cell is involved in a parse with the optimal score */
3225 i = j-d+1;
3226 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st || (cm->sttype[v] == EL_st && d >0)) {
3227 /* i is accounted for by a parse with an optimal score */
3228 optseen[i] = TRUE;
3229 /*printf("\tResidue %4d possibly accounted for by Left emitter %2s cell [v:%4d][j:%4d][d:%4d]\n", i, Statetype(cm->sttype[v]), v, j, d);*/
3230 }
3231 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
3232 /* j is accounted for by a parse with an optimal score */
3233 optseen[j] = TRUE;
3234 /*printf("\tResidue %4d possibly accounted for by Right emitter %2s cell [v:%4d][j:%4d][d:%4d]\n", j, Statetype(cm->sttype[v]), v, j, d);*/
3235 }
3236 }
3237 }
3238 }
3239 }
3240 for(j = 1; j <= L; j++) {
3241 if(optseen[j] == FALSE) {
3242 printf("Check 2 failure: residue %d not emitted in the optimal parsetree\n", j);
3243 fail2_flag = TRUE;
3244 }
3245 }
3246 free(optseen);
3247 }
3248 /* Another test that we can only do if local ends are OFF */
3249 if(do_check && (!(cm->flags & CMH_LOCAL_END))) {
3250 /* Local ends make the following test invalid because it is not true that
3251 * exactly 1 state in each node's split set must be visited in each parse.
3252 *
3253 * Determine P(pi, S|M) / P(S|R) (probability of the sequence and most likely parse
3254 * tree pi given the model)
3255 * using both the Outside (beta) and Inside (alpha) matrices,
3256 * and ensure they're consistent with P(pi, S|M) / P(S|R) from the Inside calculation.
3257 * For all v in each split set: Max_v [ Max_j,(d<=j) ( alpha[v][j][d] * beta[v][j][d] ) ]
3258 * = P(pi, S|M) / P(S|R)
3259 */
3260 for(n = 0; n < cm->nodes; n++) {
3261 sc = IMPOSSIBLE;
3262 num_split_states = SplitStatesInNode(cm->ndtype[n]);
3263 for(v = cm->nodemap[n]; v < cm->nodemap[n] + num_split_states; v++) {
3264 for (j = 0; j <= L; j++) {
3265 for (d = 0; d <= j; d++) {
3266 sc = ESL_MAX(sc, (alpha[v][j][d] + beta[v][j][d]));
3267 }
3268 }
3269 }
3270 /*printf("checking node: %d | sc: %.6f\n", n, sc);*/
3271 diff = sc - alpha[0][L][L];
3272 if(diff > 0.01 || diff < -0.01) {
3273 fail3_flag = TRUE;
3274 printf("ERROR: node %d P(S|M): %.5f inconsistent with Inside P(S|M): %.5f (diff: %.5f)\n",
3275 n, sc, alpha[0][L][L], diff);
3276 }
3277 }
3278 }
3279 /* Finally, calculate the optimal score, but this only works if
3280 * we're not in local mode:
3281 *
3282 * If local ends are off, we know the optimal parse MUST visit each END_E state,
3283 * we pick final END_E state state cm->M-1 (though any END_E could be used here):
3284 *
3285 * Max_j=0 to L (alpha[M-1][j][0] * beta[M-1][j][0]) = P(S|M) / P(S|R)
3286 *
3287 * Note: alpha[M-1][j][0] = 0.0 for all j
3288 * because all parse subtrees rooted at an END_E must have d=0, (2^0 = 1.0)
3289 * therefore:
3290 * Max_j=0 to L (beta[M-1][j][0]) = P(S|M) / P(S|R)
3291 *
3292 * *** If local ends are on, each parse MUST visit either each END_E state with d=0
3293 * or the EL state but d can vary, so we can't use this test (believe me I tried
3294 * to get a similar test working, but I'm convinced you need alpha to get P(S|M)
3295 * in local mode).
3296 */
3297 if(!(cm->flags & CMH_LOCAL_END)) {
3298 sc = IMPOSSIBLE;
3299 v = cm->M-1;
3300 for (j = 0; j <= L; j++) {
3301 sc = ESL_MAX(sc, (beta[v][j][0]));
3302 /*printf("\talpha[%3d][%3d][%3d]: %5.2f | beta[%3d][%3d][%3d]: %5.2f\n", (cm->M-1), (j), 0, alpha[(cm->M-1)][j][0], (cm->M-1), (j), 0, beta[(cm->M-1)][j][0]);*/
3303 }
3304 }
3305 else { /* return sc = P(S|M) / P(S|R) from Inside() */
3306 sc = alpha[0][L][L];
3307 }
3308
3309 if(do_check) {
3310 if (fail1_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside check1 FAILED.");
3311 else if(fail2_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside check2 FAILED.");
3312 else if(fail3_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside check3 FAILED.");
3313 ESL_DPRINTF1(("#DEBUG: SUCCESS! CYK Inside/Outside checks PASSED.\n"));
3314 }
3315
3316 if(!(cm->flags & CMH_LOCAL_END)) ESL_DPRINTF1(("#DEBUG: \tcm_CYKOutsideAlign() sc : %f\n", sc));
3317 else ESL_DPRINTF1(("#DEBUG: \tcm_CYKOutsideAlign() sc : %f (LOCAL mode; sc is from Inside)\n", sc));
3318
3319 if(ret_sc != NULL) *ret_sc = sc;
3320
3321 return eslOK;
3322
3323 ERROR:
3324 ESL_FAIL(status, errbuf, "Out of memory");
3325 return status; /* NEVER REACHED */
3326 }
3327
3328 /* Function: cm_CYKOutsideAlignHB()
3329 * Date: EPN, Fri Sep 30 10:12:51 2011
3330 *
3331 * Purpose: Run the outside CYK algorithm on a target sequence.
3332 * HMM banded version. See cm_CYKOutsideAlign() for
3333 * the non-banded version. The full target sequence
3334 * 1..L is aligned.
3335 *
3336 * Very similar to cm_OutsideAlignHB() but calculates
3337 * beta[v][j][d]: log probability of the most likely parse
3338 * that emits 1..i-1 and j+1..L and passes through v at j,d
3339 * (where i = j-d+1) instead of the log of the summed
3340 * probability of all such parses. This means max operations
3341 * are used instead of logsums.
3342 *
3343 * This function complements cm_CYKInsideAlignHB() but is
3344 * mainly useful for testing and reference. It can be used
3345 * with do_check=TRUE to verify that the implementation of
3346 * CYKInsideHB and CYKOutsideHB are consistent. Because the
3347 * structure of CYKInsideHB and InsideHB, and CYKOutsideHB
3348 * and OutsideHB are so similar and the CYK variants are
3349 * easier to debug (because only the optimal parsetree is
3350 * considered instead of all possible parsetrees) this
3351 * function can be useful for finding bugs in OutsideHB. It
3352 * is currently not hooked up to any of the main Infernal
3353 * programs.
3354 *
3355 * Args: cm - the model
3356 * errbuf - char buffer for reporting errors
3357 * dsq - the digitized sequence
3358 * L - length of the dsq to align
3359 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
3360 * do_check - TRUE to attempt to check
3361 * mx - the dp matrix, only cells within bands in cp9b will be valid
3362 * ins_mx - the dp matrix from the Inside run calculation (required)
3363 * ret_sc - RETURN: log P(S|M)/P(S|R), as a bit score, this is from ins_mx IF local
3364 * ends are on (see *** comment towards end of function).
3365 *
3366 * Returns: <eslOK> on success
3367 *
3368 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
3369 * <eslFAIL> if <do_check>==TRUE and we fail a test
3370 * In either of these cases, alignment has been aborted, ret_sc is not valid.
3371 */
3372 int
3373 cm_CYKOutsideAlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_check,
3374 CM_HB_MX *mx, CM_HB_MX *ins_mx, float *ret_sc)
3375 {
3376 int status;
3377 int v,y,z; /* indices for states */
3378 int j,d,i,k; /* indices in sequence dimensions */
3379 float **esc_vAA; /* ptr to cm->oesc, optimized emission scores */
3380 float sc; /* a temporary score */
3381 float escore; /* an emission score, tmp variable */
3382 int voffset; /* index of v in t_v(y) transition scores */
3383 int emitmode; /* EMITLEFT, EMITRIGHT, EMITPAIR, EMITNONE, for state y */
3384 int sd; /* StateDelta(cm->sttype[y]) */
3385 int sdr; /* StateRightDelta(cm->sttype[y] */
3386
3387 /* variables used only if do_check */
3388 int fail1_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 1*/
3389 int fail2_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 2*/
3390 int fail3_flag = FALSE; /* set to TRUE if do_check and we see a problem with check 3*/
3391 int n; /* counter over nodes, used only if do_check = TRUE */
3392 int num_split_states; /* temp variable used only if do_check = TRUE */
3393 float diff; /* temp variable used only if do_check = TRUE */
3394 int vmax; /* i, offset in the matrix */
3395 float tol; /* tolerance for differences in bit scores */
3396 int *optseen = NULL; /* [1..i..W] TRUE is residue i is accounted for in optimal parse */
3397
3398 /* band related variables */
3399 int dp_v; /* d index for state v in alpha w/mem eff bands */
3400 int dp_y; /* d index for state y in alpha w/mem eff bands */
3401 int kp_z; /* k (in the d dim) index for state z in alpha w/mem eff bands */
3402 int Lp; /* L index also changes depending on state */
3403 int jp_v, jp_y, jp_z; /* offset j index for states v, y, z */
3404 int kmin, kmax; /* temporary minimum/maximum allowed k */
3405 int jn, jx; /* current minimum/maximum j allowed */
3406 int dn, dx; /* current minimum/maximum d allowed */
3407 int jp_0; /* L offset in ROOT_S's (v==0) j band */
3408 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
3409
3410 /* the DP matrices */
3411 float ***beta = mx->dp; /* pointer to the Oustide DP mx */
3412 float ***alpha = ins_mx->dp; /* pointer to the Inside DP mx (already calc'ed and passed in) */
3413
3414 /* ptrs to cp9b info, for convenience */
3415 int *jmin = cm->cp9b->jmin;
3416 int *jmax = cm->cp9b->jmax;
3417 int **hdmin = cm->cp9b->hdmin;
3418 int **hdmax = cm->cp9b->hdmax;
3419
3420 /* Allocations and initializations */
3421 esc_vAA = cm->oesc; /* a ptr to the optimized emission scores */
3422
3423 /* grow the matrix based on the current sequence and bands */
3424 if((status = cm_hb_mx_GrowTo(cm, mx, errbuf, cm->cp9b, L, size_limit)) != eslOK) return status;
3425
3426 /* initialize all cells of the matrix to IMPOSSIBLE */
3427 esl_vec_FSet(beta[0][0], mx->ncells_valid, IMPOSSIBLE);
3428
3429 /* ensure a full alignment to ROOT_S (v==0) is allowed by the bands */
3430 if (jmin[0] > L || jmax[0] < L)
3431 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, jmin[0], jmax[0]);
3432 jp_0 = L - jmin[0];
3433 if (hdmin[0][jp_0] > L || hdmax[0][jp_0] < L)
3434 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, hdmin[0][jp_0], hdmax[0][jp_0]);
3435 Lp_0 = L - hdmin[0][jp_0];
3436 /* set the offset banded cell corresponding to beta[0][L][L] to 0., all parses must end there */
3437 beta[0][jp_0][Lp_0] = 0.;
3438
3439 /* If we can do a local begin into v, overwrite IMPOSSIBLE with the local begin score. */
3440 if (cm->flags & CMH_LOCAL_BEGIN) {
3441 for (v = 1; v < cm->M; v++) {
3442 if(NOT_IMPOSSIBLE(cm->beginsc[v])) {
3443 if((L >= jmin[v]) && (L <= jmax[v])) {
3444 jp_v = L - jmin[v];
3445 if((L >= hdmin[v][jp_v]) && L <= hdmax[v][jp_v]) {
3446 Lp = L - hdmin[v][jp_v];
3447 beta[v][jp_v][Lp] = cm->beginsc[v];
3448 }
3449 }
3450 }
3451 }
3452 }
3453 /* done allocation/initialization */
3454
3455 /* Recursion: main loop down through the decks */
3456 for (v = 1; v < cm->M; v++) { /* start at state 1 because we set all values for ROOT_S state 0 above */
3457 if (cm->stid[v] == BEGL_S) { /* BEGL_S */
3458 y = cm->plast[v]; /* the parent bifurcation */
3459 z = cm->cnum[y]; /* the other (right) S state */
3460 for (j = jmax[v]; j >= jmin[v]; j--) {
3461 ESL_DASSERT1((j >= 0 && j <= L));
3462 jp_v = j - jmin[v];
3463 jp_y = j - jmin[y];
3464 jp_z = j - jmin[z];
3465 i = j-d+1;
3466 for (d = hdmax[v][jp_v]; d >= hdmin[v][jp_v]; d--) {
3467 dp_v = d - hdmin[v][jp_v];
3468 /* Find the first k value that implies a valid cell in the y and z decks.
3469 * This k must satisfy the following 8 inequalities (some may be redundant):
3470 * NOTE: these are different from those in Inside() (for one thing, v and y
3471 * (BEGL_S and BIF_B here respectively) are switched relative to Inside.
3472 *
3473 * (1) k <= jmax[y] - j;
3474 * (2) k >= jmin[y] - j;
3475 * (3) k <= jmax[z] - j;
3476 * (4) k >= jmin[z] - j;
3477 * 1 and 2 guarantee (j+k) is within state y's j band
3478 * 3 and 4 guarantee (j+k) is within state z's j band
3479 *
3480 * (5) k >= hdmin[y][j-jmin[y]+k] - d;
3481 * (6) k <= hdmax[y][j-jmin[y]+k] - d;
3482 * 5 and 6 guarantee k+d is within y's j=(j+k), d band
3483 *
3484 * (7) k >= hdmin[z][j-jmin[z]+k];
3485 * (8) k <= hdmax[z][j-jmin[z]+k];
3486 * 5 and 6 guarantee k is within state z's j=(j+k) d band
3487 */
3488 kmin = ESL_MAX(jmin[y], jmin[z]) - j;
3489 kmax = ESL_MIN(jmax[y], jmax[z]) - j;
3490 /* kmin and kmax satisfy inequalities (1-4) */
3491 /* RHS of inequalities 5-8 are dependent on k, so we check
3492 * for these within the next for loop. */
3493 for(k = kmin; k <= kmax; k++) {
3494 if(k < (hdmin[y][jp_y+k] - d) || k > (hdmax[y][jp_y+k] - d)) continue;
3495 /* above line continues if inequality 5 or 6 is violated */
3496 if(k < (hdmin[z][jp_z+k]) || k > (hdmax[z][jp_z+k])) continue;
3497 /* above line continues if inequality 7 or 8 is violated */
3498
3499 /* if we get here for current k, all 8 inequalities have been satisified
3500 * so we know the cells corresponding to the platonic
3501 * matrix cells alpha[v][j][d], alpha[y][j+k][d+k], and
3502 * alpha[z][j+k][k] are all within the bands. These
3503 * cells correspond to beta[v][jp_v][dp_v],
3504 * beta[y][jp_y+k][d-hdmin[y][jp_y+k]+k],
3505 * and alpha[z][jp_z][k-hdmin[z][jp_z+k]];
3506 */
3507 kp_z = k-hdmin[z][jp_z+k];
3508 dp_y = d-hdmin[y][jp_y+k];
3509 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y+k][dp_y+k] + alpha[z][jp_z+k][kp_z]));
3510 }
3511 }
3512 }
3513 } /* end of 'if (cm->stid[v] == BEGL_S */
3514 else if (cm->stid[v] == BEGR_S) {
3515 y = cm->plast[v]; /* the parent bifurcation */
3516 z = cm->cfirst[y]; /* the other (left) S state */
3517 jn = ESL_MAX(jmin[v], jmin[y]);
3518 jx = ESL_MIN(jmax[v], jmax[y]);
3519 for (j = jx; j >= jn; j--) {
3520 ESL_DASSERT1((j >= 0 && j <= L));
3521 jp_v = j - jmin[v];
3522 jp_y = j - jmin[y];
3523 jp_z = j - jmin[z];
3524 i = j-d+1;
3525
3526 dn = ESL_MAX(hdmin[v][jp_v], j-jmax[z]);
3527 dx = ESL_MIN(hdmax[v][jp_v], jp_z);
3528 /* above makes sure that j,d are valid for state z: (jmin[z] + d) >= j >= (jmax[z] + d) */
3529 for (d = dx; d >= dn; d--) {
3530 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
3531 /* Find the first k value that implies a valid cell in the y and z decks.
3532 * This k must satisfy the following 4 inequalities (some may be redundant):
3533 * NOTE: these are different from those in Inside() (for one thing, v and y
3534 * (BEGR_S and BIF_B here respectively) are switched relative to Inside.
3535 *
3536 * (1) k >= hdmin[y][j-jmin[y]] - d;
3537 * (2) k <= hdmax[y][j-jmin[y]] - d;
3538 * 1 and 2 guarantee (d+k) is within state y's j=(j) d band
3539 *
3540 * (3) k >= hdmin[z][j-jmin[z]-d];
3541 * (4) k <= hdmax[z][j-jmin[z]-d];
3542 * 3 and 4 guarantee k is within z's j=(j-d) d band
3543 *
3544 */
3545 kmin = ESL_MAX((hdmin[y][jp_y]-d), (hdmin[z][jp_z-d]));
3546 kmax = ESL_MIN((hdmax[y][jp_y]-d), (hdmax[z][jp_z-d]));
3547 /* kmin and kmax satisfy inequalities (1-4) */
3548 for(k = kmin; k <= kmax; k++) {
3549 /* for current k, all 4 inequalities have been satisified
3550 * so we know the cells corresponding to the platonic
3551 * matrix cells beta[v][j][d], beta[y][j][d+k], and
3552 * alpha[z][j-d][k] are all within the bands. These
3553 * cells correspond to beta[v][jp_v][dp_v],
3554 * beta[y][jp_y+k][d-hdmin[y][jp_y]+k],
3555 * and alpha[z][jp_z-d][k-hdmin[z][jp_z-d]];
3556 */
3557 kp_z = k-hdmin[z][jp_z-d];
3558 dp_y = d-hdmin[y][jp_y];
3559 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y+k]
3560 + alpha[z][jp_z-d][kp_z]));
3561 }
3562 }
3563 }
3564 } /* end of 'else if (cm->stid[v] == BEGR_S */
3565 else if (cm->sttype[v] == IL_st || cm->sttype[v] == IR_st) {
3566 /* ILs and IRs can self transit, this means that beta[v][j][d] must be fully calculated
3567 * before beta[v][j][d+1] can be started to be calculated, forcing the following nesting order:
3568 * for j { for d { for y { } } }
3569 * for non-self-transitioners, we can do a more efficient nesting order (see below)
3570 */
3571 for (j = jmax[v]; j >= jmin[v]; j--) {
3572 ESL_DASSERT1((j >= 0 && j <= L));
3573 jp_v = j - jmin[v];
3574 for (d = hdmax[v][jp_v]; d >= hdmin[v][jp_v]; d--) {
3575 i = j-d+1;
3576 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
3577
3578 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
3579 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
3580
3581 /* Note: this looks like it can be optimized, I tried but my 'optimization' slowed the code, so I reverted [EPN] */
3582 switch(cm->sttype[y]) {
3583 case MP_st:
3584 if (j == L || d == j) continue; /* boundary condition */
3585 if ((j+1) < jmin[y] || (j+1) > jmax[y]) continue; /* enforces j is valid for state y */
3586 jp_y = j - jmin[y];
3587 if ((d+2) < hdmin[y][(jp_y+1)] || (d+2) > hdmax[y][(jp_y+1)]) continue; /* enforces d is valid for state y */
3588 /* if we get here alpha[y][jp_y+1][dp_y+2] is a valid alpha cell
3589 * corresponding to alpha[y][j+1][d+2] in the platonic matrix.
3590 */
3591 dp_y = d - hdmin[y][jp_y+1]; /* d index for state y */
3592 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
3593 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y+1][dp_y+2]
3594 + cm->tsc[y][voffset] + escore));
3595 break;
3596
3597 case ML_st:
3598 case IL_st:
3599 if (d == j) continue; /* boundary condition (note when j=0, d=0)*/
3600 if (j < jmin[y] || j > jmax[y]) continue; /* enforces j is valid for state y */
3601 jp_y = j - jmin[y];
3602 if ((d+1) < hdmin[y][jp_y] || (d+1) > hdmax[y][jp_y]) continue; /* enforces d is valid for state y */
3603 /* if we get here alpha[y][jp_y][dp_y+1] is a valid alpha cell
3604 * corresponding to alpha[y][j][d+1] in the platonic matrix.
3605 */
3606 dp_y = d - hdmin[y][jp_y]; /* d index for state y */
3607 escore = esc_vAA[y][dsq[i-1]];
3608 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y+1]
3609 + cm->tsc[y][voffset] + escore));
3610 break;
3611
3612 case MR_st:
3613 case IR_st:
3614 if (j == L) continue;
3615 if ((j+1) < jmin[y] || (j+1) > jmax[y]) continue; /* enforces j is valid for state y */
3616 jp_y = j - jmin[y];
3617 if ((d+1) < hdmin[y][(jp_y+1)] || (d+1) > hdmax[y][(jp_y+1)]) continue; /* enforces d is valid for state y */
3618 /* if we get here alpha[y][jp_y+1][dp_y+1] is a valid alpha cell
3619 * corresponding to alpha[y][j+1][d+1] in the platonic matrix.
3620 */
3621 dp_y = d - hdmin[y][(jp_y+1)]; /* d index for state y */
3622 escore = esc_vAA[y][dsq[j+1]];
3623 /*printf("j: %d | jmin[y]: %d | jmax[y]: %d | jp_v: %d | dp_v: %d | jp_y: %d | dp_y: %d\n", j, jmin[y], jmax[y], jp_v, dp_v, jp_y, dp_y);*/
3624 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y+1][dp_y+1]
3625 + cm->tsc[y][voffset] + escore));
3626 break;
3627
3628 case S_st:
3629 case E_st:
3630 case D_st:
3631 if (j < jmin[y] || j > jmax[y]) continue; /* enforces j is valid for state y */
3632 jp_y = j - jmin[y];
3633 if (d < hdmin[y][jp_y] || d > hdmax[y][jp_y]) continue; /* enforces d is valid for state y */
3634 /* if we get here alpha[y][jp_y][dp_y] is a valid alpha cell
3635 * corresponding to alpha[y][j][d] in the platonic matrix.
3636 */
3637 dp_y = d - hdmin[y][jp_y]; /* d index for state y */
3638 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y] + cm->tsc[y][voffset]));
3639 break;
3640 } /* end of switch(cm->sttype[y] */
3641 } /* ends for loop over parent states. we now know beta[v][j][d] for this d */
3642 if (beta[v][jp_v][dp_v] < IMPOSSIBLE) beta[v][jp_v][dp_v] = IMPOSSIBLE;
3643 } /* ends loop over d. We know all beta[v][j][d] in this row j and state v */
3644 } /* end loop over jp. We know beta for this whole state */
3645 } /* end of 'else if cm->sttype[v] == IL_st || cm->sttype[v] == IR_st' */
3646 else { /* state v is not BEGL_S, BEGL_R IL nor IR (must be ML, MP, MR, D, S, B or E) */
3647 /* ML, MP, MR, D, S, B, E states cannot self transit, this means that all cells
3648 * in beta[v] are independent of each other, only depending on beta[y] for previously calc'ed y.
3649 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
3650 * for y { for j { for d { } } }
3651 */
3652 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
3653 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
3654 sdr = StateRightDelta(cm->sttype[y]);
3655 sd = StateDelta(cm->sttype[y]);
3656 emitmode = Emitmode(cm->sttype[y]);
3657 /* determine min j (jn) and max j (jx) that are valid for v and y */
3658 jn = ESL_MAX(jmin[v], jmin[y]-sdr);
3659 jx = ESL_MIN(jmax[v], jmax[y]-sdr);
3660 for (j = jx; j >= jn; j--) {
3661 ESL_DASSERT1((j >= 0 && j <= L));
3662 jp_v = j - jmin[v];
3663 jp_y = j - jmin[y];
3664 ESL_DASSERT1((j+sdr >= jmin[y] && j+sdr <= jmax[y]));
3665
3666 /* determine min d (dn) and max d (dx) that are valid for v and y and j */
3667 dn = ESL_MAX(hdmin[v][jp_v], hdmin[y][jp_y + sdr] - sd);
3668 dx = ESL_MIN(hdmax[v][jp_v], hdmax[y][jp_y + sdr] - sd);
3669 dp_v = dx - hdmin[v][jp_v];
3670 dp_y = dx - hdmin[y][jp_y + sdr];
3671 i = j-dx+1;
3672
3673 /* for each emit mode, update beta[v][jp_v][dp_v] for all valid d = dp_v */
3674 switch(emitmode) {
3675 case EMITPAIR: /* MP_st */
3676 for (d = dx; d >= dn; d--, dp_v--, dp_y--, i++) {
3677 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
3678 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
3679 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
3680 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
3681 + cm->tsc[y][voffset] + escore));
3682 }
3683 break;
3684 case EMITLEFT: /* ML_st, IL_st */
3685 for (d = dx; d >= dn; d--, dp_v--, dp_y--, i++) {
3686 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
3687 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
3688 escore = esc_vAA[y][dsq[i-1]];
3689 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
3690 + cm->tsc[y][voffset] + escore));
3691 }
3692 break;
3693 case EMITRIGHT: /* MR_st, IR_st */
3694 escore = esc_vAA[y][dsq[j+1]]; /* not dependent on i */
3695 for (d = dx; d >= dn; d--, dp_v--, dp_y--) {
3696 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
3697 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
3698 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
3699 + cm->tsc[y][voffset] + escore));
3700 }
3701 break;
3702 case EMITNONE: /* D_st, S_st, E_st*/
3703 for (d = dx; d >= dn; d--, dp_v--, dp_y--) {
3704 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
3705 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
3706 beta[v][jp_v][dp_v] = ESL_MAX(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
3707 + cm->tsc[y][voffset]));
3708 }
3709 break;
3710 } /* end of switch(emitmode) */
3711 } /* end of for j = jx; j >= jn; j-- */
3712 } /* end of for y = plast[v]... */
3713 } /* ends else entered for non-BEGL_S/BEGR_S/IL/IR states*/
3714 /* we're done calculating deck v for everything but local begins */
3715
3716 /* deal with local alignment end transitions v->EL (EL = deck at M.) */
3717 if ((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
3718 sdr = StateRightDelta(cm->sttype[v]); /* note sdr is for state v */
3719 sd = StateDelta(cm->sttype[v]); /* note sd is for state v */
3720 emitmode = Emitmode(cm->sttype[v]); /* note emitmode is for state v */
3721
3722 jn = jmin[v] - sdr;
3723 jx = jmax[v] - sdr;
3724 for (j = jn; j <= jx; j++) {
3725 jp_v = j - jmin[v];
3726 dn = hdmin[v][jp_v + sdr] - sd;
3727 dx = hdmax[v][jp_v + sdr] - sd;
3728 i = j-dn+1; /* we'll decrement this in for (d... loops inside switch below */
3729 dp_v = dn - hdmin[v][jp_v + sdr]; /* we'll increment this in for (d... loops inside switch below */
3730
3731 switch (emitmode) {
3732 case EMITPAIR:
3733 for (d = dn; d <= dx; d++, dp_v++, i--) {
3734 escore = esc_vAA[v][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
3735 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
3736 + escore));
3737 }
3738 break;
3739 case EMITLEFT:
3740 for (d = dn; d <= dx; d++, dp_v++, i--) {
3741 escore = esc_vAA[v][dsq[i-1]];
3742 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
3743 + escore));
3744 }
3745 break;
3746
3747 case EMITRIGHT:
3748 escore = esc_vAA[v][dsq[j+1]];
3749 for (d = dn; d <= dx; d++, dp_v++) {
3750 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
3751 + escore));
3752 }
3753 break;
3754
3755 case EMITNONE:
3756 for (d = dn; d <= dx; d++, dp_v++) {
3757 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]));
3758 }
3759 break;
3760 }
3761 }
3762 }
3763 } /* end loop over decks v. */
3764
3765 /* Deal with last step needed for local alignment
3766 * w.r.t. ends: left-emitting, EL->EL transitions. (EL = deck at M.)
3767 */
3768 if (cm->flags & CMH_LOCAL_END) {
3769 for (j = L; j > 0; j--) { /* careful w/ boundary here */
3770 for (d = j-1; d >= 0; d--) /* careful w/ boundary here */
3771 beta[cm->M][j][d] = ESL_MAX(beta[cm->M][j][d], (beta[cm->M][j][d+1] + cm->el_selfsc));
3772 }
3773 }
3774
3775 #if eslDEBUGLEVEL >= 3
3776 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
3777 /* FILE *fp1; fp1 = fopen("tmp.stdocykhbmx", "w"); cm_hb_mx_Dump(fp1, mx); fclose(fp1); */
3778 #endif
3779
3780 fail1_flag = FALSE;
3781 fail2_flag = FALSE;
3782 fail3_flag = FALSE;
3783 printf("DO CHECK: %d\n", do_check);
3784 if(do_check) {
3785 /* Check for consistency between the Inside alpha matrix and the
3786 * Outside beta matrix. We assume the Inside CYK parse score
3787 * (optsc) is the optimal score, so for all v,j,d:
3788 *
3789 * Jalpha[v][j][d] + Jbeta[v][j][d] <= optsc
3790 *
3791 * Further, we know that each residue must be emitted by a state
3792 * in the optimal parse. So as we do the above check, we determine
3793 * when we're in a cell that may be involved in the optimal parse
3794 * (the sum of the Inside and Outside scores are equal to the
3795 * optimal parse score), if that cell corresponds to a left
3796 * emitter emitting position i, we know an emitted i has been
3797 * observed in an optimal parse and set optseen[i] to TRUE.
3798 * Likewise, if that cell corresponds to a right emitter emitting
3799 * position j, we update optseen[j] to TRUE. At the end of the
3800 * check optseen[i] should be TRUE for all i in the range
3801 * [1..L].
3802 *
3803 * Note that we don't ensure that all of our presumed optimal
3804 * cells make up a valid parse, so it is possible we could pass
3805 * this check even if the Inside and Outside matrices are
3806 * inconsistent (i.e. there's a bug in the implementation of one
3807 * and or the other) but that should be extremely unlikely. If we
3808 * do this test many times for many different models and pass, we
3809 * should be confident we have consistent implementations.
3810 *
3811 * This is an expensive check and should only be done while
3812 * debugging.
3813 *
3814 * Another test we could do but do not is to determine the CYK
3815 * parse by tracing back the CYK Inside matrix, then ensure that
3816 * for each cell in that parse alpha[v][j][d]+beta[v][j][d] ==
3817 * optsc.
3818 */
3819 ESL_ALLOC(optseen, sizeof(int) * (L+1));
3820 esl_vec_ISet(optseen, L+1, FALSE);
3821 vmax = (cm->flags & CMH_LOCAL_END) ? cm->M : cm->M-1;
3822 /* define bit score difference tolerance, somewhat arbitrarily:
3823 * clen <= 200: tolerance is 0.001; then a function of clen:
3824 * clen == 1000 tolerance is 0.005,
3825 * clen == 2000, tolerance is 0.01.
3826 *
3827 * I did this b/c with tests with SSU_rRNA_eukarya I noticed
3828 * failures with bit score differences up to 0.004 or so. This
3829 * could mean a bug, but I couldn't get any average sized model to
3830 * fail with a difference above 0.001, so I blamed it on
3831 * precision. I'm not entirely convinced it isn't a bug but
3832 * until I see a failure on a smaller model it seems precision
3833 * is the most likely explanation, right?
3834 */
3835 tol = ESL_MAX(1e-3, (float) cm->clen / 200000.);
3836 for(v = 0; v <= vmax; v++) {
3837 jn = (v == cm->M) ? 1 : jmin[v];
3838 jx = (v == cm->M) ? L : jmax[v];
3839 for(j = jn; j <= jx; j++) {
3840 jp_v = (v == cm->M) ? j : j - jmin[v];
3841 dn = (v == cm->M) ? 0 : hdmin[v][jp_v];
3842 dx = (v == cm->M) ? j : hdmax[v][jp_v];
3843 for(d = dn; d <= dx; d++) {
3844 dp_v = (v == cm->M) ? d : d - hdmin[v][jp_v];
3845 sc = (alpha[v][jp_v][dp_v] + beta[v][jp_v][dp_v]) - alpha[0][jp_0][Lp_0];
3846 if(sc > tol) {
3847 printf("Check 1 failure: v: %4d j: %4d d: %4d (%.4f + %.4f) %.4f > %.4f\n",
3848 v, j, d, alpha[v][jp_v][dp_v], beta[v][jp_v][dp_v], alpha[v][jp_v][dp_v] + beta[v][jp_v][dp_v], alpha[0][jp_0][Lp_0]);
3849 fail1_flag = TRUE;
3850 }
3851 if(fabs(sc) < tol) { /* this cell is involved in a parse with the optimal score */
3852 i = j-d+1;
3853 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st || (cm->sttype[v] == EL_st && d >0)) {
3854 /* i is accounted for by a parse with an optimal score */
3855 optseen[i] = TRUE;
3856 /*printf("\tResidue %4d possibly accounted for by Left emitter %2s cell [v:%4d][j:%4d][d:%4d]\n", i, Statetype(cm->sttype[v]), v, j, d);*/
3857 }
3858 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
3859 /* j is accounted for by a parse with an optimal score */
3860 optseen[j] = TRUE;
3861 /*printf("\tResidue %4d possibly accounted for by Right emitter %2s cell [v:%4d][j:%4d][d:%4d]\n", j, Statetype(cm->sttype[v]), v, j, d);*/
3862 }
3863 }
3864 }
3865 }
3866 }
3867 for(j = 1; j <= L; j++) {
3868 if(optseen[j] == FALSE) {
3869 printf("Check 2 failure: residue %d not emitted in the optimal parsetree\n", j);
3870 fail2_flag = TRUE;
3871 }
3872 }
3873 free(optseen);
3874 }
3875 /* Another test that we can only do if local ends are OFF */
3876 if(do_check && (!(cm->flags & CMH_LOCAL_END))) {
3877 /* Local ends make the following test invalid because it is not true that
3878 * exactly 1 state in each node's split set must be visited in each parse.
3879 *
3880 * Determine P(pi, S|M) / P(S|R) (probability of the sequence and most likely parse
3881 * tree pi given the model)
3882 * using both the Outside (beta) and Inside (alpha) matrices,
3883 * and ensure they're consistent with P(pi, S|M) / P(S|R) from the Inside calculation.
3884 * For all v in each split set: Max_v [ Max_j,(d<=j) ( alpha[v][j][d] * beta[v][j][d] ) ]
3885 * = P(pi, S|M) / P(S|R)
3886 */
3887 for(n = 0; n < cm->nodes; n++) {
3888 sc = IMPOSSIBLE;
3889 num_split_states = SplitStatesInNode(cm->ndtype[n]);
3890 for(v = cm->nodemap[n]; v < cm->nodemap[n] + num_split_states; v++) {
3891 for (j = jmin[v]; j <= jmax[v]; j++) {
3892 jp_v = j - jmin[v];
3893 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
3894 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
3895 sc = ESL_MAX(sc, (alpha[v][jp_v][dp_v] + beta[v][jp_v][dp_v]));
3896 }
3897 }
3898 }
3899 /*printf("checking node: %d | sc: %.6f\n", n, sc);*/
3900 diff = sc - alpha[0][jp_0][Lp_0];
3901 if(diff > 0.01 || diff < -0.01) {
3902 fail3_flag = TRUE;
3903 printf("ERROR: node %d P(S|M): %.5f inconsistent with Inside P(S|M): %.5f (diff: %.5f)\n",
3904 n, sc, alpha[0][jp_0][Lp_0], diff);
3905 }
3906 }
3907 }
3908
3909 /* Finally, calculate the optimal score, but this only works if
3910 * we're not in local mode:
3911 *
3912 * If local ends are off, we know the optimal parse MUST visit each END_E state,
3913 * we pick final END_E state state cm->M-1 (though any END_E could be used here):
3914 *
3915 * Max_j=0 to L (alpha[M-1][j][0] * beta[M-1][j][0]) = P(S|M) / P(S|R)
3916 *
3917 * Note: alpha[M-1][j][0] = 0.0 for all j
3918 * because all parse subtrees rooted at an END_E must have d=0, (2^0 = 1.0)
3919 * therefore:
3920 * Max_j=0 to L (beta[M-1][j][0]) = P(S|M) / P(S|R)
3921 *
3922 * *** If local ends are on, each parse MUST visit either each END_E state with d=0
3923 * or the EL state but d can vary, so we can't use this test (believe me I tried
3924 * to get a similar test working, but I'm convinced you need alpha to get P(S|M)
3925 * in local mode).
3926 */
3927 if(!(cm->flags & CMH_LOCAL_END)) {
3928 sc = IMPOSSIBLE;
3929 v = cm->M-1;
3930 for (j = jmin[v]; j <= jmax[v]; j++) {
3931 jp_v = j - jmin[v];
3932 assert(hdmin[v][jp_v] == 0);
3933 sc = ESL_MAX(sc, (beta[v][jp_v][0]));
3934 /* printf("\talpha[%3d][%3d][%3d]: %5.2f | beta[%3d][%3d][%3d]: %5.2f\n", (cm->M-1), (j), 0, alpha[(cm->M-1)][j][0], (cm->M-1), (j), 0, beta[(cm->M-1)][j][0]);*/
3935 }
3936 }
3937 else { /* return sc = P(S|M) / P(S|R) from Inside() */
3938 sc = alpha[0][jp_0][Lp_0];
3939 }
3940
3941 #if eslDEBUGLEVEL >= 3
3942 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
3943 /* FILE *fp; fp = fopen("tmp.std_ocykhbmx", "w"); cm_hb_mx_Dump(fp, mx); fclose(fp); */
3944 #endif
3945
3946 if(do_check) {
3947 if (fail1_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside HB check1 FAILED.");
3948 else if(fail2_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside HB check2 FAILED.");
3949 else if(fail3_flag) ESL_FAIL(eslFAIL, errbuf, "CYK Inside/Outside HB check3 FAILED.");
3950 ESL_DPRINTF1(("#DEBUG: SUCCESS! CYK Inside/Outside HB checks PASSED.\n"));
3951 }
3952
3953 if(!(cm->flags & CMH_LOCAL_END)) ESL_DPRINTF1(("#DEBUG: \tcm_CYKOutsideAlignHB() sc : %f\n", sc));
3954 else ESL_DPRINTF1(("#DEBUG: \tcm_CYKOutsideAlignHB() sc : %f (LOCAL mode; sc is from Inside)\n", sc));
3955
3956 if(ret_sc != NULL) *ret_sc = sc;
3957
3958 return eslOK;
3959
3960 ERROR:
3961 ESL_FAIL(status, errbuf, "Out of memory");
3962 return status; /* NEVER REACHED */
3963 }
3964
3965 /* Function: cm_OutsideAlign()
3966 * Date: EPN, Mon Nov 19 07:00:37 2007
3967 *
3968 * Purpose: Run the outside algorithm on a target sequence.
3969 * Non-banded version. See cm_OutsideAlignHB() for
3970 * the HMM banded version. The full target sequence
3971 * 1..L is aligned.
3972 *
3973 * Very similar to cm_CYKOutsideAlign() but calculates
3974 * beta[v][j][d]: log of the summed probability of all
3975 * parsetrees that emits 1..i-1 and j+1..L and pass through
3976 * v at j,d (where i = j-d+1) instead of the log of the
3977 * probability of the most likely (CYK) parse. This means
3978 * logsum operations are used instead of max operations.
3979 *
3980 * For debugging this function, the cm_CYKOutsideAlign() can
3981 * be useful, because it has a very similar organization but
3982 * is easier to debug because only the most likely parsetree
3983 * is considered. cm_CYKOutsideAlign() also allows a more
3984 * stringent test for the consistency of the CYKInside and
3985 * CYKOutside matrices.
3986 *
3987 * If <do_check> is TRUE (and the CM is not in local mode)
3988 * we check that the outside matrix values are consistent
3989 * with the inside matrix values (in ins_mx). This check is
3990 * described in comments towards the end of the function.
3991 *
3992 * Note: renamed from FastOutsideAlign() [EPN, Wed Sep 14 06:13:53 2011].
3993 *
3994 * Args: cm - the model
3995 * errbuf - char buffer for reporting errors
3996 * dsq - the digitized sequence
3997 * L - length of the dsq to align
3998 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
3999 * do_check - TRUE to attempt to check
4000 * mx - the dp matrix, grown and filled here
4001 * ins_mx - the pre-filled dp matrix from the Inside run calculation (required)
4002 * ret_sc - RETURN: log P(S|M)/P(S|R), as a bit score, this is from ins_mx IF local
4003 * ends are on (see *** comment towards end of function).
4004 *
4005 * Returns: <eslOK> on success
4006 *
4007 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
4008 * <eslFAIL> if <do_check>==TRUE and we fail a test
4009 * In either of these cases, alignment has been aborted, ret_sc is not valid.
4010
4011 */
4012 int
4013 cm_OutsideAlign(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_check,
4014 CM_MX *mx, CM_MX *ins_mx, float *ret_sc)
4015 {
4016 int status;
4017 int v,y,z; /* indices for states */
4018 int j,d,i,k; /* indices in sequence dimensions */
4019 float sc; /* a temporary score */
4020 float **esc_vAA; /* ptr to cm->oesc, optimized emission scores */
4021 float escore; /* an emission score, tmp variable */
4022 int voffset; /* index of v in t_v(y) transition scores */
4023 int sd; /* StateDelta(cm->sttype[y]) */
4024 int sdr; /* StateRightDelta(cm->sttype[y] */
4025
4026 /* variables used only if do_check==TRUE */
4027 int n; /* counter over nodes, used only if do_check = TRUE */
4028 int num_split_states; /* temp variable used only if do_check = TRUE */
4029 float diff; /* temp variable used only if do_check = TRUE */
4030 int fail_flag = FALSE; /* set to TRUE if do_check and we see a problem */
4031
4032 /* the DP matrices */
4033 float ***beta = mx->dp; /* pointer to the Oustide DP mx */
4034 float ***alpha = ins_mx->dp; /* pointer to the Inside DP mx (already calc'ed and passed in) */
4035
4036 /* Allocations and initializations */
4037 esc_vAA = cm->oesc; /* a ptr to the optimized emission scores */
4038
4039 /* grow the matrix based on the current sequence */
4040 if((status = cm_mx_GrowTo(cm, mx, errbuf, L, size_limit)) != eslOK) return status;
4041
4042 /* initialize all cells of the matrix to IMPOSSIBLE */
4043 esl_vec_FSet(beta[0][0], mx->ncells_valid, IMPOSSIBLE);
4044
4045 /* now set beta[0][L][L] to 0., all parses must end there */
4046 beta[0][L][L] = 0.;
4047
4048 /* initialize local begin cells for emitting full seq (j==L && d == L) */
4049 if (cm->flags & CMH_LOCAL_BEGIN) {
4050 for (v = 1; v < cm->M; v++)
4051 beta[v][L][L] = cm->beginsc[v];
4052 }
4053
4054 /* Main recursion */
4055 for (v = 1; v < cm->M; v++) { /* start at state 1 because we set all values for ROOT_S state 0 above */
4056 sd = StateDelta(cm->sttype[v]);
4057 sdr = StateRightDelta(cm->sttype[v]);
4058
4059 if (cm->stid[v] == BEGL_S) { /* BEGL_S */
4060 y = cm->plast[v]; /* the parent bifurcation */
4061 z = cm->cnum[y]; /* the other (right) S state */
4062 for(j = 0; j <= L; j++) {
4063 for (d = 0; d <= j; d++) {
4064 for (k = 0; k <= (L-j); k++) {
4065 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j+k][d+k] + alpha[z][j+k][k]));
4066 }
4067 }
4068 }
4069 } /* end of 'if (cm->stid[v] == BEGL_S */
4070 else if (cm->stid[v] == BEGR_S) {
4071 y = cm->plast[v]; /* the parent bifurcation */
4072 z = cm->cfirst[y]; /* the other (left) S state */
4073 for(j = 0; j <= L; j++) {
4074 for (d = 0; d <= j; d++) {
4075 for (k = 0; k <= (j-d); k++) {
4076 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j][d+k] + alpha[z][j-d][k]));
4077 }
4078 }
4079 }
4080 } /* end of 'else if (cm->stid[v] == BEGR_S */
4081 else { /* (cm->sttype[v] != BEGL_S && cm->sttype[v] != BEGR_S */
4082 for (j = L; j >= 0; j--) {
4083 i = 1;
4084 for (d = j; d >= 0; d--, i++) {
4085 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
4086 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
4087 sd = StateDelta(cm->sttype[y]);
4088 sdr = StateRightDelta(cm->sttype[y]);
4089 switch(cm->sttype[y]) {
4090 case MP_st:
4091 if (j == L || d == j) continue; /* boundary condition */
4092 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
4093 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
4094 break;
4095
4096 case ML_st:
4097 case IL_st:
4098 if (d == j) continue; /* boundary condition (note when j=0, d=0*/
4099 escore = esc_vAA[y][dsq[i-1]];
4100 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
4101 break;
4102
4103 case MR_st:
4104 case IR_st:
4105 if (j == L) continue;
4106 escore = esc_vAA[y][dsq[j+1]];
4107 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset] + escore));
4108 break;
4109
4110 case S_st:
4111 case E_st:
4112 case D_st:
4113 beta[v][j][d] = FLogsum(beta[v][j][d], (beta[y][j+sdr][d+sd] + cm->tsc[y][voffset]));
4114 break;
4115 } /* end of switch(cm->sttype[y] */
4116 } /* ends for loop over parent states. we now know beta[v][j][d] for this d */
4117 if (beta[v][j][d] < IMPOSSIBLE) beta[v][j][d] = IMPOSSIBLE;
4118 } /* ends loop over d. We know all beta[v][j][d] in this row j and state v */
4119 } /* end loop over j. We know beta for this whole state */
4120 } /* end of 'else if cm->sttype[v] != BEGL_S, BEGR_S */
4121 /* we're done calculating deck v for everything but local begins */
4122
4123 /* deal with local alignment end transitions v->EL (EL = deck at M.) */
4124 if ((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
4125 sdr = StateRightDelta(cm->sttype[v]); /* note sdr is for state v */
4126 sd = StateDelta(cm->sttype[v]); /* note sd is for state v */
4127
4128 for (j = 0; j <= L; j++) {
4129 for (d = 0; d <= j; d++) {
4130 i = j-d+1;
4131 switch (cm->sttype[v]) {
4132 case MP_st:
4133 if (j == L || d == j) continue; /* boundary condition */
4134 escore = esc_vAA[v][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
4135 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
4136 + escore));
4137 break;
4138 case ML_st:
4139 case IL_st:
4140 if (d == j) continue;
4141 escore = esc_vAA[v][dsq[i-1]];
4142 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
4143 + escore));
4144 break;
4145 case MR_st:
4146 case IR_st:
4147 if (j == L) continue;
4148 escore = esc_vAA[v][dsq[j+1]];
4149 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]
4150 + escore));
4151 break;
4152 case S_st:
4153 case D_st:
4154 case B_st:
4155 case E_st:
4156 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][j+sdr][d+sd] + cm->endsc[v]));
4157 break;
4158 }
4159 }
4160 }
4161 }
4162 }
4163 /* Deal with last step needed for local alignment
4164 * w.r.t. ends: left-emitting, EL->EL transitions. (EL = deck at M.)
4165 */
4166 if (cm->flags & CMH_LOCAL_END) {
4167 for (j = L; j > 0; j--) { /* careful w/ boundary here */
4168 for (d = j-1; d >= 0; d--) /* careful w/ boundary here */
4169 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[cm->M][j][d+1] + cm->el_selfsc));
4170 }
4171 }
4172
4173 if(do_check && (!(cm->flags & CMH_LOCAL_END))) {
4174 /* Local ends make the following test invalid because it is not true that
4175 * exactly 1 state in each node's split set must be visited in each parse.
4176 *
4177 * Determine P(S|M) / P(S|R) (probability of the sequence given the model)
4178 * using both the Outside (beta) and Inside (alpha) matrices,
4179 * and ensure they're consistent with P(S|M) / P(S|R) from the Inside calculation.
4180 * For all v in each split set: Sum_v [ Sum_j,(d<=j) ( alpha[v][j][d] * beta[v][j][d] ) ]
4181 * = P(S|M) / P(S|R)
4182 */
4183 for(n = 0; n < cm->nodes; n++) {
4184 sc = IMPOSSIBLE;
4185 num_split_states = SplitStatesInNode(cm->ndtype[n]);
4186 for(v = cm->nodemap[n]; v < cm->nodemap[n] + num_split_states; v++) {
4187 for (j = 0; j <= L; j++) {
4188 for (d = 0; d <= j; d++) {
4189 sc = FLogsum(sc, (alpha[v][j][d] + beta[v][j][d]));
4190 }
4191 }
4192 }
4193 /*printf("checking node: %d | sc: %.6f\n", n, sc);*/
4194 diff = sc - alpha[0][L][L];
4195 if(diff > 0.01 || diff < -0.01) {
4196 fail_flag = TRUE;
4197 printf("ERROR: node %d P(S|M): %.5f inconsistent with Inside P(S|M): %.5f (diff: %.5f)\n",
4198 n, sc, alpha[0][L][L], diff);
4199 }
4200 }
4201 if(! fail_flag) {
4202 ESL_DPRINTF1(("#DEBUG: SUCCESS! all nodes passed error check (cm_OutsideAlign())\n"));
4203 }
4204 }
4205
4206 /* Finally, calculate the optimal score, but this only works if
4207 * we're not in local mode:
4208 *
4209 * IF local ends are off, we know each parse MUST visit each END_E state,
4210 * we pick final END_E state state cm->M-1 (though any END_E could be used here):
4211 *
4212 * Sum_j=0 to L (alpha[M-1][j][0] * beta[M-1][j][0]) = P(S|M) / P(S|R)
4213 *
4214 * Note: alpha[M-1][j][0] = 0.0 for all j
4215 * because all parse subtrees rooted at an END_E must have d=0, (2^0 = 1.0)
4216 * therefore:
4217 * Sum_j=0 to L (beta[M-1][j][0]) = P(S|M) / P(S|R)
4218 *
4219 * *** If local ends are on, each parse MUST visit either each END_E state with d=0
4220 * or the EL state but d can vary, so we can't use this test (believe me I tried
4221 * to get a similar test working, but I'm convinced you need alpha to get P(S|M)
4222 * in local mode).
4223 */
4224 if(!(cm->flags & CMH_LOCAL_END)) {
4225 sc = IMPOSSIBLE;
4226 v = cm->M-1;
4227 for (j = 0; j <= L; j++) {
4228 sc = FLogsum(sc, (beta[v][j][0]));
4229 /*printf("\talpha[%3d][%3d][%3d]: %5.2f | beta[%3d][%3d][%3d]: %5.2f\n", (cm->M-1), (j), 0, alpha[(cm->M-1)][j][0], (cm->M-1), (j), 0, beta[(cm->M-1)][j][0]);*/
4230 }
4231 }
4232 else { /* sc = P(S|M) / P(S|R) from Inside() */
4233 sc = alpha[0][L][L];
4234 }
4235
4236 if(fail_flag) ESL_FAIL(eslFAIL, errbuf, "Not all nodes passed posterior check.");
4237
4238 #if eslDEBUGLEVEL >= 3
4239 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
4240 /* FILE *fp1; fp1 = fopen("tmp.std_omx", "w"); cm_mx_Dump(fp1, mx); fclose(fp1); */
4241 #endif
4242
4243 if(!(cm->flags & CMH_LOCAL_END)) ESL_DPRINTF1(("#DEBUG: \tcm_OutsideAlign() sc : %f\n", sc));
4244 else ESL_DPRINTF1(("#DEBUG: \tcm_OutsideAlign() sc : %f (LOCAL mode; sc is from Inside)\n", sc));
4245
4246 if(ret_sc != NULL) *ret_sc = sc;
4247
4248 return eslOK;
4249 }
4250
4251 /* Function: cm_OutsideAlignHB()
4252 * Date: EPN, Thu Nov 8 18:40:05 2007
4253 *
4254 * Purpose: Run the outside algorithm on a target sequence.
4255 * HMM banded version. See cm_OutsideAlign() for
4256 * the non-banded version. The full target sequence
4257 * 1..L is aligned.
4258 *
4259 * Very similar to cm_CYKOutsideAlignHB() but calculates
4260 * beta[v][j][d]: log of the summed probability of all
4261 * parsetrees that emits 1..i-1 and j+1..L and pass through
4262 * v at j,d (where i = j-d+1) instead of the log of the
4263 * probability of the most likely (CYK) parse. This means
4264 * logsum operations are used instead of max operations.
4265 *
4266 * For debugging this function, the cm_CYKOutsideAlign() can
4267 * be useful, because it has a very similar organization but
4268 * is easier to debug because only the most likely parsetree
4269 * is considered. cm_CYKOutsideAlign() also allows a more
4270 * stringent test for the consistency of the CYKInside and
4271 * CYKOutside matrices.
4272 *
4273 * The DP recursion has been 'optimized' for all state types
4274 * except IL, IR, BEGL_S, BEGR_S. The main optimization
4275 * is a change in nesting order of the for loops:
4276 * optimized order: for v { for y { for j { for d {}}}}
4277 * non-optimized order: for v { for j { for d { for y {}}}}
4278 *
4279 * ILs and IRs are not optimized because they can self
4280 * transit so mx[v][j][d] must be fully calc'ed before
4281 * mx[v][j][d+1] can be calced. BEGL_S and BEGR_S are not
4282 * optimized b/c they require searching for optimal d and k,
4283 * which complicates the enforcement of the bands and makes
4284 * this optimization strategy impossible.
4285 *
4286 * If <do_check> is TRUE (and the CM is not in local mode)
4287 * we check that the outside matrix values are consistent
4288 * with the inside matrix values (in ins_mx). This check is
4289 * described in comments towards the end of the function.
4290 *
4291 * Note: renamed from FastOutsideAlignHB() [EPN, Wed Sep 14 06:13:53 2011].
4292 *
4293 * Args: cm - the model
4294 * errbuf - char buffer for reporting errors
4295 * dsq - the digitized sequence
4296 * L - length of the dsq to align
4297 * size_limit- max number of Mb for DP matrix, if matrix is bigger return eslERANGE
4298 * do_check - TRUE to attempt to check
4299 * mx - the dp matrix, only cells within bands in cp9b will be valid
4300 * ins_mx - the dp matrix from the Inside run calculation (required)
4301 * ret_sc - RETURN: log P(S|M)/P(S|R), as a bit score, this is from ins_mx IF local
4302 * ends are on (see *** comment towards end of function).
4303 *
4304 * Returns: <eslOK> on success
4305 *
4306 * Throws: <eslERANGE> if required CM_HB_MX size exceeds <size_limit>
4307 * <eslFAIL> if <do_check>==TRUE and we fail a test
4308 * In either of these cases, alignment has been aborted, ret_sc is not valid.
4309 */
4310 int
4311 cm_OutsideAlignHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, float size_limit, int do_check,
4312 CM_HB_MX *mx, CM_HB_MX *ins_mx, float *ret_sc)
4313 {
4314 int status;
4315 int v,y,z; /* indices for states */
4316 int j,d,i,k; /* indices in sequence dimensions */
4317 float **esc_vAA; /* ptr to cm->oesc, optimized emission scores */
4318 float sc; /* a temporary score */
4319 float escore; /* an emission score, tmp variable */
4320 int voffset; /* index of v in t_v(y) transition scores */
4321 int emitmode; /* EMITLEFT, EMITRIGHT, EMITPAIR, EMITNONE, for state y */
4322 int sd; /* StateDelta(cm->sttype[y]) */
4323 int sdr; /* StateRightDelta(cm->sttype[y] */
4324
4325 /* variables used only if do_check */
4326 int fail_flag = FALSE; /* set to TRUE if do_check and we see a problem */
4327 int n; /* counter over nodes, used only if do_check = TRUE */
4328 int num_split_states; /* temp variable used only if do_check = TRUE */
4329 float diff; /* temp variable used only if do_check = TRUE */
4330
4331 /* band related variables */
4332 int dp_v; /* d index for state v in alpha w/mem eff bands */
4333 int dp_y; /* d index for state y in alpha w/mem eff bands */
4334 int kp_z; /* k (in the d dim) index for state z in alpha w/mem eff bands */
4335 int Lp; /* L index also changes depending on state */
4336 int jp_v, jp_y, jp_z; /* offset j index for states v, y, z */
4337 int kmin, kmax; /* temporary minimum/maximum allowed k */
4338 int jn, jx; /* current minimum/maximum j allowed */
4339 int dn, dx; /* current minimum/maximum d allowed */
4340 int jp_0; /* L offset in ROOT_S's (v==0) j band */
4341 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
4342
4343 /* the DP matrices */
4344 float ***beta = mx->dp; /* pointer to the Oustide DP mx */
4345 float ***alpha = ins_mx->dp; /* pointer to the Inside DP mx (already calc'ed and passed in) */
4346
4347 /* ptrs to cp9b info, for convenience */
4348 int *jmin = cm->cp9b->jmin;
4349 int *jmax = cm->cp9b->jmax;
4350 int **hdmin = cm->cp9b->hdmin;
4351 int **hdmax = cm->cp9b->hdmax;
4352
4353 /* Allocations and initializations */
4354 esc_vAA = cm->oesc; /* a ptr to the optimized emission scores */
4355
4356 /* grow the matrix based on the current sequence and bands */
4357 if((status = cm_hb_mx_GrowTo(cm, mx, errbuf, cm->cp9b, L, size_limit)) != eslOK) return status;
4358
4359 /* initialize all cells of the matrix to IMPOSSIBLE */
4360 esl_vec_FSet(beta[0][0], mx->ncells_valid, IMPOSSIBLE);
4361
4362 /* ensure a full alignment to ROOT_S (v==0) is allowed by the bands */
4363 if (jmin[0] > L || jmax[0] < L)
4364 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, jmin[0], jmax[0]);
4365 jp_0 = L - jmin[0];
4366 if (hdmin[0][jp_0] > L || hdmax[0][jp_0] < L)
4367 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, hdmin[0][jp_0], hdmax[0][jp_0]);
4368 Lp_0 = L - hdmin[0][jp_0];
4369 /* set the offset banded cell corresponding to beta[0][L][L] to 0., all parses must end there */
4370 beta[0][jp_0][Lp_0] = 0.;
4371
4372 /* If we can do a local begin into v, overwrite IMPOSSIBLE with the local begin score. */
4373 if (cm->flags & CMH_LOCAL_BEGIN) {
4374 for (v = 1; v < cm->M; v++) {
4375 if(NOT_IMPOSSIBLE(cm->beginsc[v])) {
4376 if((L >= jmin[v]) && (L <= jmax[v])) {
4377 jp_v = L - jmin[v];
4378 if((L >= hdmin[v][jp_v]) && L <= hdmax[v][jp_v]) {
4379 Lp = L - hdmin[v][jp_v];
4380 beta[v][jp_v][Lp] = cm->beginsc[v];
4381 }
4382 }
4383 }
4384 }
4385 }
4386 /* done allocation/initialization */
4387
4388 /* Recursion: main loop down through the decks */
4389 for (v = 1; v < cm->M; v++) { /* start at state 1 because we set all values for ROOT_S state 0 above */
4390 if (cm->stid[v] == BEGL_S) { /* BEGL_S */
4391 y = cm->plast[v]; /* the parent bifurcation */
4392 z = cm->cnum[y]; /* the other (right) S state */
4393 for (j = jmax[v]; j >= jmin[v]; j--) {
4394 ESL_DASSERT1((j >= 0 && j <= L));
4395 jp_v = j - jmin[v];
4396 jp_y = j - jmin[y];
4397 jp_z = j - jmin[z];
4398 i = j-d+1;
4399 for (d = hdmax[v][jp_v]; d >= hdmin[v][jp_v]; d--) {
4400 dp_v = d - hdmin[v][jp_v];
4401 /* Find the first k value that implies a valid cell in the y and z decks.
4402 * This k must satisfy the following 8 inequalities (some may be redundant):
4403 * NOTE: these are different from those in Inside() (for one thing, v and y
4404 * (BEGL_S and BIF_B here respectively) are switched relative to Inside.
4405 *
4406 * (1) k <= jmax[y] - j;
4407 * (2) k >= jmin[y] - j;
4408 * (3) k <= jmax[z] - j;
4409 * (4) k >= jmin[z] - j;
4410 * 1 and 2 guarantee (j+k) is within state y's j band
4411 * 3 and 4 guarantee (j+k) is within state z's j band
4412 *
4413 * (5) k >= hdmin[y][j-jmin[y]+k] - d;
4414 * (6) k <= hdmax[y][j-jmin[y]+k] - d;
4415 * 5 and 6 guarantee k+d is within y's j=(j+k), d band
4416 *
4417 * (7) k >= hdmin[z][j-jmin[z]+k];
4418 * (8) k <= hdmax[z][j-jmin[z]+k];
4419 * 5 and 6 guarantee k is within state z's j=(j+k) d band
4420 */
4421 kmin = ESL_MAX(jmin[y], jmin[z]) - j;
4422 kmax = ESL_MIN(jmax[y], jmax[z]) - j;
4423 /* kmin and kmax satisfy inequalities (1-4) */
4424 /* RHS of inequalities 5-8 are dependent on k, so we check
4425 * for these within the next for loop. */
4426 for(k = kmin; k <= kmax; k++) {
4427 if(k < (hdmin[y][jp_y+k] - d) || k > (hdmax[y][jp_y+k] - d)) continue;
4428 /* above line continues if inequality 5 or 6 is violated */
4429 if(k < (hdmin[z][jp_z+k]) || k > (hdmax[z][jp_z+k])) continue;
4430 /* above line continues if inequality 7 or 8 is violated */
4431
4432 /* if we get here for current k, all 8 inequalities have been satisified
4433 * so we know the cells corresponding to the platonic
4434 * matrix cells alpha[v][j][d], alpha[y][j+k][d+k], and
4435 * alpha[z][j+k][k] are all within the bands. These
4436 * cells correspond to beta[v][jp_v][dp_v],
4437 * beta[y][jp_y+k][d-hdmin[y][jp_y+k]+k],
4438 * and alpha[z][jp_z][k-hdmin[z][jp_z+k]];
4439 */
4440 kp_z = k-hdmin[z][jp_z+k];
4441 dp_y = d-hdmin[y][jp_y+k];
4442 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y+k][dp_y+k] + alpha[z][jp_z+k][kp_z]));
4443 }
4444 }
4445 }
4446 } /* end of 'if (cm->stid[v] == BEGL_S */
4447 else if (cm->stid[v] == BEGR_S) {
4448 y = cm->plast[v]; /* the parent bifurcation */
4449 z = cm->cfirst[y]; /* the other (left) S state */
4450 jn = ESL_MAX(jmin[v], jmin[y]);
4451 jx = ESL_MIN(jmax[v], jmax[y]);
4452 for (j = jx; j >= jn; j--) {
4453 ESL_DASSERT1((j >= 0 && j <= L));
4454 jp_v = j - jmin[v];
4455 jp_y = j - jmin[y];
4456 jp_z = j - jmin[z];
4457 i = j-d+1;
4458
4459 dn = ESL_MAX(hdmin[v][jp_v], j-jmax[z]);
4460 dx = ESL_MIN(hdmax[v][jp_v], jp_z);
4461 /* above makes sure that j,d are valid for state z: (jmin[z] + d) >= j >= (jmax[z] + d) */
4462 for (d = dx; d >= dn; d--) {
4463 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
4464 /* Find the first k value that implies a valid cell in the y and z decks.
4465 * This k must satisfy the following 4 inequalities (some may be redundant):
4466 * NOTE: these are different from those in Inside() (for one thing, v and y
4467 * (BEGR_S and BIF_B here respectively) are switched relative to Inside.
4468 *
4469 * (1) k >= hdmin[y][j-jmin[y]] - d;
4470 * (2) k <= hdmax[y][j-jmin[y]] - d;
4471 * 1 and 2 guarantee (d+k) is within state y's j=(j) d band
4472 *
4473 * (3) k >= hdmin[z][j-jmin[z]-d];
4474 * (4) k <= hdmax[z][j-jmin[z]-d];
4475 * 3 and 4 guarantee k is within z's j=(j-d) d band
4476 *
4477 */
4478 kmin = ESL_MAX((hdmin[y][jp_y]-d), (hdmin[z][jp_z-d]));
4479 kmax = ESL_MIN((hdmax[y][jp_y]-d), (hdmax[z][jp_z-d]));
4480 /* kmin and kmax satisfy inequalities (1-4) */
4481 for(k = kmin; k <= kmax; k++) {
4482 /* for current k, all 4 inequalities have been satisified
4483 * so we know the cells corresponding to the platonic
4484 * matrix cells beta[v][j][d], beta[y][j][d+k], and
4485 * alpha[z][j-d][k] are all within the bands. These
4486 * cells correspond to beta[v][jp_v][dp_v],
4487 * beta[y][jp_y+k][d-hdmin[y][jp_y]+k],
4488 * and alpha[z][jp_z-d][k-hdmin[z][jp_z-d]];
4489 */
4490 kp_z = k-hdmin[z][jp_z-d];
4491 dp_y = d-hdmin[y][jp_y];
4492 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y+k]
4493 + alpha[z][jp_z-d][kp_z]));
4494 }
4495 }
4496 }
4497 } /* end of 'else if (cm->stid[v] == BEGR_S */
4498 else if (cm->sttype[v] == IL_st || cm->sttype[v] == IR_st) {
4499 /* ILs and IRs can self transit, this means that beta[v][j][d] must be fully calculated
4500 * before beta[v][j][d+1] can be started to be calculated, forcing the following nesting order:
4501 * for j { for d { for y { } } }
4502 * for non-self-transitioners, we can do a more efficient nesting order (see below)
4503 */
4504 for (j = jmax[v]; j >= jmin[v]; j--) {
4505 ESL_DASSERT1((j >= 0 && j <= L));
4506 jp_v = j - jmin[v];
4507 for (d = hdmax[v][jp_v]; d >= hdmin[v][jp_v]; d--) {
4508 i = j-d+1;
4509 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
4510
4511 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
4512 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
4513
4514 /* Note: this looks like it can be optimized, I tried but my 'optimization' slowed the code, so I reverted [EPN] */
4515 switch(cm->sttype[y]) {
4516 case MP_st:
4517 if (j == L || d == j) continue; /* boundary condition */
4518 if ((j+1) < jmin[y] || (j+1) > jmax[y]) continue; /* enforces j is valid for state y */
4519 jp_y = j - jmin[y];
4520 if ((d+2) < hdmin[y][(jp_y+1)] || (d+2) > hdmax[y][(jp_y+1)]) continue; /* enforces d is valid for state y */
4521 /* if we get here alpha[y][jp_y+1][dp_y+2] is a valid alpha cell
4522 * corresponding to alpha[y][j+1][d+2] in the platonic matrix.
4523 */
4524 dp_y = d - hdmin[y][jp_y+1]; /* d index for state y */
4525 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
4526 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y+1][dp_y+2]
4527 + cm->tsc[y][voffset] + escore));
4528 break;
4529
4530 case ML_st:
4531 case IL_st:
4532 if (d == j) continue; /* boundary condition (note when j=0, d=0)*/
4533 if (j < jmin[y] || j > jmax[y]) continue; /* enforces j is valid for state y */
4534 jp_y = j - jmin[y];
4535 if ((d+1) < hdmin[y][jp_y] || (d+1) > hdmax[y][jp_y]) continue; /* enforces d is valid for state y */
4536 /* if we get here alpha[y][jp_y][dp_y+1] is a valid alpha cell
4537 * corresponding to alpha[y][j][d+1] in the platonic matrix.
4538 */
4539 dp_y = d - hdmin[y][jp_y]; /* d index for state y */
4540 escore = esc_vAA[y][dsq[i-1]];
4541 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y+1]
4542 + cm->tsc[y][voffset] + escore));
4543 break;
4544
4545 case MR_st:
4546 case IR_st:
4547 if (j == L) continue;
4548 if ((j+1) < jmin[y] || (j+1) > jmax[y]) continue; /* enforces j is valid for state y */
4549 jp_y = j - jmin[y];
4550 if ((d+1) < hdmin[y][(jp_y+1)] || (d+1) > hdmax[y][(jp_y+1)]) continue; /* enforces d is valid for state y */
4551 /* if we get here alpha[y][jp_y+1][dp_y+1] is a valid alpha cell
4552 * corresponding to alpha[y][j+1][d+1] in the platonic matrix.
4553 */
4554 dp_y = d - hdmin[y][(jp_y+1)]; /* d index for state y */
4555 escore = esc_vAA[y][dsq[j+1]];
4556 /*printf("j: %d | jmin[y]: %d | jmax[y]: %d | jp_v: %d | dp_v: %d | jp_y: %d | dp_y: %d\n", j, jmin[y], jmax[y], jp_v, dp_v, jp_y, dp_y);*/
4557 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y+1][dp_y+1]
4558 + cm->tsc[y][voffset] + escore));
4559 break;
4560
4561 case S_st:
4562 case E_st:
4563 case D_st:
4564 if (j < jmin[y] || j > jmax[y]) continue; /* enforces j is valid for state y */
4565 jp_y = j - jmin[y];
4566 if (d < hdmin[y][jp_y] || d > hdmax[y][jp_y]) continue; /* enforces d is valid for state y */
4567 /* if we get here alpha[y][jp_y][dp_y] is a valid alpha cell
4568 * corresponding to alpha[y][j][d] in the platonic matrix.
4569 */
4570 dp_y = d - hdmin[y][jp_y]; /* d index for state y */
4571 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y][dp_y] + cm->tsc[y][voffset]));
4572 break;
4573 } /* end of switch(cm->sttype[y] */
4574 } /* ends for loop over parent states. we now know beta[v][j][d] for this d */
4575 if (beta[v][jp_v][dp_v] < IMPOSSIBLE) beta[v][jp_v][dp_v] = IMPOSSIBLE;
4576 } /* ends loop over d. We know all beta[v][j][d] in this row j and state v */
4577 } /* end loop over jp. We know beta for this whole state */
4578 } /* end of 'else if cm->sttype[v] == IL_st || cm->sttype[v] == IR_st' */
4579 else { /* state v is not BEGL_S, BEGL_R IL nor IR (must be ML, MP, MR, D, S, B or E) */
4580 /* ML, MP, MR, D, S, B, E states cannot self transit, this means that all cells
4581 * in beta[v] are independent of each other, only depending on beta[y] for previously calc'ed y.
4582 * We can do the for loops in any nesting order, this implementation does what I think is most efficient:
4583 * for y { for j { for d { } } }
4584 */
4585 for (y = cm->plast[v]; y > cm->plast[v]-cm->pnum[v]; y--) {
4586 voffset = v - cm->cfirst[y]; /* gotta calculate the transition score index for t_y(v) */
4587 sdr = StateRightDelta(cm->sttype[y]);
4588 sd = StateDelta(cm->sttype[y]);
4589 emitmode = Emitmode(cm->sttype[y]);
4590 /* determine min j (jn) and max j (jx) that are valid for v and y */
4591 jn = ESL_MAX(jmin[v], jmin[y]-sdr);
4592 jx = ESL_MIN(jmax[v], jmax[y]-sdr);
4593 for (j = jx; j >= jn; j--) {
4594 ESL_DASSERT1((j >= 0 && j <= L));
4595 jp_v = j - jmin[v];
4596 jp_y = j - jmin[y];
4597 ESL_DASSERT1((j+sdr >= jmin[y] && j+sdr <= jmax[y]));
4598
4599 /* determine min d (dn) and max d (dx) that are valid for v and y and j */
4600 dn = ESL_MAX(hdmin[v][jp_v], hdmin[y][jp_y + sdr] - sd);
4601 dx = ESL_MIN(hdmax[v][jp_v], hdmax[y][jp_y + sdr] - sd);
4602 dp_v = dx - hdmin[v][jp_v];
4603 dp_y = dx - hdmin[y][jp_y + sdr];
4604 i = j-dx+1;
4605
4606 /* for each emit mode, update beta[v][jp_v][dp_v] for all valid d = dp_v */
4607 switch(emitmode) {
4608 case EMITPAIR: /* MP_st */
4609 for (d = dx; d >= dn; d--, dp_v--, dp_y--, i++) {
4610 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
4611 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
4612 escore = esc_vAA[y][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
4613 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
4614 + cm->tsc[y][voffset] + escore));
4615 }
4616 break;
4617 case EMITLEFT: /* ML_st, IL_st */
4618 for (d = dx; d >= dn; d--, dp_v--, dp_y--, i++) {
4619 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
4620 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
4621 escore = esc_vAA[y][dsq[i-1]];
4622 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
4623 + cm->tsc[y][voffset] + escore));
4624 }
4625 break;
4626 case EMITRIGHT: /* MR_st, IR_st */
4627 escore = esc_vAA[y][dsq[j+1]]; /* not dependent on i */
4628 for (d = dx; d >= dn; d--, dp_v--, dp_y--) {
4629 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
4630 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
4631 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
4632 + cm->tsc[y][voffset] + escore));
4633 }
4634 break;
4635 case EMITNONE: /* D_st, S_st, E_st*/
4636 for (d = dx; d >= dn; d--, dp_v--, dp_y--) {
4637 ESL_DASSERT1(( d >= hdmin[v][jp_v] && d <= hdmax[v][jp_v]));
4638 ESL_DASSERT1((((d + sd) >= hdmin[y][jp_y + sdr]) && ((d + sd) <= hdmax[y][jp_y + sdr])));
4639 beta[v][jp_v][dp_v] = FLogsum(beta[v][jp_v][dp_v], (beta[y][jp_y + sdr][dp_y + sd]
4640 + cm->tsc[y][voffset]));
4641 }
4642 break;
4643 } /* end of switch(emitmode) */
4644 } /* end of for j = jx; j >= jn; j-- */
4645 } /* end of for y = plast[v]... */
4646 } /* ends else entered for non-BEGL_S/BEGR_S/IL/IR states*/
4647 /* we're done calculating deck v for everything but local begins */
4648
4649 /* deal with local alignment end transitions v->EL (EL = deck at M.) */
4650 if ((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
4651 sdr = StateRightDelta(cm->sttype[v]); /* note sdr is for state v */
4652 sd = StateDelta(cm->sttype[v]); /* note sd is for state v */
4653 emitmode = Emitmode(cm->sttype[v]); /* note emitmode is for state v */
4654
4655 jn = jmin[v] - sdr;
4656 jx = jmax[v] - sdr;
4657 for (j = jn; j <= jx; j++) {
4658 jp_v = j - jmin[v];
4659 dn = hdmin[v][jp_v + sdr] - sd;
4660 dx = hdmax[v][jp_v + sdr] - sd;
4661 i = j-dn+1; /* we'll decrement this in for (d... loops inside switch below */
4662 dp_v = dn - hdmin[v][jp_v + sdr]; /* we'll increment this in for (d... loops inside switch below */
4663
4664 switch (emitmode) {
4665 case EMITPAIR:
4666 for (d = dn; d <= dx; d++, dp_v++, i--) {
4667 escore = esc_vAA[v][dsq[i-1]*cm->abc->Kp+dsq[j+1]];
4668 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
4669 + escore));
4670 }
4671 break;
4672 case EMITLEFT:
4673 for (d = dn; d <= dx; d++, dp_v++, i--) {
4674 escore = esc_vAA[v][dsq[i-1]];
4675 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
4676 + escore));
4677 }
4678 break;
4679
4680 case EMITRIGHT:
4681 escore = esc_vAA[v][dsq[j+1]];
4682 for (d = dn; d <= dx; d++, dp_v++) {
4683 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]
4684 + escore));
4685 }
4686 break;
4687
4688 case EMITNONE:
4689 for (d = dn; d <= dx; d++, dp_v++) {
4690 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[v][jp_v+sdr][dp_v+sd] + cm->endsc[v]));
4691 }
4692 break;
4693 }
4694 }
4695 }
4696 } /* end loop over decks v. */
4697
4698 /* Deal with last step needed for local alignment
4699 * w.r.t. ends: left-emitting, EL->EL transitions. (EL = deck at M.)
4700 */
4701 if (cm->flags & CMH_LOCAL_END) {
4702 for (j = L; j > 0; j--) { /* careful w/ boundary here */
4703 for (d = j-1; d >= 0; d--) /* careful w/ boundary here */
4704 beta[cm->M][j][d] = FLogsum(beta[cm->M][j][d], (beta[cm->M][j][d+1] + cm->el_selfsc));
4705 }
4706 }
4707
4708 if(do_check && (!(cm->flags & CMH_LOCAL_END))) {
4709 /* Local ends make the following test invalid because it is not true that
4710 * exactly 1 state in each node's split set must be visited in each parse.
4711 *
4712 * Determine P(S|M) / P(S|R) (probability of the sequence given the model)
4713 * using both the Outside (beta) and Inside (alpha) matrices,
4714 * and ensure they're consistent with P(S|M) / P(S|R) from the Inside calculation.
4715 * For all v in each split set: Sum_v [ Sum_j,(d<=j) ( alpha[v][j][d] * beta[v][j][d] ) ]
4716 * = P(S|M) / P(S|R)
4717 */
4718
4719 for(n = 0; n < cm->nodes; n++) {
4720 sc = IMPOSSIBLE;
4721 num_split_states = SplitStatesInNode(cm->ndtype[n]);
4722 for(v = cm->nodemap[n]; v < cm->nodemap[n] + num_split_states; v++) {
4723 for (j = jmin[v]; j <= jmax[v]; j++) {
4724 jp_v = j - jmin[v];
4725 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
4726 dp_v = d - hdmin[v][jp_v]; /* d index for state v in alpha w/mem eff bands */
4727 sc = FLogsum(sc, (alpha[v][jp_v][dp_v] + beta[v][jp_v][dp_v]));
4728 /*printf("node %d | adding alpha beta: v: %d | jp_v: %d | dp_v: %d| j: %d | d: %d\n", n, v, jp_v, dp_v, j, d);
4729 printf("\talpha: %f | beta: %f\n", alpha[v][jp_v][dp_v], beta[v][jp_v][dp_v]);*/
4730 }
4731 }
4732 }
4733 /*printf("checking node: %d | sc: %.6f\n", n, sc);*/
4734 diff = sc - alpha[0][jp_0][Lp_0];
4735 if(diff > 0.01 || diff < -0.01) {
4736 fail_flag = TRUE;
4737 printf("ERROR: node %d P(S|M): %.5f inconsistent with Inside P(S|M): %.5f (diff: %.5f)\n",
4738 n, sc, alpha[0][jp_0][Lp_0], diff);
4739 }
4740 }
4741 }
4742
4743 /* If not in local mode, we can calculate P(S|M) / P(S|R) given only the
4744 * beta matrix as follows:
4745 *
4746 * IF local ends are off, we know each parse MUST visit each END_E state,
4747 * we pick final END_E state state cm->M-1 (though any END_E could be used here):
4748 *
4749 * Sum_j=0 to W (alpha[M-1][j][0] * beta[M-1][j][0]) = P(S|M) / P(S|R)
4750 *
4751 * Note: alpha[M-1][j][0] = 0.0 for all j
4752 * because all parse subtrees rooted at an END_E must have d=0, (2^0 = 1.0)
4753 * therefore:
4754 * Sum_j=0 to W (beta[M-1][j][0]) = P(S|M) / P(S|R)
4755 *
4756 * *** If local ends are on, each parse MUST visit either each END_E state with d=0
4757 * or the EL state but d can vary, so we can't use this test (believe me I tried
4758 * to get a similar test working, but I'm convinced you need alpha to get P(S|M)
4759 * in local mode).
4760 */
4761 if(!(cm->flags & CMH_LOCAL_END)) {
4762 sc = IMPOSSIBLE;
4763 v = cm->M-1;
4764 for (j = jmin[v]; j <= jmax[v]; j++) {
4765 jp_v = j - jmin[v];
4766 assert(hdmin[v][jp_v] == 0);
4767 sc = FLogsum(sc, (beta[v][jp_v][0]));
4768 /* printf("\talpha[%3d][%3d][%3d]: %5.2f | beta[%3d][%3d][%3d]: %5.2f\n", (cm->M-1), (j), 0, alpha[(cm->M-1)][j][0], (cm->M-1), (j), 0, beta[(cm->M-1)][j][0]);*/
4769 }
4770 }
4771 else { /* return_sc = P(S|M) / P(S|R) from Inside() */
4772 sc = alpha[0][jp_0][Lp_0];
4773 }
4774
4775 if(fail_flag) ESL_FAIL(eslFAIL, errbuf, "Not all nodes passed posterior check.");
4776
4777 #if eslDEBUGLEVEL >= 3
4778 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
4779 /* FILE *fp1; fp1 = fopen("tmp.std_ohbmx", "w"); cm_hb_mx_Dump(fp1, mx); fclose(fp1); */
4780 #endif
4781
4782
4783 if(!(cm->flags & CMH_LOCAL_END)) ESL_DPRINTF1(("#DEBUG: \tcm_OutsideAlignHB() sc : %f\n", sc));
4784 else ESL_DPRINTF1(("#DEBUG: \tcm_OutsideAlignHB() sc : %f (LOCAL mode; sc is from Inside)\n", sc));
4785
4786 if (ret_sc != NULL) *ret_sc = sc;
4787 return eslOK;
4788 }
4789
4790 /* Function: cm_Posterior()
4791 * Date: EPN, Mon Nov 19 09:02:12 2007
4792 * Note: based on Ian Holmes' P7EmitterPosterior() from HMMER's 2.x postprob.c
4793 * Renamed from CMPosterior() [EPN, Wed Sep 14 06:15:22 2011].
4794 *
4795 * Purpose: Combines non-banded Inside and Outside matrices into a
4796 * posterior probability matrix. The value in post[v][j][d]
4797 * is the log of the posterior probability of a parse
4798 * subtree rooted at v emitting the subsequence i..j
4799 * (i=j-d+1). The caller must provide a <post> float
4800 * matrix, but this matrix may be the same matrix as that
4801 * provided as Outside <out_mx>, (overwriting it will not
4802 * compromise the algorithm). Posteriors are calculated
4803 * for the full sequence 1..L.
4804 *
4805 *
4806 * Args: cm - the model
4807 * errbuf - char buffer for reporting errors
4808 * L - length of the dsq to align
4809 * size_limit - max number of Mb for DP matrix
4810 * ins_mx - pre-calculated Inside matrix
4811 * out_mx - pre-calculated Outside matrix
4812 * post_mx - pre-allocated matrix for Posteriors
4813 *
4814 * Returns: <eslOK> on success.
4815 * Throws: <eslERANGE> if required DP matrix size exceeds <size_limit>, in
4816 * this case, post_mx is not filled.
4817 */
4818 int
4819 cm_Posterior(CM_t *cm, char *errbuf, int L, float size_limit, CM_MX *ins_mx, CM_MX *out_mx, CM_MX *post_mx)
4820 {
4821 int status;
4822 int v, j, d; /* state, position, subseq length */
4823 int vmax; /* cm->M if local ends on, else cm->M-1 */
4824 float sc; /* optimal score, from Inside matrix */
4825
4826 /* the DP matrices */
4827 float ***alpha = ins_mx->dp; /* pointer to the alpha DP matrix */
4828 float ***beta = out_mx->dp; /* pointer to the beta DP matrix */
4829 float ***post = post_mx->dp; /* pointer to the post DP matrix */
4830
4831 /* grow our post matrix, but only if isn't also our out_mx in which
4832 * case we know we're already big enought (also in that case we
4833 * don't want to call GrowTo b/c it can potentially free the DP
4834 * matrix memory and reallocate it, which would be bad b/c we
4835 * need the out_mx!)
4836 */
4837 if(post_mx != out_mx) {
4838 if((status = cm_mx_GrowTo(cm, post_mx, errbuf, L, size_limit)) != eslOK) return status;
4839 }
4840
4841 sc = ins_mx->dp[0][L][L];
4842
4843 /* If local ends are on, start with the EL state (cm->M), otherwise
4844 * its not a valid deck.
4845 */
4846 vmax = (cm->flags & CMH_LOCAL_END) ? cm->M : cm->M-1;
4847 for (v = vmax; v >= 0; v--) {
4848 for (j = 0; j <= L; j++) {
4849 for (d = 0; d <= j; d++) {
4850 post[v][j][d] = alpha[v][j][d] + beta[v][j][d] - sc;
4851 }
4852 }
4853 }
4854
4855 #if eslDEBUGLEVEL >= 3
4856 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
4857 /* FILE *fp1; fp1 = fopen("tmp.std_pmx", "w"); cm_mx_Dump(fp1, post_mx); fclose(fp1); */
4858 #endif
4859
4860 return eslOK;
4861 }
4862
4863 /* Function: cm_PosteriorHB()
4864 * Date: EPN 05.27.06
4865 * Note: based on Ian Holmes' P7EmitterPosterior() from HMMER's 2.x postprob.c
4866 * Renamed from CMPosteriorHB() [EPN, Wed Sep 14 06:14:48 2011].
4867 *
4868 * Purpose: Combines HMM banded Inside and Outside matrices into a
4869 * posterior probability matrix. Any cells outside of HMM
4870 * bands do not exist in memory. The value in
4871 * post[v][jp_v][dp_v] is the log of the posterior
4872 * probability of a parse subtree rooted at v emitting the
4873 * subsequence i..j (i=j-d+1). Where j = jp_v + jmin[v], and
4874 * d = dp_v + hdmin[v][jp_v]. The caller must provide a
4875 * <post> CM_HB_MX matrix, but this matrix may be the same
4876 * matrix as that provided as Outside <out_mx>, (overwriting
4877 * it will not compromise the algorithm). Posteriors are
4878 * calculated for the full sequence 1..L.
4879 *
4880 * Args: cm - the model
4881 * errbuf - char buffer for reporting errors
4882 * L - length of the dsq to align
4883 * size_limit - max number of Mb for DP matrix, if matrix is bigger return eslERANGE
4884 * ins_mx - pre-calculated Inside matrix
4885 * out_mx - pre-calculated Outside matrix
4886 * post_mx - pre-allocated matrix for Posteriors
4887 *
4888 * Returns: <eslOK> on success.
4889 * Throws: <eslERANGE> if required DP matrix size exceeds <size_limit>
4890 * <eslEINVAL> if the full sequence is not within the bands for state 0
4891 * In either case the post_mx is not filled
4892 */
4893 int
4894 cm_PosteriorHB(CM_t *cm, char *errbuf, int L, float size_limit, CM_HB_MX *ins_mx, CM_HB_MX *out_mx, CM_HB_MX *post_mx)
4895 {
4896 int status;
4897 int v, j, d; /* state, position, position, subseq length */
4898 float sc; /* total score, the log probability of the current seq */
4899 int jp_v; /* j index for state v in alpha/beta with HMM bands */
4900 int dp_v; /* d index for state v in alpha/beta with HMM bands */
4901 int jp_0; /* L offset in ROOT_S's (v==0) j band */
4902 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
4903
4904 /* the DP matrices */
4905 float ***alpha = ins_mx->dp; /* pointer to the alpha DP matrix */
4906 float ***beta = out_mx->dp; /* pointer to the beta DP matrix */
4907 float ***post = post_mx->dp; /* pointer to the post DP matrix */
4908
4909 /* ptrs to cp9b info, for convenience */
4910 int *jmin = cm->cp9b->jmin;
4911 int *jmax = cm->cp9b->jmax;
4912 int **hdmin = cm->cp9b->hdmin;
4913 int **hdmax = cm->cp9b->hdmax;
4914
4915 /* ensure a full alignment to ROOT_S (v==0) is allowed by the bands */
4916 if (cm->cp9b->jmin[0] > L || cm->cp9b->jmax[0] < L)
4917 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cm->cp9b->jmin[0], cm->cp9b->jmax[0]);
4918 jp_0 = L - jmin[0];
4919 if (cm->cp9b->hdmin[0][jp_0] > L || cm->cp9b->hdmax[0][jp_0] < L)
4920 ESL_FAIL(eslEINVAL, errbuf, "cm_CYKInsideAlignHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cm->cp9b->hdmin[0][jp_0], cm->cp9b->hdmax[0][jp_0]);
4921 Lp_0 = L - hdmin[0][jp_0];
4922
4923 sc = alpha[0][jp_0][Lp_0];
4924
4925 /* grow our post matrix, but only if isn't also our out_mx in which
4926 * case we know we're already big enought (also in that case we
4927 * don't want to call GrowTo b/c it can potentially free the DP
4928 * matrix memory and reallocate it, which would be bad b/c we
4929 * need the out_mx!)
4930 */
4931 if(post_mx != out_mx) {
4932 if((status = cm_hb_mx_GrowTo(cm, post_mx, errbuf, cm->cp9b, L, size_limit)) != eslOK) return status;
4933 }
4934
4935 /* If local ends are on, start with the EL state (cm->M), otherwise
4936 * M deck is not valid. Note: there are no bands on the EL state
4937 */
4938 if (cm->flags & CMH_LOCAL_END) {
4939 for(j = 0; j <= L; j++) {
4940 for (d = 0; d <= j; d++) {
4941 post[cm->M][j][d] = alpha[cm->M][j][d] + beta[cm->M][j][d] - sc;
4942 }
4943 }
4944 }
4945
4946 for (v = (cm->M-1); v >= 0; v--) {
4947 for (j = jmin[v]; j <= jmax[v]; j++) {
4948 ESL_DASSERT1((j >= 0 && j <= L));
4949 jp_v = j - jmin[v];
4950 for (d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
4951 dp_v = d - hdmin[v][jp_v];
4952 post[v][jp_v][dp_v] = alpha[v][jp_v][dp_v] + beta[v][jp_v][dp_v] - sc;
4953 /*printf("v: %3d | jp_v: %3d | dp_v: %3d | alpha: %5.2f | beta: %5.2f\n", v, jp_v, dp_v, alpha[v][jp_v][dp_v], beta[v][jp_v][dp_v]);*/
4954 }
4955 }
4956 }
4957 return eslOK;
4958 }
4959
4960 /* Function: cm_EmitterPosterior()
4961 * Date: EPN, Fri Sep 30 13:53:57 2011
4962 *
4963 * Purpose: Given a posterior probability cube, where the value in
4964 * post[v][j][d] is the log of the posterior probability of
4965 * a parse subtree rooted at v emitting the subsequence i..j
4966 * (i=j-d+1), fill a CM_EMIT_MX <emit_mx> with two 2-dimensional
4967 * matrices with values:
4968 *
4969 * emit_mx->l_pp[v][i]: log of the posterior probability that
4970 * state v emitted residue i leftwise either at (if a match
4971 * state) or *after* (if an insert state) the left consensus
4972 * position modeled by state v's node.
4973 *
4974 * emit_mx->r_pp[v][i]: log of the posterior probability that
4975 * state v emitted residue i rightwise either at (if a match
4976 * state) or *before* (if an insert state) the right
4977 * consensus position modeled by state v's node.
4978 *
4979 * l_pp[v] is NULL for states that do not emit leftwise
4980 * r_pp[v] is NULL for states that do not emit rightwise
4981 *
4982 * This is done in 3 steps:
4983 * 1. Fill l_pp[v][i] and r_pp[v][i] with the posterior
4984 * probability that state v emitted residue i either
4985 * leftwise (l_pp) or rightwise (r_pp).
4986 *
4987 * 2. Normalize l_pp and r_pp so that probability that
4988 * each residue was emitted by any state is exactly
4989 * 1.0.
4990 *
4991 * 3. Combine l_pp values for MATP_MP (v) and MATP_ML (y=v+1)
4992 * states in the same node so they give the value defined
4993 * above (i.e. l_pp[v] == l_pp[y] = the PP that either v
4994 * or y emitted residue i) instead of l_pp[v] = PP that v
4995 * emitted i, and l_pp[y] = PP that y emitted i. And
4996 * combine r_pp values for MATP_MP (v) and MATP_MR (y=v+2)
4997 * states in an analogous way.
4998 *
4999 * If <do_check> we check to make sure the summed probability
5000 * of any residue is > 0.98 and < 1.02 prior the step 2
5001 * normalization, and throw eslFAIL if not.
5002 *
5003 * Note: A failure of this test does not necessarily mean a
5004 * bug in the code, because this check is known to fail for
5005 * some cases with parsetrees that contain inserts of 100s of
5006 * residues from the same IL or IR state (that utilize 100s
5007 * of IL->IL or IR->IR self transitions). These cases were
5008 * looked at in detail to determine if they were due to a bug
5009 * in the DP code. This was logged in
5010 * ~nawrockie/notebook/8_1016_inf-1rc3_bug_alignment/00LOG.
5011 * The conclusion was that the failure of the posterior check
5012 * is due completely to lack of precision in the float scores
5013 * (not just in the logsum look-up table but also with using
5014 * real log() and exp() calls). If this function returns an
5015 * error, please check to see if the parsetree has a large
5016 * insertion in it, if so you can expect probabilities up to
5017 * 1.03 due solely to this precision issue. See the notebook
5018 * 00LOG for more, included a check I performed to change the
5019 * relevant IL->IL transition probability by very small
5020 * values (~0.0001) and you can observe the posteriors change
5021 * dramatically which demonstrates that precision of floats
5022 * is the culprit. (EPN, Sun Oct 26 14:54:31 2008
5023 * (originally added to cm_Posterior() function 'Purpose'
5024 * function which no longer exists, having been replaced by
5025 * this function.)
5026 *
5027 *
5028 * Args: cm - the model
5029 * errbuf - for error messages
5030 * L - length of the sequence
5031 * size_limit - max number of Mb for DP matrix, if matrix is bigger return eslERANGE
5032 * post - pre-filled posterior cube
5033 * emit_mx - pre-allocated emit matrix, grown and filled-in here
5034 * do_check - if TRUE, return eslEFAIL if summed prob of any residue
5035 * (before normalization) is < 0.98 or > 1.02.
5036 *
5037 * Returns: <eslOK> on success.
5038 * Throws: <eslERANGE> if required DP matrix size exceeds <size_limit>
5039 * <eslFAIL> if (do_check) and any residue check fails
5040 * <eslEMEM> if we run out of memory.
5041 * If !eslOK the l_pp and r_pp values are invalid.
5042 */
5043 int
5044 cm_EmitterPosterior(CM_t *cm, char *errbuf, int L, float size_limit, CM_MX *post, CM_EMIT_MX *emit_mx, int do_check)
5045 {
5046 int status;
5047 int v, j, d; /* state, position, subseq length */
5048 int i; /* sequence position */
5049 int sd; /* StateDelta(v) */
5050
5051 /* grow the emit matrices based on the current sequence */
5052 if((status = cm_emit_mx_GrowTo(cm, emit_mx, errbuf, L, size_limit)) != eslOK) return status;
5053
5054 /* initialize all cells of the emit matrices to IMPOSSIBLE */
5055 esl_vec_FSet(emit_mx->l_pp_mem, emit_mx->l_ncells_valid, IMPOSSIBLE);
5056 esl_vec_FSet(emit_mx->r_pp_mem, emit_mx->r_ncells_valid, IMPOSSIBLE);
5057
5058 /* Step 1. Fill l_pp[v][i] and r_pp[v][i] with the posterior
5059 * probability that state v emitted residue i either
5060 * leftwise (l_pp) or rightwise (r_pp).
5061 */
5062 for(v = 0; v < cm->M; v++) {
5063 sd = StateDelta(cm->sttype[v]);
5064 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
5065 for(j = 1; j <= L; j++) {
5066 i = j-sd+1;
5067 for(d = sd; d <= j; d++, i--) {
5068 emit_mx->l_pp[v][i] = FLogsum(emit_mx->l_pp[v][i], post->dp[v][j][d]);
5069 }
5070 }
5071 }
5072 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
5073 for(j = 1; j <= L; j++) {
5074 sd = StateDelta(cm->sttype[v]);
5075 for(d = sd; d <= j; d++) {
5076 emit_mx->r_pp[v][j] = FLogsum(emit_mx->r_pp[v][j], post->dp[v][j][d]);
5077 }
5078 }
5079 }
5080 }
5081 /* factor in contribution of local ends, the EL state may have emitted this residue. */
5082 if (cm->flags & CMH_LOCAL_END) {
5083 for (j = 1; j <= L; j++) {
5084 i = j;
5085 for (d = 1; d <= j; d++, i--) { /* note: d >= 1, b/c EL emits 1 residue */
5086 emit_mx->l_pp[cm->M][i] = FLogsum(emit_mx->l_pp[cm->M][i], post->dp[cm->M][j][d]);
5087 }
5088 }
5089 }
5090
5091 #if eslDEBUGLEVEL >= 3
5092 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
5093 /* FILE *fp1; fp1 = fopen("tmp.std_unnorm_emitmx", "w"); cm_emit_mx_Dump(fp1, cm, emit_mx); fclose(fp1); */
5094 #endif
5095
5096 /* Step 2. Normalize l_pp and r_pp so that probability that
5097 * each residue was emitted by any state is exactly
5098 * 1.0.
5099 */
5100 esl_vec_FSet(emit_mx->sum, (L+1), IMPOSSIBLE);
5101 for(v = 0; v <= cm->M; v++) {
5102 if(emit_mx->l_pp[v] != NULL) {
5103 for(i = 1; i <= L; i++) {
5104 emit_mx->sum[i] = FLogsum(emit_mx->sum[i], emit_mx->l_pp[v][i]);
5105 }
5106 }
5107 if(emit_mx->r_pp[v] != NULL) {
5108 for(j = 1; j <= L; j++) {
5109 emit_mx->sum[j] = FLogsum(emit_mx->sum[j], emit_mx->r_pp[v][j]);
5110 }
5111 }
5112 }
5113 /* perform the check, if nec */
5114 if(do_check) {
5115 for(i = 1; i <= L; i++) {
5116 if((sreEXP2(emit_mx->sum[i]) < 0.98) || (sreEXP2(emit_mx->sum[i]) > 1.02)) {
5117 ESL_FAIL(eslFAIL, errbuf, "residue %d has summed prob of %5.4f (2^%5.4f).\nMay not be a DP coding bug, see 'Note:' on precision in cm_EmitterPosterior().\n", i, (sreEXP2(emit_mx->sum[i])), emit_mx->sum[i]);
5118 }
5119 printf("i: %d | total: %10.4f\n", i, (sreEXP2(emit_mx->sum[i])));
5120 }
5121 ESL_DPRINTF1(("#DEBUG: cm_EmitterPosterior() check passed, all residues have summed probability of emission of between 0.98 and 1.02.\n"));
5122 }
5123
5124 /* normalize, using the sum vector */
5125 for(v = 0; v <= cm->M; v++) {
5126 if(emit_mx->l_pp[v] != NULL) {
5127 for(i = 1; i <= L; i++) {
5128 emit_mx->l_pp[v][i] -= emit_mx->sum[i];
5129 }
5130 }
5131 if(emit_mx->r_pp[v] != NULL) {
5132 for(j = 1; j <= L; j++) {
5133 emit_mx->r_pp[v][j] -= emit_mx->sum[j];
5134 }
5135 }
5136 }
5137
5138 /* Step 3. Combine l_pp values for MATP_MP (v) and MATP_ML (y=v+1)
5139 * states in the same node so they give the value defined
5140 * above (i.e. l_pp[v] == l_pp[y] = the PP that either v or
5141 * y emitted residue i) instead of l_pp[v] = PP that v
5142 * emitted i, and l_pp[y] = PP that y emitted i. And
5143 * combine r_pp values for MATP_MP (v) and MATP_MR (y=v+2)
5144 * states in an analogous way.
5145 */
5146 for(v = 0; v <= cm->M; v++) {
5147 if(cm->sttype[v] == MP_st) {
5148 for(i = 1; i <= L; i++) {
5149 emit_mx->l_pp[v][i] = FLogsum(emit_mx->l_pp[v][i], emit_mx->l_pp[v+1][i]);
5150 emit_mx->l_pp[v+1][i] = emit_mx->l_pp[v][i];
5151 }
5152 for(j = 1; j <= L; j++) {
5153 emit_mx->r_pp[v][j] = FLogsum(emit_mx->r_pp[v][j], emit_mx->r_pp[v+2][j]);
5154 emit_mx->r_pp[v+2][j] = emit_mx->r_pp[v][j];
5155 }
5156 }
5157 }
5158
5159 #if eslDEBUGLEVEL >= 3
5160 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
5161 /* FILE *fp2; fp2 = fopen("tmp.std_emitmx", "w"); cm_emit_mx_Dump(fp2, cm, emit_mx); fclose(fp2); */
5162 #endif
5163
5164 return eslOK;
5165 }
5166
5167
5168 /* Function: cm_EmitterPosteriorHB()
5169 * Date: EPN, Thu Oct 6 06:59:53 2011
5170 *
5171 * Purpose: Same as cm_EmitterPosterior() except HMM banded matrices
5172 * are used. The main difference is that we have to be careful
5173 * to stay within the bands because matrix cells outside
5174 * the bands do not exist (are not allocated). This requires
5175 * keeping careful track of our offsets between the sequence
5176 * position index and the corresponding indices in the matrix.
5177 *
5178 * Args: cm - the model
5179 * errbuf - for error messages
5180 * L - length of the sequence
5181 * size_limit - max number of Mb for DP matrix, if matrix is bigger return eslERANGE
5182 * post - pre-filled posterior cube
5183 * emit_mx - pre-allocated emit matrix, grown and filled-in here
5184 * do_check - if TRUE, return eslEFAIL if summed prob of any residue
5185 * (before normalization) is < 0.98 or > 1.02.
5186 *
5187 * Returns: <eslOK> on success.
5188 * Throws: <eslERANGE> if required DP matrix size exceeds <size_limit>
5189 * <eslFAIL> if (do_check) and any residue check fails
5190 * <eslEMEM> if we run out of memory.
5191 * If !eslOK the l_pp and r_pp values are invalid.
5192 */
5193 int
5194 cm_EmitterPosteriorHB(CM_t *cm, char *errbuf, int L, float size_limit, CM_HB_MX *post, CM_HB_EMIT_MX *emit_mx, int do_check)
5195 {
5196 int status;
5197 int v, j, d; /* state, position, subseq length */
5198 int i; /* sequence position */
5199 int ip_v; /* offset i in banded matrix */
5200 int ip_v2; /* another offset i in banded matrix */
5201 int jp_v; /* offset j in banded matrix */
5202 int jp_v2; /* another offset j in banded matrix */
5203 int dp_v; /* offset d in banded matrix */
5204 int in, ix; /* temp min/max i */
5205 int jn, jx; /* temp min/max j */
5206
5207 /* ptrs to band info, for convenience */
5208 int *imin = cm->cp9b->imin;
5209 int *imax = cm->cp9b->imax;
5210 int *jmin = cm->cp9b->jmin;
5211 int *jmax = cm->cp9b->jmax;
5212 int **hdmin = cm->cp9b->hdmin;
5213 int **hdmax = cm->cp9b->hdmax;
5214
5215 /* grow the emit matrices based on the current sequence */
5216 if((status = cm_hb_emit_mx_GrowTo(cm, emit_mx, errbuf, cm->cp9b, L, size_limit)) != eslOK) return status;
5217
5218 /* initialize all cells of the emit matrices to IMPOSSIBLE */
5219 esl_vec_FSet(emit_mx->l_pp_mem, emit_mx->l_ncells_valid, IMPOSSIBLE);
5220 esl_vec_FSet(emit_mx->r_pp_mem, emit_mx->r_ncells_valid, IMPOSSIBLE);
5221
5222 /* Step 1. Fill l_pp[v][i] and r_pp[v][i] with the posterior
5223 * probability that state v emitted residue i either
5224 * leftwise (l_pp) or rightwise (r_pp).
5225 */
5226 for(v = 0; v < cm->M; v++) {
5227 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
5228 for(j = jmin[v]; j <= jmax[v]; j++) {
5229 jp_v = j - jmin[v];
5230 for(d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
5231 dp_v = d-hdmin[v][jp_v];
5232 i = j-d+1;
5233 assert(i >= imin[v] && i <= imax[v]);
5234 ip_v = i - imin[v];
5235 emit_mx->l_pp[v][ip_v] = FLogsum(emit_mx->l_pp[v][ip_v], post->dp[v][jp_v][dp_v]);
5236 }
5237 }
5238 }
5239 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
5240 for(j = jmin[v]; j <= jmax[v]; j++) {
5241 jp_v = j - jmin[v];
5242 for(d = hdmin[v][jp_v]; d <= hdmax[v][jp_v]; d++) {
5243 dp_v = d-hdmin[v][jp_v];
5244 emit_mx->r_pp[v][jp_v] = FLogsum(emit_mx->r_pp[v][jp_v], post->dp[v][jp_v][dp_v]);
5245 }
5246 }
5247 }
5248 }
5249 /* factor in contribution of local ends, the EL state may have emitted this residue.
5250 * Note, the M deck is non-banded
5251 */
5252 if (cm->flags & CMH_LOCAL_END) {
5253 for (j = 1; j <= L; j++) {
5254 i = j;
5255 for (d = 1; d <= j; d++, i--) { /* note: d >= 1, b/c EL emits 1 residue */
5256 emit_mx->l_pp[cm->M][i] = FLogsum(emit_mx->l_pp[cm->M][i], post->dp[cm->M][j][d]);
5257 }
5258 }
5259 }
5260
5261 #if eslDEBUGLEVEL >= 3
5262 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
5263 /* FILE *fp1; fp1 = fopen("tmp.std_unnorm_hbemitmx", "w"); cm_hb_emit_mx_Dump(fp1, cm, emit_mx); fclose(fp1); */
5264 #endif
5265
5266 /* Step 2. Normalize l_pp and r_pp so that probability that
5267 * each residue was emitted by any state is exactly
5268 * 1.0.
5269 */
5270 esl_vec_FSet(emit_mx->sum, (L+1), IMPOSSIBLE);
5271 for(v = 0; v < cm->M; v++) { /* we'll handle EL special */
5272 if(emit_mx->l_pp[v] != NULL) {
5273 for(i = imin[v]; i <= imax[v]; i++) {
5274 ip_v = i - imin[v];
5275 emit_mx->sum[i] = FLogsum(emit_mx->sum[i], emit_mx->l_pp[v][ip_v]);
5276 }
5277 }
5278 if(emit_mx->r_pp[v] != NULL) {
5279 for(j = jmin[v]; j <= jmax[v]; j++) {
5280 jp_v = j - jmin[v];
5281 emit_mx->sum[j] = FLogsum(emit_mx->sum[j], emit_mx->r_pp[v][jp_v]);
5282 }
5283 }
5284 }
5285 /* Handle EL deck, remember it is non-banded */
5286 if(emit_mx->l_pp[cm->M] != NULL) {
5287 for(i = 1; i <= L; i++) {
5288 emit_mx->sum[i] = FLogsum(emit_mx->sum[i], emit_mx->l_pp[v][i]);
5289 }
5290 }
5291
5292 /* perform the check, if nec */
5293 if(do_check) {
5294 for(i = 1; i <= L; i++) {
5295 if((sreEXP2(emit_mx->sum[i]) < 0.98) || (sreEXP2(emit_mx->sum[i]) > 1.02)) {
5296 ESL_FAIL(eslFAIL, errbuf, "residue %d has summed prob of %5.4f (2^%5.4f).\nMay not be a DP coding bug, see 'Note:' on precision in cm_EmitterPosterior().\n", i, (sreEXP2(emit_mx->sum[i])), emit_mx->sum[i]);
5297 }
5298 printf("HB i: %d | total: %10.4f\n", i, (sreEXP2(emit_mx->sum[i])));
5299 }
5300 ESL_DPRINTF1(("#DEBUG: cm_EmitterPosteriorHB() check passed, all residues have summed probability of emission of between 0.98 and 1.02.\n"));
5301 }
5302
5303 /* normalize, using the sum vector */
5304 for(v = 0; v < cm->M; v++) {
5305 if(emit_mx->l_pp[v] != NULL) {
5306 for(i = imin[v]; i <= imax[v]; i++) {
5307 ip_v = i - imin[v];
5308 emit_mx->l_pp[v][ip_v] -= emit_mx->sum[i];
5309 }
5310 }
5311 if(emit_mx->r_pp[v] != NULL) {
5312 for(j = jmin[v]; j <= jmax[v]; j++) {
5313 jp_v = j - jmin[v];
5314 emit_mx->r_pp[v][jp_v] -= emit_mx->sum[j];
5315 }
5316 }
5317 }
5318 /* Handle EL deck, remember it is non-banded */
5319 if(emit_mx->l_pp[cm->M] != NULL) {
5320 for(i = 1; i <= L; i++) {
5321 emit_mx->l_pp[cm->M][i] -= emit_mx->sum[i];
5322 }
5323 }
5324
5325 /* Step 3. Combine l_pp values for MATP_MP (v) and MATP_ML (y=v+1)
5326 * states in the same node so they give the value defined
5327 * above (i.e. l_pp[v] == l_pp[y] = the PP that either v or
5328 * y emitted residue i) instead of l_pp[v] = PP that v
5329 * emitted i, and l_pp[y] = PP that y emitted i. And
5330 * combine r_pp values for MATP_MP (v) and MATP_MR (y=v+2)
5331 * states in an analogous way.
5332 */
5333 for(v = 0; v <= cm->M; v++) {
5334 if(cm->sttype[v] == MP_st) {
5335 /* we only change l_pp[v][i] and l_pp[v+1][i] if i is within both
5336 * state v and v+1's i band.
5337 */
5338 if(imax[v] >= 1 && imax[v+1] >= 1) {
5339 in = ESL_MAX(imin[v], imin[v+1]);
5340 ix = ESL_MIN(imax[v], imax[v+1]);
5341 for(i = in; i <= ix; i++) {
5342 ip_v = i - imin[v];
5343 ip_v2 = i - imin[v+1];
5344 emit_mx->l_pp[v][ip_v] = FLogsum(emit_mx->l_pp[v][ip_v], emit_mx->l_pp[v+1][ip_v2]);
5345 emit_mx->l_pp[v+1][ip_v2] = emit_mx->l_pp[v][ip_v];
5346 }
5347 }
5348 /* we only change r_pp[v][j] and r_pp[v+2][j] if j is within both
5349 * state v and v+2's j band.
5350 */
5351 if(jmax[v] >= 1 && jmax[v+2] >= 1) {
5352 jn = ESL_MAX(jmin[v], jmin[v+2]);
5353 jx = ESL_MIN(jmax[v], jmax[v+2]);
5354 for(j = jn; j <= jx; j++) {
5355 jp_v = j - jmin[v];
5356 jp_v2 = j - jmin[v+2];
5357 emit_mx->r_pp[v][jp_v] = FLogsum(emit_mx->r_pp[v][jp_v], emit_mx->r_pp[v+2][jp_v2]);
5358 emit_mx->r_pp[v+2][jp_v2] = emit_mx->r_pp[v][jp_v];
5359 }
5360 }
5361 }
5362 }
5363
5364 #if eslDEBUGLEVEL >= 3
5365 /* Uncomment to dump matrix to file. This could be very large, so be careful. */
5366 /* FILE *fp2; fp2 = fopen("tmp.std_hbemitmx", "w"); cm_hb_emit_mx_Dump(fp2, cm, emit_mx); fclose(fp2); */
5367 #endif
5368
5369 return eslOK;
5370 }
5371
5372 /* Function: cm_PostCode()
5373 * Date: EPN 05.25.06 based on SRE's Postcode()
5374 * from HMMER's postprob.c
5375 *
5376 * Purpose: Given a parse tree and a filled emit matrix calculate two
5377 * strings that represents the confidence values on each
5378 * aligned residue in the sequence.
5379 *
5380 * The emit_mx values are:
5381 * l_pp[v][i]: log of the posterior probability that state v emitted
5382 * residue i leftwise either at (if a match state) or
5383 * *after* (if an insert state) the left consensus
5384 * position modeled by state v's node.
5385 *
5386 * r_pp[v][i]: log of the posterior probability that state v emitted
5387 * residue i rightwise either at (if a match state) or
5388 * *before* (if an insert state) the right consensus
5389 * position modeled by state v's node.
5390 *
5391 * l_pp[v] is NULL for states that do not emit leftwise (B,S,D,E,IR,MR)
5392 * r_pp[v] is NULL for states that do not emit rightwise (B,S,D,E,IL,ML)
5393 *
5394 * The PP string is 0..L-1 (L = len of target seq),
5395 * so its in the coordinate system of the sequence string;
5396 * off by one from dsq.
5397 *
5398 * Values are 0,1,2,3,4,5,6,7,8,9,*:
5399 * '0' = [0.00-0.05)
5400 * '1' = [0.05-0.15)
5401 * '2' = [0.15-0.25)
5402 * '3' = [0.25-0.35)
5403 * '4' = [0.35-0.45)
5404 * '5' = [0.45-0.55)
5405 * '6' = [0.55-0.65)
5406 * '7' = [0.65-0.75)
5407 * '8' = [0.75-0.85)
5408 * '9' = [0.85-0.95)
5409 * '*' = [0.95-1.00)
5410 *
5411 * cm_PostCodeHB() is nearly the same function with the
5412 * difference that HMM bands were used for the alignment,
5413 * so we have to deal with offset issues.
5414 *
5415 * Renamed from CMPostCode() [EPN, Wed Sep 14 06:20:35 2011].
5416 *
5417 * Args: cm - the model
5418 * errbuf - char buffer for reporting errors
5419 * dsq - the digitized sequence [1..L]
5420 * L - length of the dsq to align
5421 * emit_mx - the pre-filled emit matrix, must be non-NULL if do_optacc
5422 * tr - the parstree with the emissions we're setting PPs for
5423 * ret_ppstr - RETURN: a string of the PP code values (0..L-1)
5424 * ret_avgp - RETURN: the average PP of all aligned residues
5425 *
5426 * Returns: <eslOK> on success.
5427 * Throws: <eslEINVAL> if a posterior probability is > 1.01 or less than -0.01.
5428 */
5429 char
5430 Fscore2postcode(float sc)
5431 {
5432 float p = FScore2Prob(sc, 1.);
5433 return (p + 0.05 >= 1.0) ? '*' : (char) ((p + 0.05) * 10.0) + '0';
5434 }
5435
5436 /* Function: FScore2Prob()
5437 *
5438 * Purpose: Convert a float log_2 odds score back to a probability;
5439 * needs the null model probability, if any, to do the conversion.
5440 */
5441 float
5442 FScore2Prob(float sc, float null)
5443 {
5444 /*printf("in FScore2Prob: %10.2f sreEXP2: %10.2f\n", sc, (sreEXP2(sc)));*/
5445 if (!(NOT_IMPOSSIBLE(sc))) return 0.;
5446 else return (null * sreEXP2(sc));
5447 }
5448
5449 int
5450 cm_PostCode(CM_t *cm, char *errbuf, int L, CM_EMIT_MX *emit_mx, Parsetree_t *tr, char **ret_ppstr, float *ret_avgp)
5451 {
5452 int status;
5453 int x, v, i, j, r; /* counters */
5454 char *ppstr; /* the PP string, created here */
5455 float p; /* a probability */
5456 float sum_logp; /* log of summed probability of all residues emitted thus far */
5457
5458 ESL_ALLOC(ppstr, (L+1) * sizeof(char));
5459 sum_logp = IMPOSSIBLE;
5460
5461 /* go through each node of the parsetree and determine post code for emissions */
5462 for (x = 0; x < tr->n; x++)
5463 {
5464 v = tr->state[x];
5465 i = tr->emitl[x];
5466 j = tr->emitr[x];
5467
5468 /* Only P, L, R, and EL states have emissions. */
5469 if(cm->sttype[v] == EL_st) { /* EL state, we have to handle this guy special */
5470 for(r = i; r <= j; r++) { /* we have to annotate from residues i..j */
5471 ppstr[r-1] = Fscore2postcode(emit_mx->l_pp[v][r]);
5472 sum_logp = FLogsum(sum_logp, emit_mx->l_pp[v][r]);
5473 /* make sure we've got a valid probability */
5474 p = FScore2Prob(emit_mx->l_pp[v][r], 1.);
5475 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for EL state v: %d residue r: %d > 1.00 (%.2f)", v, r, p);
5476 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for EL state v: %d residue r: %d < 0.00 (%.2f)", v, r, p);
5477 }
5478 }
5479 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
5480 ppstr[i-1] = Fscore2postcode(emit_mx->l_pp[v][i]);
5481 sum_logp = FLogsum(sum_logp, emit_mx->l_pp[v][i]);
5482 /* make sure we've got a valid probability */
5483 p = FScore2Prob(emit_mx->l_pp[v][i], 1.);
5484 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for left state v: %d residue i: %d > 1.00 (%.2f)", v, i, p);
5485 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for left state v: %d residue i: %d < 0.00 (%.2f)", v, i, p);
5486 }
5487 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
5488 ppstr[j-1] = Fscore2postcode(emit_mx->r_pp[v][j]);
5489 sum_logp = FLogsum(sum_logp, emit_mx->r_pp[v][j]);
5490 /* make sure we've got a valid probability */
5491 p = FScore2Prob(emit_mx->r_pp[v][j], 1.);
5492 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for right state v: %d residue i: %d > 1.00 (%.2f)", v, j, p);
5493 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for right state v: %d residue i: %d < 0.00 (%.2f)", v, j, p);
5494 }
5495 }
5496 ppstr[L] = '\0';
5497
5498 if(ret_ppstr != NULL) *ret_ppstr = ppstr; else free(ppstr);
5499 if(ret_avgp != NULL) *ret_avgp = sreEXP2(sum_logp) / (float) L;
5500 return eslOK;
5501
5502 ERROR:
5503 ESL_FAIL(eslEMEM, errbuf, "cm_Postcode(): Memory allocation error.");
5504 return status; /* never reached */
5505 }
5506
5507
5508 int
5509 cm_PostCodeHB(CM_t *cm, char *errbuf, int L, CM_HB_EMIT_MX *emit_mx, Parsetree_t *tr, char **ret_ppstr, float *ret_avgp)
5510 {
5511 int status;
5512 int x, v, i, j, r; /* counters */
5513 char *ppstr; /* the PP string, created here */
5514 float p; /* a probability */
5515 float sum_logp; /* log of summed probability of all residues emitted thus far */
5516
5517 /* variables used for HMM bands */
5518 int ip_v, jp_v; /* i, j offset within bands */
5519 /* ptrs to cp9b info, for convenience */
5520 CP9Bands_t *cp9b = cm->cp9b;
5521 int *imin = cp9b->imin;
5522 int *imax = cp9b->imax;
5523 int *jmin = cp9b->jmin;
5524 int *jmax = cp9b->jmax;
5525
5526 ESL_ALLOC(ppstr, (L+1) * sizeof(char));
5527 sum_logp = IMPOSSIBLE;
5528
5529 /* go through each node of the parsetree and determine post code for emissions */
5530 for (x = 0; x < tr->n; x++)
5531 {
5532 v = tr->state[x];
5533 i = tr->emitl[x];
5534 j = tr->emitr[x];
5535
5536 /* Only P, L, R, and EL states have emissions. */
5537 if(cm->sttype[v] == EL_st) { /* EL state, we have to handle this guy special */
5538 for(r = i; r <= j; r++) { /* we have to annotate from residues i..j */
5539 /* remember the EL deck is non-banded */
5540 ppstr[r-1] = Fscore2postcode(emit_mx->l_pp[v][r]);
5541 sum_logp = FLogsum(sum_logp, emit_mx->l_pp[v][r]);
5542 /* make sure we've got a valid probability */
5543 p = FScore2Prob(emit_mx->l_pp[v][r], 1.);
5544 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for EL state v: %d residue r: %d > 1.00 (%.2f)", v, r, p);
5545 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for EL state v: %d residue r: %d < 0.00 (%.2f)", v, r, p);
5546 }
5547 }
5548 if(cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
5549 ip_v = i - imin[v];
5550 assert(i >= imin[v] && i <= imax[v]);
5551 ESL_DASSERT1((i >= imin[v] && i <= imax[v]));
5552 ppstr[i-1] = Fscore2postcode(emit_mx->l_pp[v][ip_v]);
5553 sum_logp = FLogsum(sum_logp, emit_mx->l_pp[v][ip_v]);
5554 /* make sure we've got a valid probability */
5555 p = FScore2Prob(emit_mx->l_pp[v][ip_v], 1.);
5556 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for left state v: %d residue i: %d > 1.00 (%.2f)", v, i, p);
5557 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for left state v: %d residue i: %d < 0.00 (%.2f)", v, i, p);
5558 }
5559 if(cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
5560 jp_v = j - jmin[v];
5561 assert(j >= jmin[v] && j <= jmax[v]);
5562 ESL_DASSERT1((j >= jmin[v] && j <= jmax[v]));
5563 ppstr[j-1] = Fscore2postcode(emit_mx->r_pp[v][jp_v]);
5564 sum_logp = FLogsum(sum_logp, emit_mx->r_pp[v][jp_v]);
5565 /* make sure we've got a valid probability */
5566 p = FScore2Prob(emit_mx->r_pp[v][jp_v], 1.);
5567 if(p > 1.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for right state v: %d residue i: %d > 1.00 (%.2f)", v, j, p);
5568 if(p < -0.01) ESL_FAIL(eslEINVAL, errbuf, "cm_PostCode(): probability for right state v: %d residue i: %d < 0.00 (%.2f)", v, j, p);
5569 }
5570 }
5571 ppstr[L] = '\0';
5572
5573 if(ret_ppstr != NULL) *ret_ppstr = ppstr; else free(ppstr);
5574 if(ret_avgp != NULL) *ret_avgp = sreEXP2(sum_logp) / (float) L;
5575 ESL_DPRINTF1(("#DEBUG: cm_PostcodeHB(): average pp %.4f\n", sreEXP2(sum_logp) / (float) L));
5576 /*printf("cm_PostcodeHB(): average pp %.4f\n", sreEXP2(sum_logp) / (float) L);*/
5577
5578 return eslOK;
5579
5580 ERROR:
5581 ESL_FAIL(eslEMEM, errbuf, "cm_PostcodeHB(): Memory allocation error.");
5582 return status; /* never reached */
5583 }
5584
5585 /* Function: cm_InitializeOptAccShadowDZero()
5586 * Date: EPN, Fri Nov 11 13:09:14 2011
5587 *
5588 * Purpose: Initialize a optimal accuracy shadow (traceback) matrix
5589 * for d == 0, based on transition scores. Optimal accuracy
5590 * traceback matrices are special when d==0 because only
5591 * emissions contribute to score so the value when d==0 is
5592 * always IMPOSSIBLE. So d==0 cells are never modified
5593 * during the OA DP recursion.
5594 *
5595 * In this function we determine the appropriate state to
5596 * traceback to for d==0 for all states v and endpoints
5597 * j. If local ends are off, this is trivial; it is simply
5598 * the child state y for which StateDelta(y) == 0 (there is
5599 * always exactly 1 such child state for each v). If any
5600 * such state is entered for d == 0 in the optimally
5601 * accurate parsetree, the parse will continue along
5602 * delete->delete transitions (all with d==0) until an E_st
5603 * (or E_st's if we go through a B_st) is reached.
5604 *
5605 * If local ends are on, it is more complex because we
5606 * could do a local end instead of a string of deletes until
5607 * an end is reached. We determine the score of the
5608 * transitions from the current state v through y to the
5609 * nearest E_st(s) and if it is less than the score for
5610 * entering a EL state we set the shadow matrix to y, else
5611 * we set it to USED_EL.
5612 *
5613 * In some cases, we initialize to USED_EL for states v for
5614 * which ELs are illegal (not a MATP_MP, MATL_ML, MATR_MR,
5615 * BEGL_S or BEGR_nd). This means that the eventual optimal
5616 * accuracy parsetree may contain an illegal EL, but I think
5617 * this is unavoidable.
5618 *
5619 * Upon entrance, yshadow should be initialized to USED_EL
5620 * for all values.
5621 *
5622 * Note that if we didn't call this function, the optimally
5623 * accurate parsetree would not be affected, nor its score.
5624 * This function is only useful because it affects the
5625 * output of the parsetree's alignment by only using a zero
5626 * length EL transitions only when it is less expensive than
5627 * a string of deletes.
5628 *
5629 * If called by a truncated optimal accuracy function
5630 * (cm_TrOptAccAlign()), yshadow is really a <Jyshadow>
5631 * matrix from a CM_TR_SHADOW_MX object. Otherwise it is a
5632 * <yshadow> matrix from a CM_SHADOW_MX object.
5633 *
5634 * Args: cm - the model, used only for its alphabet and null model
5635 * errbuf - for reporting errors
5636 * yshadow - the shadow matrix to updated, only values for which
5637 * d==0 will be modified.
5638 * L - length of the sequence we're aligning
5639 *
5640 *
5641 * Returns: eslOK on success
5642 *
5643 * Throws: eslEMEM on memory error.
5644 */
5645 int
5646 cm_InitializeOptAccShadowDZero(CM_t *cm, char *errbuf, char ***yshadow, int L)
5647 {
5648 int status;
5649 float *esc; /* [0..v..M-1] summed transition score for getting from v to nearest E_st(s)
5650 * through only delete states */
5651 float endsc; /* score for transitioning to an EL state */
5652 int have_el; /* are local ends on? */
5653 int v; /* state counter */
5654 int j; /* sequence position */
5655 int y, z; /* BEGL_S and BEGR_S states */
5656 int sd; /* StateDelta(v) */
5657 int yoffset; /* child state index */
5658
5659 have_el = (cm->flags & CMH_LOCAL_END) ? TRUE : FALSE;
5660 if(have_el) {
5661 ESL_ALLOC(esc, sizeof(float) * cm->M);
5662 esl_vec_FSet(esc, cm->M, 0.);
5663 /* determine score for transitioning to an EL (same for all legal states) */
5664 v = 0; while(! NOT_IMPOSSIBLE(cm->endsc[v])) v++;
5665 endsc = cm->endsc[v];
5666 /*printf("endsc: %.4f end %.4f\n", endsc, cm->end[v]);*/
5667 }
5668 else {
5669 esc = NULL;
5670 endsc = IMPOSSIBLE;
5671 }
5672
5673 for(v = cm->M-1; v >= 0; v--) {
5674 sd = StateDelta(cm->sttype[v]);
5675 if(cm->sttype[v] == E_st) {
5676 if(esc != NULL) esc[v] = 0.;
5677 }
5678 else if(cm->sttype[v] == B_st) {
5679 if(esc != NULL) {
5680 y = cm->cfirst[v]; /* left subtree */
5681 z = cm->cnum[v]; /* right subtree */
5682 esc[v] = esc[y] + esc[z];
5683 }
5684 }
5685 else {
5686 /* determine the one and only child state y for which StateDelta(y) == 0 */
5687 y = cm->cfirst[v];
5688 while(StateDelta(cm->sttype[y]) != 0) y++;
5689 yoffset = y-cm->cfirst[v];
5690 assert(cm->ndidx[v] == (cm->ndidx[y]-1));
5691 if(esc != NULL) {
5692 esc[v] = esc[y] + cm->tsc[v][yoffset];
5693 if(endsc > esc[v]) yoffset = USED_EL;
5694 /* else yoffset is not changed */
5695
5696 /*printf("EL: %10.4f d->d->e %10.4f ", endsc, esc[v]);
5697 if(yoffset != USED_EL) printf(" path for v: %4d %4s %2s is through deletes!\n", v, Nodetype(cm->ndtype[cm->ndidx[v]]), Statetype(cm->sttype[v]));
5698 else printf("\n");
5699 */
5700 }
5701 for(j = sd; j <= L; j++) yshadow[v][j][sd] = yoffset;
5702 }
5703 }
5704
5705 if(esc != NULL) free(esc);
5706 return eslOK;
5707
5708 ERROR:
5709 ESL_FAIL(eslEMEM, errbuf, "Out of memory");
5710 }
5711
5712
5713 /* Function: cm_InitializeOptAccShadowDZeroHB()
5714 * Date: EPN, Fri Nov 11 14:00:55 2011
5715 *
5716 * Purpose: Same as cm_InitializeOptAccShadowDZero() but for HMM
5717 * banded matrices, see that function for more information.
5718 *
5719 * Args: cm - the model, used only for its alphabet and null model
5720 * cp9b - CP9 Bands for current sequence
5721 * errbuf - for reporting errors
5722 * yshadow - the shadow matrix to updated, only values for which
5723 * d==0 will be modified.
5724 * L - length of the sequence we're aligning
5725 *
5726 *
5727 * Returns: eslOK on success
5728 *
5729 * Throws: eslEMEM on memory error.
5730 */
5731 int
5732 cm_InitializeOptAccShadowDZeroHB(CM_t *cm, CP9Bands_t *cp9b, char *errbuf, char ***yshadow, int L)
5733 {
5734 int status;
5735 float *esc; /* [0..v..M-1] summed transition score for getting from v to nearest E_st(s)
5736 * through only delete states */
5737 float endsc; /* score for transitioning to an EL state */
5738 int have_el; /* are local ends on? */
5739 int v; /* state counter */
5740 int j; /* sequence position */
5741 int y, z; /* BEGL_S and BEGR_S states */
5742 int sd; /* StateDelta(v) */
5743 int yoffset; /* child state index */
5744
5745 /* variables needed because we've got HMM bands */
5746 int sdr; /* StateRightDelta(v) */
5747 int jp_v; /* j offset for state v given HMM bands */
5748 int jp_y; /* j offset for state y given HMM bands */
5749 int dp_v; /* d offset for state v given HMM bands */
5750
5751 /* pointers to cp9b data for convenience */
5752 int *jmin = cp9b->jmin;
5753 int *jmax = cp9b->jmax;
5754 int **hdmin = cp9b->hdmin;
5755 int **hdmax = cp9b->hdmax;
5756
5757 have_el = (cm->flags & CMH_LOCAL_END) ? TRUE : FALSE;
5758 if(have_el) {
5759 ESL_ALLOC(esc, sizeof(float) * cm->M);
5760 esl_vec_FSet(esc, cm->M, IMPOSSIBLE);
5761 /* determine score for transitioning to an EL (same for all legal states) */
5762 v = 0; while(! NOT_IMPOSSIBLE(cm->endsc[v])) v++;
5763 endsc = cm->endsc[v];
5764 /*printf("endsc: %.4f end %.4f\n", endsc, cm->end[v]);*/
5765 }
5766 else {
5767 esc = NULL;
5768 endsc = IMPOSSIBLE;
5769 }
5770
5771 for(v = cm->M-1; v >= 0; v--) {
5772 if(cm->cp9b->Jvalid[v]) { /* only valid v values will have non-impossible esc[v] values */
5773 sd = StateDelta(cm->sttype[v]);
5774 sdr = StateRightDelta(cm->sttype[v]);
5775 if(cm->sttype[v] == E_st) {
5776 if(esc != NULL) esc[v] = 0.;
5777 }
5778 else if(cm->sttype[v] == B_st) {
5779 if(esc != NULL) {
5780 y = cm->cfirst[v]; /* left subtree */
5781 z = cm->cnum[v]; /* right subtree */
5782 esc[v] = esc[y] + esc[z];
5783 }
5784 }
5785 else {
5786 /* determine the one and only child state y for which StateDelta(y) == 0 */
5787 y = cm->cfirst[v];
5788 while(StateDelta(cm->sttype[y]) != 0) y++;
5789 yoffset = y-cm->cfirst[v];
5790 assert(cm->ndidx[v] == (cm->ndidx[y]-1));
5791 if(esc != NULL) {
5792 esc[v] = esc[y] + cm->tsc[v][yoffset];
5793 if(endsc > esc[v]) yoffset = USED_EL;
5794 /* else yoffset is not changed */
5795
5796 #if 0
5797 printf("EL: %10.4f d->d->e %10.4f ", endsc, esc[v]);
5798 if(yoffset != USED_EL) printf(" path for v %4d %4s %2s is through deletes!\n", v, Nodetype(cm->ndtype[cm->ndidx[v]]), Statetype(cm->sttype[v]));
5799 else printf("\n");
5800 #endif
5801
5802 }
5803 for(j = ESL_MAX(sd, jmin[v]); j <= jmax[v]; j++) {
5804 jp_v = j-jmin[v];
5805 if(hdmin[v][jp_v] <= hdmax[v][jp_v]) { /* at least one valid d exists for this v and j */
5806 if((j-sdr) >= jmin[y] && (j-sdr) <= jmax[y]) { /* j-sdr is valid for state y */
5807 jp_y = j - sdr - jmin[y];
5808 if(sd >= hdmin[v][jp_v] && sd <= hdmax[v][jp_v] && /* d==sd is valid for state v and end posn j */
5809 0 >= hdmin[y][jp_y] && 0 <= hdmax[y][jp_y]) { /* d==0 is valid for state y and end posn j-sdr */
5810 dp_v = sd - hdmin[v][jp_v];
5811 yshadow[v][jp_v][dp_v] = yoffset;
5812 }
5813 }
5814 }
5815 }
5816 }
5817 }
5818 }
5819
5820 if(esc != NULL) free(esc);
5821 return eslOK;
5822
5823 ERROR:
5824 ESL_FAIL(eslEMEM, errbuf, "Out of memory");
5825 }
5826
5827
5828 /*****************************************************************
5829 * Benchmark driver
5830 *****************************************************************/
5831 #ifdef IMPL_ALIGN_BENCHMARK
5832 /* Next line is not optimized (debugging on) on MacBook Pro:
5833 * gcc -o benchmark-align -std=gnu99 -g -Wall -I. -L. -I../hmmer/src -L../hmmer/src -I../easel -L../easel -DIMPL_ALIGN_BENCHMARK cm_dpalign.c -linfernal -lhmmer -leasel -lm
5834 * Next line is optimized (debugging not on) on wyvern:
5835 * gcc -o benchmark-align -std=gnu99 -O3 -fomit-frame-pointer -malign-double -fstrict-aliasing -pthread -I. -L. -I../hmmer/src -L../hmmer/src -I../easel -L../easel -DIMPL_ALIGN_BENCHMARK cm_dpalign.c -linfernal -lhmmer -leasel -lm
5836 * ./benchmark-align <cmfile>
5837 */
5838
5839 #include <esl_config.h>
5840 #include "config.h"
5841
5842 #include <stdio.h>
5843 #include <stdlib.h>
5844 #include <string.h>
5845 #include <time.h>
5846
5847 #include "easel.h"
5848 #include <esl_getopts.h>
5849 #include <esl_histogram.h>
5850 #include <esl_sqio.h>
5851 #include <esl_stats.h>
5852 #include <esl_stopwatch.h>
5853 #include <esl_vectorops.h>
5854 #include <esl_wuss.h>
5855
5856 #include "hmmer.h"
5857
5858 #include "infernal.h"
5859
5860 static ESL_OPTIONS options[] = {
5861 /* name type default env range toggles reqs incomp help docgroup*/
5862 { "-h", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
5863 { "-l", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "configure CM/HMM for local alignment", 0 },
5864 { "--cykout", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "run CYKOutside, to make sure it agrees with CYK (Inside)", 0 },
5865 { "--sums", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use posterior sums during HMM band calculation (widens bands)", 0 },
5866 { "--dlev", eslARG_INT, "0", NULL, "0<=n<=3",NULL,NULL,NULL, "set verbosity of debugging print statements to <n>", 0 },
5867 { "--hmmcheck",eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "check that HMM posteriors are correctly calc'ed", 0 },
5868 { "--cmcheck", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "check that CM posteriors are correctly calc'ed", 0 },
5869 { "--optacc", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute optimal accuracy HMM banded alignment alg", 0 },
5870 { "--tau", eslARG_REAL, "5e-6",NULL, "0<x<1",NULL, NULL, NULL, "set tail loss prob for HMM bands to <x>", 0 },
5871 { "--post", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute fast float HMM banded Inside/Outside alignment algs", 0 },
5872 { "--mxsize", eslARG_REAL, "256.0", NULL, "x>0.",NULL, NULL, NULL, "set maximum allowable DP matrix size to <x> (Mb)", 0 },
5873 { "--nonbanded",eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute non-banded alignment algorithms", 0 },
5874 { "--tr", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "dump parsetrees to stdout", 0 },
5875 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
5876 };
5877 static char usage[] = "[-options] <cmfile> <seqfile>";
5878 static char banner[] = "benchmark driver for fast HMM banded CYK alignment and scanning algorithm";
5879
5880 int
5881 main(int argc, char **argv)
5882 {
5883 int status;
5884 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 2, argc, argv, banner, usage);
5885 CM_t *cm;
5886 ESL_STOPWATCH *w = esl_stopwatch_Create();
5887 ESL_ALPHABET *abc = NULL;
5888 int i;
5889 float sc;
5890 float pp;
5891 char *cmfile = esl_opt_GetArg(go, 1);
5892 char *seqfile = esl_opt_GetArg(go, 2);
5893 CM_FILE *cmfp = NULL; /* open input CM file stream */
5894 ESL_SQFILE *sqfp = NULL; /* open sequence input file stream */
5895 ESL_SQ *sq = NULL; /* a sequence */
5896 int L; /* length of sequence */
5897 char errbuf[eslERRBUFSIZE];
5898 float size_limit = esl_opt_GetReal(go, "--mxsize");
5899 int do_check = esl_opt_GetBoolean(go, "--cmcheck");
5900 float parsetree_sc, parsetree_struct_sc;
5901 Parsetree_t *tr = NULL;
5902
5903 /* open CM file */
5904 if ((status = cm_file_Open(cmfile, NULL, FALSE, &(cmfp), errbuf)) != eslOK) cm_Fail(errbuf);
5905 if ((status = cm_file_Read(cmfp, TRUE, &abc, &cm)) != eslOK) cm_Fail(cmfp->errbuf);
5906 cm_file_Close(cmfp);
5907
5908 /* open the sequence file */
5909 status = esl_sqfile_OpenDigital(cm->abc, seqfile, eslSQFILE_UNKNOWN, NULL, &sqfp);
5910 if (status == eslENOTFOUND) esl_fatal("File %s doesn't exist or is not readable\n", seqfile);
5911 else if (status == eslEFORMAT) esl_fatal("Couldn't determine format of sequence file %s\n", seqfile);
5912 else if (status == eslEINVAL) esl_fatal("Can't autodetect stdin or .gz.");
5913 else if (status != eslOK) esl_fatal("Sequence file open failed with error %d.\n", status);
5914
5915 /* configure CM */
5916 cm->align_opts |= CM_ALIGN_HBANDED;
5917 if(esl_opt_GetBoolean(go, "--sums")) cm->align_opts |= CM_ALIGN_SUMS;
5918 if(esl_opt_GetBoolean(go, "-l")) {
5919 cm->config_opts |= CM_CONFIG_LOCAL;
5920 cm->config_opts |= CM_CONFIG_HMMLOCAL;
5921 cm->config_opts |= CM_CONFIG_HMMEL;
5922 }
5923 if(esl_opt_GetBoolean(go, "--hmmcheck")) cm->align_opts |= CM_ALIGN_CHECKFB;
5924 if(esl_opt_GetBoolean(go, "--cmcheck")) cm->align_opts |= CM_ALIGN_CHECKINOUT;
5925 cm->tau = esl_opt_GetReal(go, "--tau");
5926
5927 if((status = cm_Configure(cm, errbuf, -1)) != eslOK) cm_Fail(errbuf);
5928
5929 /* setup logsum lookups (could do this only if nec based on options, but this is safer) */
5930 init_ilogsum();
5931 FLogsumInit();
5932
5933 i = 0;
5934 sq = esl_sq_CreateDigital(cm->abc);
5935 while((status = esl_sqio_Read(sqfp, sq)) == eslOK) {
5936 i++;
5937 L = sq->n;
5938
5939 esl_stopwatch_Start(w);
5940 if((status = cp9_Seq2Bands(cm, errbuf, cm->cp9_mx, cm->cp9_bmx, cm->cp9_bmx, sq->dsq, 1, L, cm->cp9b, FALSE, PLI_PASS_STD_ANY, 0)) != eslOK) cm_Fail(errbuf);
5941 esl_stopwatch_Stop(w);
5942 printf("%4d %-30s %17s", i, "Exptl Band calc:", "");
5943 esl_stopwatch_Display(stdout, w, "CPU time: ");
5944
5945 esl_stopwatch_Start(w);
5946 if((status = cm_AlignHB(cm, errbuf, sq->dsq, L, size_limit, FALSE, FALSE, cm->hb_mx, cm->hb_shmx, NULL, NULL, NULL, NULL, &tr, &pp, &sc)) != eslOK) cm_Fail(errbuf);
5947 printf("%4d %-30s %10.4f bits ", (i), "cm_AlignHB() CYK:", sc);
5948 esl_stopwatch_Stop(w);
5949 esl_stopwatch_Display(stdout, w, " CPU time: ");
5950
5951 if(esl_opt_GetBoolean(go, "--tr")) ParsetreeDump(stdout, tr, cm, sq->dsq);
5952 ParsetreeScore(cm, NULL, NULL, tr, sq->dsq, FALSE, &parsetree_sc, &parsetree_struct_sc, NULL, NULL, NULL);
5953 FreeParsetree(tr);
5954 printf("Parsetree score : %.4f (FULL LENGTH CYK)\n", parsetree_sc);
5955
5956 if(esl_opt_GetBoolean(go, "--cykout")) {
5957 esl_stopwatch_Start(w);
5958 if((status = cm_CYKOutsideAlignHB(cm, errbuf, sq->dsq, L, size_limit, TRUE, cm->hb_omx, cm->hb_mx, &sc)) != eslOK) cm_Fail(errbuf);
5959 printf("%4d %-30s %10.4f bits ", (i), "cm_Align() CYK:", sc);
5960 esl_stopwatch_Stop(w);
5961 esl_stopwatch_Display(stdout, w, " CPU time: ");
5962 }
5963
5964 if(esl_opt_GetBoolean(go, "--nonbanded")) {
5965 esl_stopwatch_Start(w);
5966 if((status = cm_Align(cm, errbuf, sq->dsq, L, size_limit, FALSE, FALSE, cm->nb_mx, cm->nb_shmx, NULL, cm->nb_emx, NULL, NULL, &tr, &pp, &sc)) != eslOK) cm_Fail(errbuf);
5967 printf("%4d %-30s %10.4f bits ", (i), "cm_Align() CYK:", sc);
5968 esl_stopwatch_Stop(w);
5969 esl_stopwatch_Display(stdout, w, " CPU time: ");
5970
5971 if(esl_opt_GetBoolean(go, "--tr")) ParsetreeDump(stdout, tr, cm, sq->dsq);
5972 ParsetreeScore(cm, NULL, NULL, tr, sq->dsq, FALSE, &parsetree_sc, &parsetree_struct_sc, NULL, NULL, NULL);
5973 FreeParsetree(tr);
5974 printf("Parsetree score : %.4f (FULL LENGTH CYK)\n", parsetree_sc);
5975
5976 if(esl_opt_GetBoolean(go, "--cykout")) {
5977 esl_stopwatch_Start(w);
5978 if((status = cm_CYKOutsideAlign(cm, errbuf, sq->dsq, L, size_limit, TRUE, cm->nb_omx, cm->nb_mx, &sc)) != eslOK) cm_Fail(errbuf);
5979 printf("%4d %-30s %10.4f bits ", (i), "cm_Align() CYK:", sc);
5980 esl_stopwatch_Stop(w);
5981 esl_stopwatch_Display(stdout, w, " CPU time: ");
5982 }
5983 }
5984 printf("\n");
5985
5986 if(esl_opt_GetBoolean(go, "--post")) {
5987 esl_stopwatch_Start(w);
5988 /* need alpha matrix from Inside to do Outside */
5989 if((status = cm_InsideAlignHB(cm, errbuf, sq->dsq, L, size_limit, cm->hb_mx, &sc)) != eslOK) cm_Fail(errbuf);
5990 printf("%4d %-30s %10.4f bits ", (i), "cm_InsideAlignHB():", sc);
5991 esl_stopwatch_Stop(w);
5992 esl_stopwatch_Display(stdout, w, " CPU time: ");
5993
5994 esl_stopwatch_Start(w);
5995 /* need alpha matrix from Inside to do Outside */
5996 if((status = cm_OutsideAlignHB(cm, errbuf, sq->dsq, L, size_limit, do_check, cm->hb_omx, cm->hb_mx, &sc)) != eslOK) cm_Fail(errbuf);
5997 printf("%4d %-30s %10.4f bits ", (i), "cm_OutsideAlignHB():", sc);
5998 esl_stopwatch_Stop(w);
5999 esl_stopwatch_Display(stdout, w, " CPU time: ");
6000
6001 if(esl_opt_GetBoolean(go, "--nonbanded")) {
6002 esl_stopwatch_Start(w);
6003 /* need alpha matrix from Inside to do Outside */
6004 if((status = cm_InsideAlign(cm, errbuf, sq->dsq, L, size_limit, cm->nb_mx, &sc)) != eslOK) cm_Fail(errbuf);
6005 printf("%4d %-30s %10.4f bits ", (i), "cm_InsideAlign():", sc);
6006 esl_stopwatch_Stop(w);
6007 esl_stopwatch_Display(stdout, w, " CPU time: ");
6008
6009 esl_stopwatch_Start(w);
6010 /* need alpha matrix from Inside to do Outside */
6011 if((status = cm_OutsideAlign(cm, errbuf, sq->dsq, L, size_limit, do_check, cm->nb_omx, cm->nb_mx, &sc)) != eslOK) cm_Fail(errbuf);
6012 printf("%4d %-30s %10.4f bits ", (i), "cm_OutsideAlign():", sc);
6013 esl_stopwatch_Stop(w);
6014 esl_stopwatch_Display(stdout, w, " CPU time: ");
6015 }
6016 }
6017
6018 if(esl_opt_GetBoolean(go, "--optacc")) {
6019 esl_stopwatch_Start(w);
6020 if((status = cm_AlignHB(cm, errbuf, sq->dsq, L, size_limit, TRUE, FALSE, cm->hb_mx, cm->hb_shmx, cm->hb_omx, cm->hb_emx, NULL, NULL, &tr, &pp, &sc)) != eslOK) cm_Fail(errbuf);
6021 printf("%4d %-30s %10.4f avgpp ", (i), "cm_AlignHB() OA:", pp);
6022 esl_stopwatch_Stop(w);
6023 esl_stopwatch_Display(stdout, w, " CPU time: ");
6024
6025 if(esl_opt_GetBoolean(go, "--tr")) ParsetreeDump(stdout, tr, cm, sq->dsq);
6026 ParsetreeScore(cm, NULL, NULL, tr, sq->dsq, FALSE, &parsetree_sc, &parsetree_struct_sc, NULL, NULL, NULL);
6027 FreeParsetree(tr);
6028 printf("Parsetree score : %.4f (FULL LENGTH OPTACC)\n", parsetree_sc);
6029
6030 if(esl_opt_GetBoolean(go, "--nonbanded")) {
6031 esl_stopwatch_Start(w);
6032 if((status = cm_Align(cm, errbuf, sq->dsq, L, size_limit, TRUE, FALSE, cm->nb_mx, cm->nb_shmx, cm->nb_omx, cm->nb_emx, NULL, NULL, &tr, &pp, &sc)) != eslOK) cm_Fail(errbuf);
6033 printf("%4d %-30s %10.4f avgpp ", (i), "cm_Align() OA:", sc);
6034 esl_stopwatch_Stop(w);
6035 esl_stopwatch_Display(stdout, w, " CPU time: ");
6036
6037 if(esl_opt_GetBoolean(go, "--tr")) ParsetreeDump(stdout, tr, cm, sq->dsq);
6038 ParsetreeScore(cm, NULL, NULL, tr, sq->dsq, FALSE, &parsetree_sc, &parsetree_struct_sc, NULL, NULL, NULL);
6039 FreeParsetree(tr);
6040 printf("Parsetree score : %.4f (FULL LENGTH OPTACC)\n", parsetree_sc);
6041 }
6042 }
6043 printf("\n");
6044 esl_sq_Reuse(sq);
6045 }
6046 if(status != eslEOF) cm_Fail("ERROR reading sequence file, sequence number %d\n", i);
6047
6048 FreeCM(cm);
6049 esl_sq_Destroy(sq);
6050 esl_alphabet_Destroy(abc);
6051 esl_stopwatch_Destroy(w);
6052 esl_getopts_Destroy(go);
6053 esl_sqfile_Close(sqfp);
6054
6055 return 0;
6056 }
6057 #endif /*IMPL_ALIGN_BENCHMARK*/