Debian Codegraph @

src/cp9_dp.c

raw symbols SCIP
1 /* cp9_dp.c
2 *
3 * Dynamic programming functions for alignment and search
4 * with CM plan 9 HMMs.
5 *
6 * All of these functions were written between the 0.81 and
7 * 1.0 release of Infernal.
8 *
9 * EPN, Wed Sep 12 16:53:32 2007
10 */
11
12 #include <esl_config.h>
13 #include <p7_config.h>
14 #include "config.h"
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <math.h>
19
20 #include "easel.h"
21 #include "esl_sqio.h"
22 #include "esl_stack.h"
23 #include "esl_stopwatch.h"
24 #include "esl_vectorops.h"
25
26 #include "hmmer.h"
27
28 #include "infernal.h"
29
30 #define CP9TSC(s,k) (tsc[(k) * cp9O_NTRANS + (s)])
31
32 #define IAMI_M (1<<0)
33 #define IAMI_I (1<<1)
34 #define IAMI_D (1<<2)
35 #define IAMI_EL (1<<3)
36 #define nIAMI_S 4
37
38 #define IAMI_MM (1<<0)
39 #define IAMI_IM (1<<1)
40 #define IAMI_DM (1<<2)
41 #define IAMI_BM (1<<3)
42 #define IAMI_MI (1<<4)
43 #define IAMI_II (1<<5)
44 #define IAMI_DI (1<<6)
45 #define IAMI_MD (1<<7)
46 #define IAMI_ID (1<<8)
47 #define IAMI_DD (1<<9)
48 #define IAMI_ME (1<<10)
49 #define IAMI_MEL (1<<11)
50 #define nIAMI_T 12
51
52 #define TDIFF_MI_M 0
53 #define TDIFF_MI_I 1
54 #define TDIFF_MI_D 2
55 #define nTDIFF 3
56
57 /* Function: cp9_Viterbi()
58 *
59 * Purpose: Runs the Viterbi dynamic programming algorithm on an
60 * input subsequence (i0-j0).
61 * Somewhat flexible based on input options.
62 *
63 * Note: IDENTICAL to CP9Forward() below with maxes replacing
64 * sums in DP recursion, and the possibility of returning a
65 * CP9 trace if doing_align == TRUE. See CP9Forward() for more info,
66 * including more verbose 'Purpose' and description of arguments.
67 *
68 * Returns: <ret_sc>: if(!do_scan) log P(S,tr|M)/P(S,tr|R), as a bit score
69 * else max log P(S,tr|M)/P(S,tr|R), for argmax subseq S of input seq i0..j0,
70 * eslOK on success;
71 * eslEINCOMPAT on contract violation;
72 */
73 int
74 cp9_Viterbi(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int i0, int j0, int do_scan, int doing_align,
75 int be_efficient, int **ret_psc, int *ret_maxres, CP9trace_t **ret_tr, float *ret_sc)
76 {
77 int status;
78 int j; /* actual position in the subsequence */
79 int jp; /* j': relative position in the subsequence */
80 int cur, prv; /* rows in DP matrix 0 or 1 */
81 int k; /* CP9 HMM node position */
82 int L; /* j0-i0+1: subsequence length */
83 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
84 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
85 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
86 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
87 int *erow; /* end score for each position [0..1] */
88 int *scA; /* prob (seq from j0..jp | HMM) [0..jp..cp9->M] */
89 float fsc; /* float log odds score */
90 float best_sc; /* score of best hit overall */
91 float best_pos; /* residue (j) giving best_sc, where best hit ends */
92 int nrows; /* num rows for DP matrix, 2 or L+1 depending on be_efficient */
93 int c; /* counter for EL states */
94 CP9trace_t *tr; /* CP9 trace for full seq i0..j0, used if ret_tr != NULL */
95 int M; /* cp9->M, query length, number of consensus nodes of model */
96
97 /* Contract checks */
98 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Viterbi, dsq is NULL.");
99 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Viterbi, mx is NULL.\n");
100
101 best_sc = IMPOSSIBLE;
102 best_pos = -1;
103 L = j0-i0+1;
104 M = cp9->M;
105
106 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
107
108 /* Grow DP matrix if nec, to either 2 rows or L+1 rows (depending on be_efficient),
109 * stays M+1 columns */
110 if(be_efficient) nrows = 1; /* mx will be 2 rows */
111 else nrows = L; /* mx will be L+1 rows */
112 if((status = GrowCP9Matrix(mx, errbuf, nrows, M, NULL, NULL, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
113 ESL_DPRINTF1(("#DEBUG: cp9_Viterbi(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
114
115 /* scA will hold P(seq up to j | Model) in int log odds form */
116 ESL_ALLOC(scA, sizeof(int) * (j0-i0+2));
117
118 /* Initialization of the zero row. */
119 mmx[0][0] = 0; /* M_0 is state B, and everything starts in B */
120 imx[0][0] = -INFTY; /* I_0 is state N, can't get here without emitting*/
121 dmx[0][0] = -INFTY; /* D_0 doesn't exist. */
122 elmx[0][0]= -INFTY; /* can't go from B to EL state */
123 erow[0] = -INFTY;
124
125 /* Because there's a D state for every node 1..M,
126 dmx[0][k] is possible for all k 1..M */
127 int sc;
128 for (k = 1; k <= M; k++)
129 {
130 mmx[0][k] = imx[0][k] = elmx[0][k] = -INFTY; /* need seq to get here */
131 sc = ESL_MAX(mmx[0][k-1] + CP9TSC(cp9O_MD,k-1),
132 imx[0][k-1] + CP9TSC(cp9O_ID,k-1));
133 sc = ESL_MAX(sc, dmx[0][k-1] + CP9TSC(cp9O_DD,k-1));
134 dmx[0][k] = sc;
135 }
136 /* We can do a full parse through all delete states. */
137 erow[0] = dmx[0][M] + CP9TSC(cp9O_DM,M);
138 scA[0] = erow[0];
139 fsc = Scorify(scA[0]);
140 /*printf("jp: %d j: %d fsc: %f isc: %d\n", jp, j, fsc, isc[jp]);*/
141 if(fsc > best_sc) { best_sc = fsc; best_pos= i0-1; }
142 /*printf("jp: %d j: %d fsc: %f sc: %d\n", 0, i0-1, Scorify(sc[0]), sc[0]);*/
143
144 /*****************************************************************
145 * The main loop: scan the sequence from position i0 to j0.
146 *****************************************************************/
147 /* Recursion. */
148 for (j = i0; j <= j0; j++)
149 {
150 int const *isc = cp9->isc[dsq[j]];
151 int const *msc = cp9->msc[dsq[j]];
152
153 int endsc = -INFTY;
154 int el_selfsc = cp9->el_selfsc;
155 int sc;
156
157 jp = j-i0+1; /* jp is relative position in the sequence 1..L */
158 cur = (j-i0+1);
159 prv = (j-i0);
160
161 if(be_efficient) {
162 cur %= 2;
163 prv %= 2;
164 }
165
166 /* The 1 difference between a Viterbi scanner and the
167 * regular Viterbi. In non-scanner parse must begin in B at
168 * position 0 (i0-1), in scanner we can start at any position
169 * in the seq. */
170 mmx[cur][0] = (do_scan == TRUE) ? 0 : -INFTY;
171 dmx[cur][0] = -INFTY; /*D_0 is non-existent*/
172 elmx[cur][0] = -INFTY; /*no EL state for node 0 */
173
174 sc = ESL_MAX(mmx[prv][0] + CP9TSC(cp9O_MI,0),
175 imx[prv][0] + CP9TSC(cp9O_II,0));
176 sc = ESL_MAX(sc, dmx[prv][0] + CP9TSC(cp9O_DI,0));
177 imx[cur][0] = ESL_MAX(sc + isc[0], -INFTY);
178
179 for (k = 1; k <= M; k++)
180 {
181 /*match state*/
182 sc = ESL_MAX( mmx[prv][k-1] + CP9TSC(cp9O_MM,k-1),
183 imx[prv][k-1] + CP9TSC(cp9O_IM,k-1));
184 sc = ESL_MAX(sc, dmx[prv][k-1] + CP9TSC(cp9O_DM,k-1));
185 sc = ESL_MAX(sc, mmx[prv][0] + CP9TSC(cp9O_BM,k));
186 /* check possibility we came from an EL, if they're valid */
187 for(c = 0; c < cp9->el_from_ct[k]; c++) /* el_from_ct[k] is >= 0 */
188 sc = ESL_MAX(sc, elmx[prv][cp9->el_from_idx[k][c]]);
189 /* transition penalty to EL incurred when EL was entered */
190 mmx[cur][k] = ESL_MAX(sc + msc[k], -INFTY);
191
192 /* E state update */
193 endsc = ESL_MAX(endsc, mmx[cur][k] + CP9TSC(cp9O_ME,k));
194
195 /*insert state*/
196 sc = ESL_MAX( mmx[prv][k] + CP9TSC(cp9O_MI,k),
197 imx[prv][k] + CP9TSC(cp9O_II,k));
198 sc = ESL_MAX(sc, dmx[prv][k] + CP9TSC(cp9O_DI,k));
199 imx[cur][k] = ESL_MAX(sc + isc[k], -INFTY);
200
201 /*delete state*/
202 sc = ESL_MAX( mmx[cur][k-1] + CP9TSC(cp9O_MD,k-1),
203 imx[cur][k-1] + CP9TSC(cp9O_ID,k-1));
204 sc = ESL_MAX(sc, dmx[cur][k-1] + CP9TSC(cp9O_DD,k-1));
205 dmx[cur][k] = sc;
206
207 /*el state*/
208 sc = -INFTY;
209 if((cp9->flags & CPLAN9_EL) && cp9->has_el[k]) /* not all HMM nodes have an EL state (for ex:
210 HMM nodes that map to right half of a MATP_MP) */
211 {
212 sc = ESL_MAX(sc, mmx[cur][k] + CP9TSC(cp9O_MEL,k));
213 sc = ESL_MAX(sc, elmx[prv][k] + el_selfsc);
214 }
215 elmx[cur][k] = sc;
216 }
217
218 endsc = ESL_MAX(endsc, dmx[cur][M] + CP9TSC(cp9O_DM,M)); /* transition from D_M -> end */
219 endsc = ESL_MAX(endsc, imx[cur][M] + CP9TSC(cp9O_IM,M)); /* transition from I_M -> end */
220 for(c = 0; c < cp9->el_from_ct[M+1]; c++) /* el_from_ct[k] is >= 0 */
221 /* transition penalty to EL incurred when EL was entered */
222 endsc = ESL_MAX(endsc, elmx[cur][cp9->el_from_idx[M+1][c]]);
223
224 erow[cur] = endsc;
225 scA[jp] = endsc;
226 fsc = Scorify(endsc);
227
228 if(fsc > best_sc) { best_sc = fsc; best_pos= j; }
229 } /* end loop over end positions j */
230
231 if(doing_align) { /* best_sc is the alignment score */
232 best_sc = Scorify(scA[(j0-i0+1)]); /* L = j0-i0+1 */
233 best_pos = i0;
234 if(ret_tr != NULL) {
235 CP9ViterbiTrace(cp9, dsq, i0, j0, mx, &tr);
236 if(tr == NULL) ESL_FAIL(eslFAIL, errbuf, "CP9ViterbiTrace() returned NULL, problem with traceback.");
237 /* CP9PrintTrace(stdout, tr, cp9, dsq); */
238 *ret_tr = tr;
239 }
240 }
241 if(ret_sc != NULL) *ret_sc = best_sc;
242 if(ret_maxres != NULL) *ret_maxres = best_pos;
243 if(ret_psc != NULL) *ret_psc = scA;
244 else free(scA);
245 ESL_DPRINTF1(("#DEBUG: cp9_Viterbi() return score: %10.4f\n", best_sc));
246
247 return eslOK;
248
249 ERROR:
250 ESL_FAIL(eslEMEM, errbuf, "Memory allocation error.");
251 }
252
253
254 /* Function: cp9_ViterbiBackward()
255 *
256 * Purpose: Runs the Viterbi dynamic programming algorithm BACKWARDS on an
257 * input subsequence (i0-j0).
258 * Somewhat flexible based on input options.
259 *
260 * Note: IDENTICAL to CP9Backward() below with maxes replacing
261 * sums in DP recursion, and the possibility of returning a
262 * CP9 trace if doing_align == TRUE. See CP9Backward() for more info,
263 * including more verbose 'Purpose' and description of arguments.
264 *
265 * Returns: <ret_sc>: if(!do_scan) log P(S,tr|M)/P(S,tr|R), as a bit score
266 * else max log P(S,tr|M)/P(S,tr|R), for argmax subseq S of input seq i0..j0,
267 * eslOK on success;
268 * eslEINCOMPAT on contract violation;
269 */
270 int
271 cp9_ViterbiBackward(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int i0, int j0, int do_scan, int doing_align,
272 int be_efficient, int **ret_psc, int *ret_maxres, CP9trace_t **ret_tr, float *ret_sc)
273 {
274 int status;
275 int i; /* actual position in the subsequence */
276 int ip; /* i': relative position in the subsequence */
277 int cur, prv; /* rows in DP matrix 0 or 1 */
278 int k; /* CP9 HMM node position */
279 int L; /* j0-i0+1: subsequence length */
280 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
281 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
282 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
283 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
284 int *erow; /* end score for each position [0..1] */
285 int *scA; /* prob (seq from j0..jp | HMM) [0..jp..cp9->M] */
286 float fsc; /* float log odds score */
287 float best_sc; /* score of best hit overall */
288 float best_pos; /* residue (i) giving best_sc, where best hit starts */
289 int nrows; /* num rows for DP matrix, 2 or L+1 depending on be_efficient */
290 int c; /* counter for EL states */
291 int M; /* cp9->M, query length, number of consensus nodes of model */
292
293 /* Contract checks */
294 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ViterbiBackward, cp9 is NULL.\n");
295 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ViterbiBackward, dsq is NULL.");
296 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_ViterbiBackward, mx is NULL.\n");
297
298 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
299
300 best_sc = IMPOSSIBLE;
301 best_pos = -1;
302 L = j0-i0+1;
303 M = cp9->M;
304
305 /* Grow DP matrix if nec, to either 2 rows or L+1 rows (depending on be_efficient),
306 * stays M+1 columns */
307 if(be_efficient) nrows = 1; /* mx will be 2 rows */
308 else nrows = L; /* mx will be L+1 rows */
309 if((status = GrowCP9Matrix(mx, errbuf, nrows, M, NULL, NULL, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
310 ESL_DPRINTF1(("#DEBUG: cp9_ViterbiBackward(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
311
312 /* scA will hold P(seq up to j | Model) in int log odds form */
313 ESL_ALLOC(scA, sizeof(int) * (j0-i0+2));
314
315 /* Initialization of the L (i = j0, cur = (j0-i) = (j0-j0) %2 = 0) row. */
316 if(be_efficient) cur = 0;
317 else cur = j0-i0+1; /* L */
318 ip = j0-i0+1; /*L */
319 i = j0;
320
321 /*******************************************************************
322 * 0 Handle EL, looking at EL_k->E for all valid k.
323 * we're going backwards so we have to work out of order, we could get
324 * around this by storing the nodes each EL goes TO in an el_to_ct[] vec. */
325 /* init to -INFTY */
326 for (k = 1; k <= cp9->M; k++) elmx[cur][k] = -INFTY;
327 if(cp9->flags & CPLAN9_EL) {
328 for(c = 0; c < cp9->el_from_ct[cp9->M+1]; c++) /* el_from_ct[cp9->M+1] holds # ELs that can go to END */
329 elmx[cur][cp9->el_from_idx[cp9->M+1][c]] = 0.; /* EL<-E, penalty incurred when we enter EL (i.e. leave going backwards) */
330 }
331 /*******************************************************************/
332
333 /* elmx[cur][cp9->M] is either 0 (if EL_M exists (it would nec be in el_from_idx[cp9->M+1] array if it does, so
334 * it would be filled with 0 in above loop), or -INFTY if it doesn't exist. We don't add possibility of EL_M -> EL_M
335 * self loop b/c it's impossible to do that without emitting, and we've already seen our last res emitted.
336 * either way we don't have to modify it */
337
338 mmx[cur][cp9->M] = ESL_MAX(elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M),/* M_M<-EL_M<-E, with 0 self loops in EL_M */
339 CP9TSC(cp9O_ME,cp9->M)); /* M_M<-E ... everything ends in E (the 0; 2^0=1.0) */
340 mmx[cur][cp9->M] += cp9->msc[dsq[i]][cp9->M]; /* ... + emitted match symbol */
341 imx[cur][cp9->M] = CP9TSC(cp9O_IM,cp9->M); /* I_M<-E ... everything ends in E (the 0; 2^0=1.0) */
342 imx[cur][cp9->M] += cp9->isc[dsq[i]][cp9->M]; /* ... + emitted insert symbol */
343 dmx[cur][cp9->M] = CP9TSC(cp9O_DM,cp9->M); /* D_M<-E */
344
345 /*******************************************************************
346 * No need to look at EL_k->M_M b/c elmx[cur] with cur == L means last emitted residue was L+1
347 * and this is impossible if we've come from M_M (only would be valid if we were coming from
348 * E which is handled above with the EL_k->E code).
349 *******************************************************************/
350 for (k = cp9->M-1; k >= 1; k--)
351 {
352 mmx[cur][k] = CP9TSC(cp9O_ME,k); /*M_k<- E */
353 mmx[cur][k] = ESL_MAX(mmx[cur][k], dmx[cur][k+1] + CP9TSC(cp9O_MD,k));
354 if(cp9->flags & CPLAN9_EL)
355 mmx[cur][k] = ESL_MAX(mmx[cur][k], elmx[cur][k] + CP9TSC(cp9O_MEL,k));
356 mmx[cur][k] += cp9->msc[dsq[i]][k];
357
358 /*******************************************************************
359 * No need to look at EL_k->M_M b/c elmx[cur] with cur == L means last emitted residue was L+1
360 * and this is impossible if we've come from M_M (only would be valid if we were coming from
361 * E which is handled above with the EL_k->E code).
362 *******************************************************************/
363 imx[cur][k] = dmx[cur][k+1] + CP9TSC(cp9O_ID,k);
364 imx[cur][k] += cp9->isc[dsq[i]][k];
365
366 dmx[cur][k] = dmx[cur][k+1] + CP9TSC(cp9O_DD,k);
367 /* elmx[cur][k] was set above, out of order */
368 }
369
370 /* remember M_0 is special, the B state, a non-emitter */
371 mmx[cur][0] = dmx[cur][1] + CP9TSC(cp9O_MD,0); /* M_0(B)->D_1, no seq emitted, all deletes */
372 /* above line is diff from CPBackwardOLD() which has mmx[cur][0] = -INFTY; */
373 imx[cur][0] = dmx[cur][1] + CP9TSC(cp9O_ID,0);
374 imx[cur][0] += cp9->isc[dsq[i]][0];
375
376 dmx[cur][0] = -INFTY; /*D_0 doesn't exist*/
377 elmx[cur][0] = -INFTY; /*EL_0 doesn't exist*/
378
379 scA[ip] = mmx[cur][0]; /* all parses must start in M_0, the B state */
380 fsc = Scorify(scA[ip]);
381 /*printf("ip: %d i: %d fsc: %f i: %d\n", ip, i, fsc, scA[ip]);*/
382 /* we can't have a hit starting here, b/c it would correspond to all deletes,
383 * no seq emitted, so we skip the check for if(fsc > best_sc) */
384
385 /*printf("scA[ip:%d]: %d\n", ip, scA[ip]);*/
386
387 /*printf("mmx[ip:%d][%d]: %d cur: %d\n", L+1, 0, mmx[cur][0], cur);
388 printf("imx[ip:%d][%d]: %d cur: %d\n", L+1, 0, imx[cur][0], cur);
389 printf("dmx[ip:%d][%d]: %d cur: %d\n", L+1, 0, dmx[cur][0], cur);*/
390
391 /*****************************************************************
392 * The main loop: scan the sequence from position j0-1 to i0.
393 *****************************************************************/
394 /* Recursion */
395 for (i = j0-1; i >= (i0-1); i--)
396 {
397 ip = i-i0+1; /* ip is relative index in dsq (0 to L-1) */
398 if(be_efficient) { cur = (j0-i) % 2; prv = (j0-i+1) % 2; }
399 else { cur = ip; prv = ip+1; }
400
401 /* init EL mx to -INFTY */
402 for (k = 1; k <= cp9->M; k++) elmx[cur][k] = -INFTY;
403 if(ip > 0) {
404 /* elmx[cur][k] is possibly of coming from self (EL_k), we
405 * can't have come from END b/c we haven't emitted the last res of the seq yet.
406 */
407 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[cp9->M]))
408 elmx[cur][cp9->M] = elmx[cur][cp9->M] + cp9->el_selfsc;
409
410 mmx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_MI,cp9->M);
411 mmx[cur][cp9->M] += cp9->msc[dsq[i]][cp9->M];
412
413 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[cp9->M]))
414 mmx[cur][cp9->M] = ESL_MAX(mmx[cur][cp9->M],
415 elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M));
416
417 imx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_II,cp9->M);
418 imx[cur][cp9->M] += cp9->isc[dsq[i]][cp9->M];
419 }
420 else { /* ip == 0 */
421 mmx[cur][cp9->M] = -INFTY; /* need seq to get here */
422 imx[cur][cp9->M] = -INFTY; /* need seq to get here */
423 elmx[cur][cp9->M]= -INFTY; /* first emitted res can't be from an EL, need to see >= 1 matches */
424 }
425 dmx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_DI,cp9->M);
426
427 /*******************************************************************
428 * 1b Handle EL, looking at EL_k->M_M for all valid k.
429 * EL_k->M_M transition, which has no transition penalty */
430 if(cp9->flags & CPLAN9_EL)
431 {
432 for(c = 0; c < cp9->el_from_ct[cp9->M]; c++) /* el_from_ct[cp9->M] holds # ELs that can go to M_M */
433 elmx[cur][cp9->el_from_idx[cp9->M][c]] = ESL_MAX(elmx[cur][cp9->el_from_idx[cp9->M][c]], mmx[prv][cp9->M]);
434 }
435
436 /* A main difference between a Backward scanner and
437 * regular Backward: a scanner can end at the END
438 * state at any position, regular can only end at
439 * the final position j0. */
440 if(do_scan) {
441 if(ip > 0) {
442 /*******************************************************************
443 * 2 Handle EL, looking at EL_k->E for all valid k.
444 * EL_k->M_M transition, which has no transition penalty */
445 if(cp9->flags & CPLAN9_EL) {
446 for(c = 0; c < cp9->el_from_ct[cp9->M+1]; c++) /* el_from_ct[cp9->M] holds # ELs that can go to END */
447 elmx[cur][cp9->el_from_idx[cp9->M+1][c]] = 0.; /* EL<-E, penalty incurred when we enter EL (i.e. leave going backwards) */
448 }
449 /*******************************************************************/
450 /* elmx[cur][cp9->M] is either 0 (if EL_M exists (it would nec be in el_from_idx[cp9->M+1] array if it does, so
451 * it would be filled with 0 in above loop), or -INFTY if it doesn't exist. We don't add possibility of EL_M -> EL_M
452 * self loop b/c it's impossible to do that without emitting, and we've already seen our last res emitted,
453 * either way we don't have to modify it */
454
455
456 mmx[cur][cp9->M] = ESL_MAX(mmx[cur][cp9->M],
457 elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M) + cp9->msc[dsq[i]][cp9->M]); /* M_M<-EL_M<-E, with 0 selfs in EL_M */
458 mmx[cur][cp9->M] = ESL_MAX(mmx[cur][cp9->M],
459 CP9TSC(cp9O_ME,cp9->M) + cp9->msc[dsq[i]][cp9->M]); /* M_M<-E ... */
460 /* IMPT DIFFERENCE WITH cp9_Backward(): we need to add in contribution of emission within the ESL_MAX()s above
461 * here in Viterbi since we're doing a max, but in cp9_Backward we don't b/c we do a sum and don't want
462 * to double count that emission, since it was added once already above */
463
464 imx[cur][cp9->M] = ESL_MAX(imx[cur][cp9->M],
465 (CP9TSC(cp9O_IM,cp9->M) + /* I_M<-E + (only in scanner) */
466 0 + /* all parses end in E, 2^0 = 1.0;*/
467 cp9->isc[dsq[i]][cp9->M])); /* + emitted insert symbol */
468 /* IMPT DIFFERENCE WITH cp9_Backward(): we need to add in contribution of emission within the ESL_MAX() above
469 * here in Viterbi since we're doing a max, but in cp9_Backward we don't b/c we do a sum and don't want
470 * to double count that emission, since it was added once already above */
471 }
472 dmx[cur][cp9->M] = ESL_MAX(dmx[cur][cp9->M],
473 (CP9TSC(cp9O_DM,cp9->M) + /* D_M<-E + (only in scanner) */
474 0)); /* all parses end in E, 2^0 = 1.0;*/
475 }
476 /*printf("mmx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, mmx[cur][cp9->M], cur);
477 printf("imx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, imx[cur][cp9->M], cur);
478 printf("dmx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, dmx[cur][cp9->M], cur);*/
479
480 for (k = cp9->M-1; k >= 1; k--) {
481 if(ip > 0) {
482 /*******************************************************************
483 * 3 Handle EL, looking at EL_k->M_k for all valid k and EL_k->EL_k
484 * we're going backwards so we have to work out of order
485 * we could get around this by storing the nodes each EL goes TO
486 * in an el_to_ct[] vector. */
487 if(cp9->flags & CPLAN9_EL) {
488 for(c = 0; c < cp9->el_from_ct[k]; c++) /* el_from_ct[k] holds # ELs that can go to M_k */
489 elmx[cur][cp9->el_from_idx[k][c]] = ESL_MAX(elmx[cur][cp9->el_from_idx[k][c]], mmx[prv][k]);
490 /* EL<-M, penalty incurred when we enter EL (i.e. leave going backwards) */
491 }
492 /*******************************************************************/
493
494 /* Finish off elmx[cur][k] with possibility of coming from self (EL_k),
495 * elmx[cur][k] will have been filled by block above for ks > current k,
496 * no M_k -> EL_k' with k' > k */
497 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[k]))
498 elmx[cur][k] = ESL_MAX(elmx[cur][k], elmx[prv][k] + cp9->el_selfsc);
499
500 mmx[cur][k] = ESL_MAX(ESL_MAX((mmx[prv][k+1] + CP9TSC(cp9O_MM,k)),
501 (imx[prv][k] + CP9TSC(cp9O_MI,k))),
502 (dmx[cur][k+1] + CP9TSC(cp9O_MD,k)));
503 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[k]))
504 mmx[cur][k] = ESL_MAX(mmx[cur][k], elmx[cur][k] + CP9TSC(cp9O_MEL,k)); /* penalty for entering EL */
505 mmx[cur][k] += cp9->msc[dsq[i]][k];
506
507 imx[cur][k] = ESL_MAX(ESL_MAX((mmx[prv][k+1] + CP9TSC(cp9O_IM,k)),
508 (imx[prv][k] + CP9TSC(cp9O_II,k))),
509 (dmx[cur][k+1] + CP9TSC(cp9O_ID,k)));
510 imx[cur][k] += cp9->isc[dsq[i]][k];
511
512 }
513 else { /* ip == 0 */
514 mmx[cur][k] = -INFTY; /* need seq to get here, unless we come from E in a scanner (below) */
515 imx[cur][k] = -INFTY; /* need seq to get here */
516 elmx[cur][k]= -INFTY; /* first emitted res can't be from an EL, need to see >= 1 matches */
517 }
518 if(do_scan && ip > 0) { /* add possibility of ending at this position from this state */
519 mmx[cur][k] =
520 ESL_MAX(mmx[cur][k],
521 (CP9TSC(cp9O_ME,k) + /* M_k<-E + (only in scanner) */
522 0 + /* all parses end in E, 2^0 = 1.0;*/
523 cp9->msc[dsq[i]][k])); /* emitted match symbol */
524 /* IMPT DIFFERENCE WITH cp9_Backward(): we need to add in contribution of emission within the ESL_MAX() above
525 * here in Viterbi since we're doing a max, but in cp9_Backward we don't b/c we do a sum and don't want
526 * to double count that emission, since it was added once already above */
527
528 /* No EL contribution here b/c we'd be looking for M_k<-EL_k<-E, but EL_k<-E is impossible
529 * for k != cp9->M; */
530 }
531 dmx[cur][k] = ESL_MAX(ESL_MAX((mmx[prv][k+1] + CP9TSC(cp9O_DM,k)),
532 (imx[prv][k] + CP9TSC(cp9O_DI,k))),
533 (dmx[cur][k+1] + CP9TSC(cp9O_DD,k)));
534 } /* end of for (k = cp9->M-1; k >= 1; k--) { */
535 /* Case when k == 0 */
536 /* imx[cur][0] is filled same as imx[cur][1..k] in the loop above */
537 if(ip > 0) {
538 imx[cur][0] = ESL_MAX(ESL_MAX((mmx[prv][1] + CP9TSC(cp9O_IM,0)),
539 (imx[prv][0] + CP9TSC(cp9O_II,0))),
540 (dmx[cur][1] + CP9TSC(cp9O_ID,k)));
541 imx[cur][0] += cp9->isc[dsq[i]][k];
542 }
543 else /* ip == 0 */
544 imx[cur][0] = -INFTY; /* need seq to get here */
545 dmx[cur][0] = -INFTY; /* D_0 does not exist */
546 elmx[cur][0] = -INFTY; /* EL_0 does not exist */
547
548 /*M_0 is the B state, it doesn't emit, and can be reached from any match via a begin transition */
549 mmx[cur][0] = -INFTY;
550 for (k = cp9->M; k >= 1; k--) mmx[cur][0] = ESL_MAX(mmx[cur][0], (mmx[prv][k] + CP9TSC(cp9O_BM,k)));
551 mmx[cur][0] = ESL_MAX(mmx[cur][0], (imx[prv][0] + CP9TSC(cp9O_MI,0)));
552 mmx[cur][0] = ESL_MAX(mmx[cur][0], (dmx[cur][1] + CP9TSC(cp9O_MD,0))); /* B->D_1 */
553 /* No EL contribution here, can't go B->EL_* */
554
555 /* determine isc, the int score of all possible parses starting at the current
556 * position (i) of the target sequence. */
557 scA[ip] = mmx[cur][0]; /* all parses must start in M_0, the B state */
558 fsc = Scorify(scA[ip]);
559
560 /* Update best_sc:
561 * There's a 'backwards-specific' off-by-one here, that only occurs b/c we're going backwards,
562 * this is probably implementation specific (meaning getting rid of it is possible, but
563 * I can't figure it out), but we deal with it (albeit confusingly) as follows:
564 *
565 * '*off-by-one*' marked comments below refers to this issue:
566 * All Backward hits are rooted in M_O, the B (begin) state, which is a non-emitter.
567 * let i = ip+i0-1 => ip = i-i0+1;
568 * so sc[ip] = backward->mmx[ip][0] = summed log prob of all parses that end at j0,
569 * and start at position i+1 of the sequence (because i+1 is the last residue
570 * whose emission has been accounted for).
571 */
572
573 if(fsc > best_sc) { best_sc = fsc; best_pos= i+1; } /* *off-by-one* */
574 } /* end loop over start positions i */
575
576 if(doing_align) { /* best_sc is the alignment score */
577 best_sc = Scorify(scA[(j0-i0+1)]); /* L = j0-i0+1 */
578 best_pos = i0;
579 }
580 if(ret_sc != NULL) *ret_sc = best_sc;
581 if(ret_maxres != NULL) *ret_maxres = best_pos;
582 if(ret_psc != NULL) *ret_psc = scA;
583 else free(scA);
584 ESL_DPRINTF1(("#DEBUG: cp9_ViterbiBackward() return score: %10.4f\n", best_sc));
585
586 return eslOK;
587
588 ERROR:
589 ESL_FAIL(eslEMEM, errbuf, "Memory allocation error.");
590 }
591
592
593 /* Function: cp9_Forward()
594 *
595 * Purpose: Runs the Forward dynamic programming algorithm on an
596 * input subsequence (i0-j0). Complements cp9_Backward().
597 * Somewhat flexible based on input options as follows:
598 *
599 * if(be_efficient): only allocates 2 rows of the Forward
600 * matrix, else allocates full L+1 matrix.
601 *
602 * if(do_scan): allows parses to start at any position i
603 * i0..j0, changing meaning of DP matrix cells as discussed
604 * below.
605 *
606 * if(! do_scan): all parses must begin at i0.
607 *
608 * Reference for algorithm (when do_scan is FALSE):
609 * Durbin et. al. Biological Sequence Analysis; p. 58.
610 *
611 * The meaning of the Forward (F) matrix DP cells for
612 * matches (M) inserts (I) and deletes (D):
613 *
614 * For relative subsequence positions ip = 0..L:
615 * For HMM nodes 1..M:
616 * F->M[ip][k] : sum of all parses emitting seq
617 * from i0..ip that visit node k's match
618 * state, which emits posn ip
619 * F->I[ip][k] : sum of all parses emitting seq from
620 * i0..ip that visit node k's insert
621 * state, which emits posn ip
622 * F->D[ip][k] : sum of all parses emitting seq from
623 * i0..ip that visit node k's delete
624 * delete state, last emitted (leftmost)
625 * posn was ip
626 *
627 * For *special* HMM node 0:
628 * F->M[ip][0] : M_0 is the Begin state, which does not
629 * emit, so this is the sum of all parses
630 * emitting seq from i0..ip that start
631 * in the begin state, the last emitted
632 * (leftmost) posn was ip.
633 *
634 * Note: if ip=0, only D_k and M_0 states can have
635 * non-IMPOSSIBLE values.
636 *
637 * if(do_scan) the 'i0..ip' in the above definitions is
638 * changed to iE..ip such that i0 <= iE <= ip. Meaning
639 * any residue can be the first residue emitted in the
640 * parse. This means F->M[ip][0] is the sum of all parses
641 * emitting a subseq starting anywhere from i0..ip and
642 * ending at ip.
643 *
644 *
645 * Args:
646 * cp9 - the cp9 HMM
647 * errbuf - char buffer for error messages
648 * dsq - sequence in digitized form
649 * i0 - start of target subsequence (1 for beginning of dsq)
650 * j0 - end of target subsequence (L for end of dsq)
651 * do_scan - TRUE if we're scanning, HMM can start to emit anywhere i0..j0,
652 * FALSE if we're not, HMM must start emitting at i0, end emitting at j0
653 * doing_align - TRUE if reason we've called this function is to help get posteriors
654 * for CM alignment, in which case we can skip the traceback.
655 * be_efficient- TRUE to keep only 2 rows of DP matrix in memory, FALSE keep whole thing
656 * ret_psc - RETURN: int log odds Forward score for each end point [0..(j0-i0+1)]
657 * ret_maxres- RETURN: start position that gives maximum score max argmax_i sc[i]
658 * ret_sc - RETURN: see below
659 *
660 * Returns: <ret_sc>: if(!do_scan) log P(S|M)/P(S|R), as a bit score
661 * else max log P(S|M)/P(S|R), for argmax subseq S of input seq i0..j0,
662 * eslOK on success;
663 * eslEINCOMPAT on contract violation;
664 */
665 int
666 cp9_Forward(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int i0, int j0, int do_scan, int doing_align,
667 int be_efficient, int **ret_psc, int *ret_maxres, float *ret_sc)
668 {
669 int status;
670 int j; /* actual position in the subsequence */
671 int jp; /* j': relative position in the subsequence */
672 int cur, prv; /* rows in DP matrix 0 or 1 */
673 int k; /* CP9 HMM node position */
674 int L; /* j0-i0+1: subsequence length */
675 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
676 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
677 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
678 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
679 int *erow; /* end score for each position [0..1] */
680 int *scA; /* prob (seq from j0..jp | HMM) [0..jp..cp9->M] */
681 float fsc; /* float log odds score */
682 float best_sc; /* score of best hit overall */
683 float best_pos; /* residue (j) giving best_sc, where best hit ends */
684 int nrows = 2; /* number of rows for the dp matrix */
685 int c; /* counter for EL states */
686 int M; /* cp9->M, query length, number of consensus nodes of model */
687
688 /* Contract checks */
689 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Forward, cp9 is NULL.\n");
690 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Forward, dsq is NULL.");
691 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Forward, mx is NULL.\n");
692
693 best_sc = IMPOSSIBLE;
694 best_pos = -1;
695 L = j0-i0+1;
696 M = cp9->M;
697
698 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
699
700 /* Grow DP matrix if nec, to either 2 rows or L+1 rows (depending on be_efficient),
701 * stays M+1 columns */
702 if(be_efficient) nrows = 1; /* mx will be 2 rows */
703 else nrows = L; /* mx will be L+1 rows */
704 if((status = GrowCP9Matrix(mx, errbuf, nrows, M, NULL, NULL, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
705 ESL_DPRINTF1(("#DEBUG: cp9_Forward(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
706 ESL_DPRINTF1(("#DEBUG: cp9_Forward do_scan: %d\n", do_scan));
707
708 /* scA will hold P(seq up to j | Model) in int log odds form */
709 ESL_ALLOC(scA, sizeof(int) * (j0-i0+2));
710
711 /* Initialization of the zero row. */
712 mmx[0][0] = 0; /* M_0 is state B, and everything starts in B */
713 imx[0][0] = -INFTY; /* I_0 is state N, can't get here without emitting*/
714 dmx[0][0] = -INFTY; /* D_0 doesn't exist. */
715 elmx[0][0]= -INFTY; /* can't go from B to EL state */
716 erow[0] = -INFTY;
717
718 /* Because there's a D state for every node 1..M,
719 dmx[0][k] is possible for all k 1..M */
720 int sc;
721 for (k = 1; k <= M; k++)
722 {
723 mmx[0][k] = imx[0][k] = elmx[0][k] = -INFTY; /* need seq to get here */
724 sc = ILogsum(ILogsum(mmx[0][k-1] + CP9TSC(cp9O_MD,k-1),
725 imx[0][k-1] + CP9TSC(cp9O_ID,k-1)),
726 dmx[0][k-1] + CP9TSC(cp9O_DD,k-1));
727 dmx[0][k] = sc;
728 }
729 /* We can do a full parse through all delete states. */
730 erow[0] = dmx[0][M] + CP9TSC(cp9O_DM,M);
731 scA[0] = erow[0];
732 fsc = Scorify(scA[0]);
733 /*printf("jp: %d j: %d fsc: %f isc: %d\n", jp, j, fsc, isc[jp]);*/
734 if(fsc > best_sc)
735 {
736 best_sc = fsc;
737 best_pos= i0-1;
738 }
739 /*printf("jp: %d j: %d fsc: %f sc: %d\n", 0, i0-1, Scorify(sc[0]), sc[0]);*/
740
741 /*****************************************************************
742 * The main loop: scan the sequence from position i0 to j0.
743 *****************************************************************/
744 /* Recursion. */
745
746 /* int ctr = 0; */
747 for (j = i0; j <= j0; j++)
748 {
749 int const *isc = cp9->isc[dsq[j]];
750 int const *msc = cp9->msc[dsq[j]];
751 int endsc = -INFTY;
752 int el_selfsc = cp9->el_selfsc;
753 int sc;
754
755 jp = j-i0+1; /* jp is relative position in the sequence 1..L */
756 cur = (j-i0+1);
757 prv = (j-i0);
758
759 if(be_efficient)
760 {
761 cur %= 2;
762 prv %= 2;
763 }
764
765 /* The 1 difference between a Viterbi scanner and the
766 * regular Viterbi. In non-scanner parse must begin in B at
767 * position 0 (i0-1), in scanner we can start at any position
768 * in the seq. */
769 mmx[cur][0] = (do_scan == TRUE) ? 0 : -INFTY;
770 dmx[cur][0] = -INFTY; /*D_0 is non-existent*/
771 elmx[cur][0] = -INFTY; /*no EL state for node 0 */
772
773 sc = ILogsum(ILogsum(mmx[prv][0] + CP9TSC(cp9O_MI,0),
774 imx[prv][0] + CP9TSC(cp9O_II,0)),
775 dmx[prv][0] + CP9TSC(cp9O_DI,0));
776 imx[cur][0] = sc + isc[0];
777
778 for (k = 1; k <= M; k++)
779 {
780 /*match state*/
781 sc = ILogsum(ILogsum(mmx[prv][k-1] + CP9TSC(cp9O_MM,k-1),
782 imx[prv][k-1] + CP9TSC(cp9O_IM,k-1)),
783 ILogsum(dmx[prv][k-1] + CP9TSC(cp9O_DM,k-1),
784 mmx[prv][0] + CP9TSC(cp9O_BM,k )));
785 /* check possibility we came from an EL, if they're valid */
786 for(c = 0; c < cp9->el_from_ct[k]; c++) /* el_from_ct[k] is >= 0 */
787 sc = ILogsum(sc, elmx[prv][cp9->el_from_idx[k][c]]);
788 /* transition penalty to EL incurred when EL was entered */
789 mmx[cur][k] = sc + msc[k];
790
791 /* E state update */
792 endsc = ILogsum(endsc, mmx[cur][k] + CP9TSC(cp9O_ME,k));
793
794 /*insert state*/
795 sc = ILogsum(ILogsum(mmx[prv][k] + CP9TSC(cp9O_MI,k),
796 imx[prv][k] + CP9TSC(cp9O_II,k)),
797 dmx[prv][k] + CP9TSC(cp9O_DI,k));
798 imx[cur][k] = sc + isc[k];
799
800 /*delete state*/
801 sc = ILogsum(ILogsum(mmx[cur][k-1] + CP9TSC(cp9O_MD,k-1),
802 imx[cur][k-1] + CP9TSC(cp9O_ID,k-1)),
803 dmx[cur][k-1] + CP9TSC(cp9O_DD,k-1));
804 dmx[cur][k] = sc;
805
806 /*el state*/
807 sc = -INFTY;
808 if((cp9->flags & CPLAN9_EL) && cp9->has_el[k]) /* not all HMM nodes have an EL state (for ex:
809 HMM nodes that map to right half of a MATP_MP) */
810 {
811 sc = ILogsum(mmx[cur][k] + CP9TSC(cp9O_MEL,k), /* transitioned from cur node's match state */
812 elmx[prv][k] + el_selfsc); /* transitioned from cur node's EL state emitted ip on transition */
813 }
814 elmx[cur][k] = sc;
815 /*printf("mmx [jp:%d][%d]: %d\n", jp, k, mmx[cur][k]);
816 printf("imx [jp:%d][%d]: %d\n", jp, k, imx[cur][k]);
817 printf("dmx [jp:%d][%d]: %d\n", jp, k, dmx[cur][k]);
818 printf("elmx[jp:%d][%d]: %d\n", jp, k, elmx[cur][k]);*/
819 }
820 endsc = ILogsum(ILogsum(endsc, dmx[cur][M] + CP9TSC(cp9O_DM,M)), /* transition from D_M -> end */
821 imx[cur][M] + CP9TSC(cp9O_IM,M)); /* transition from I_M -> end */
822 for(c = 0; c < cp9->el_from_ct[M+1]; c++) /* el_from_ct[k] is >= 0 */
823 endsc = ILogsum(endsc, elmx[cur][cp9->el_from_idx[M+1][c]]);
824 /* transition penalty to EL incurred when EL was entered */
825 /*printf("endsc: %d\n", endsc);*/
826
827 erow[cur] = endsc;
828 scA[jp] = endsc;
829 fsc = Scorify(endsc);
830
831 if(fsc > best_sc) { best_sc = fsc; best_pos= j; }
832 } /* end loop over end positions j */
833
834 if(doing_align) { /* best_sc is the alignment score */
835 best_sc = Scorify(scA[(j0-i0+1)]); /* L = j0-i0+1 */
836 best_pos = i0;
837 }
838 if(ret_sc != NULL) *ret_sc = best_sc;
839 if(ret_maxres != NULL) *ret_maxres = best_pos;
840 if(ret_psc != NULL) *ret_psc = scA;
841 else free(scA);
842 ESL_DPRINTF1(("#DEBUG: cp9_Forward() return score: %10.4f\n", best_sc));
843
844 return eslOK;
845
846 ERROR:
847 ESL_FAIL(eslEMEM, errbuf, "Memory allocation error.");
848 }
849
850
851 /* Function: cp9_Backward()
852 *
853 * Purpose: Runs the Backward dynamic programming algorithm on an
854 * input subsequence (i0-j0). Complements CP9Forward().
855 * Somewhat flexible based on input options as follows:
856 *
857 * if(be_efficient): only allocates 2 rows of the Backward
858 * matrix, else allocates full L+1 matrix.
859 *
860 * if(do_scan): allows parses to end at
861 * at any position j in i0..j0, and start at any position
862 * i in i0..j0, changing meaning of DP matrix cells as
863 * discussed below.
864 *
865 * if(! do_scan): all parses must end at j0
866 *
867 * Reference for algorithm (when do_scan is FALSE):
868 * Durbin et. al. Biological Sequence Analysis; p. 59.
869 * With 1 IMPORTANT difference, emission scores for
870 * residue at posn j are part of the sum in DP cells
871 * for position j, but in Durbin, emission scores for
872 * residue at posn j+1 are part of the sum in DP cells
873 * for position j. The Durbin method makes it more
874 * straightforward to combine Backward and Forward
875 * cells to get posteriors, but it causes precision issues
876 * (overall Backward Score P(seq|X) != overall Forward Score
877 * P(seq|X) solely due to integer log odds scaling precision
878 * issues as investigated in
879 * ~nawrockie/notebook/7_0410_inf_hmmfb_hbanded_scan/00LOG)
880 * So I've resorted to the algorithm implemented here, the
881 * meaning of the Backward DP cells is given below. This
882 * implementation requires the subtraction of an emission
883 * score when combining corresponding Forward and Backward
884 * DP cells to get posteriors, b/c they've been double
885 * counted.
886 *
887 * I've wasted a lot of time rewrapping my head around this
888 * function when I revisit it, so I'll be verbose about the
889 * the meaning of the Backward (B) matrix DP cells for
890 * matches (M) inserts (I) and deletes (D) here:
891 *
892 * For relative subsequence positions jp = 0..L:
893 * For HMM nodes 1..M:
894 * B->M[jp][k] : sum of all parses emitting seq
895 * from jp+1..j0 that visit node k's match
896 * state, which emitted posn jp
897 * B->I[jp][k] : sum of all parses emitting seq from
898 * jp+1..j0 that visit node k's insert
899 * state, which emitted posn jp
900 * B->D[jp][k] : sum of all parses emitting seq from
901 * jp+1..j0 that visit node k's delete
902 * delete state, last emitted (rightmost)
903 * posn was jp+1
904 * B->EL[jp][k]: sum of all parses emitting seq from
905 * jp+1..j0 that visit node k's EL
906 * state, which MAY OR MAY NOT have
907 * emitted any posns >= jp+1, last
908 * emitted (rightmost) posn was jp+1.
909 * Some nodes k do not have an EL state
910 * (if cp9->has_el[k] == FALSE)
911 * NOTE: EL can act as non-emitter if 0
912 * self loops taken or emitter if >= 1
913 * self loops taken, this is why we
914 * treat jp as having NOT YET BEEN EMITTED
915 * which is different than the M and I
916 * convention.
917 *
918 * For *special* HMM node 0:
919 * B->M[jp][0] : M_0 is the Begin state, which does not
920 * emit, so this is the sum of all parses
921 * emitting seq from jp+1..j0 that start
922 * in the begin state, the last emitted
923 * (rightmost) posn was jp+1.
924 *
925 * Note: if jp=0, only D and M_0 states can have
926 * non-IMPOSSIBLE values.
927 *
928 * if(do_scan) the 'jp+1..j0' in the above definitions is
929 * changed to jp+1..jE such that jp+1 <= jE <= j0. Meaning
930 * any residue can be the final residue emitted in the
931 * parse. This means B->M[jp][0] is the sum of all parses
932 * emitting a subseq ending anywhere from jp+1..j0 and
933 * starting at jp+1.
934 *
935 * The *will emit* in the above definitions refers to
936 * the fact that emission scores from a state x are not
937 * counted in the matrix score for state x, and are only
938 * added when we calculate a matrix score for state y,
939 * after transitioning (backwards) from y to x. See
940 * code. This is done to facilitate combining Forward
941 * and Backward cells to get posterior probabilities
942 * in CP9Posterior().
943 *
944 * Args:
945 * cp9 - the CP9 HMM
946 * errbuf - char buffer for error messages
947 * dsq - sequence in digitized form
948 * i0 - start of target subsequence (1 for beginning of dsq)
949 * j0 - end of target subsequence (L for end of dsq)
950 * W - the maximum size of a hit
951 * hit_len_guess - the presumed length of a hit, this is needed b/c we only
952 * determine start points (i) in this function, but when we store 'hits'
953 * we need a start point j, j=i+hit_len_guess-1.
954 * This is only used if (! j_is_fixed).
955 * cutoff - minimum score to report
956 * do_scan - TRUE if we're scanning, HMM can start to emit anywhere i0..j0,
957 * FALSE if we're not, HMM must start emitting at i0, end emitting at j0
958 * doing_align - TRUE if reason we've called this function is to help get posteriors
959 * for CM alignment, in which case we can skip the traceback.
960 * be_efficient- TRUE to keep only 2 rows of DP matrix in memory, FALSE keep whole thing
961 * do_null3 - TRUE to do NULL3 score correction, FALSE not to
962 * ret_psc - RETURN: int log odds Backward score for each start point [0..(j0-i0+1)]
963 * ret_maxres- RETURN: start position that gives maximum score max argmax_i sc[i]
964 * ret_sc - RETURN: see below
965 *
966 * Returns: <ret_sc>: if(!do_scan) log P(S|M)/P(S|R), as a bit score, this is B->M[0][0]
967 * else max log P(S|M)/P(S|R), for argmax subseq S of input seq i0..j0,
968 * this is max_jp B->M[jp][0]
969 * eslOK on success;
970 * eslEINCOMPAT on contract violation;
971 */
972 int
973 cp9_Backward(CP9_t *cp9, char *errbuf, CP9_MX *mx, ESL_DSQ *dsq, int i0, int j0, int do_scan, int doing_align,
974 int be_efficient, int **ret_psc, int *ret_maxres, float *ret_sc)
975 {
976 int status;
977 int i; /* actual position in the subsequence */
978 int ip; /* i': relative position in the subsequence */
979 int cur, prv; /* rows in DP matrix 0 or 1 */
980 int k; /* CP9 HMM node position */
981 int L; /* j0-i0+1: subsequence length */
982 int **mmx; /* DP matrix for match state scores [0..1][0..cp9->M] */
983 int **imx; /* DP matrix for insert state scores [0..1][0..cp9->M] */
984 int **dmx; /* DP matrix for delete state scores [0..1][0..cp9->M] */
985 int **elmx; /* DP matrix for EL state scores [0..1][0..cp9->M] */
986 int *erow; /* end score for each position [0..1] */
987 int *scA; /* prob (seq from j0..jp | HMM) [0..jp..cp9->M] */
988 float fsc; /* float log odds score */
989 float best_sc; /* score of best hit overall */
990 float best_pos; /* residue (i) giving best_sc, where best hit starts */
991 int nrows; /* num rows for DP matrix, 2 or L+1 depending on be_efficient */
992 int c; /* counter for EL states */
993 int M; /* cp9->M */
994
995 /* Contract checks */
996 if(cp9 == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Backward, cp9 is NULL.\n");
997 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Backward, dsq is NULL.");
998 if(mx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_Backward, mx is NULL.\n");
999
1000 int const *tsc = cp9->otsc; /* ptr to efficiently ordered transition scores */
1001
1002 best_sc = IMPOSSIBLE;
1003 best_pos = -1;
1004 L = j0-i0+1;
1005 M = cp9->M;
1006
1007 /* Grow DP matrix if nec, to either 2 rows or L+1 rows (depending on be_efficient),
1008 * stays M+1 columns */
1009 if(be_efficient) nrows = 1; /* mx will be 2 rows */
1010 else nrows = L; /* mx will be L+1 rows */
1011 if((status = GrowCP9Matrix(mx, errbuf, nrows, M, NULL, NULL, &mmx, &imx, &dmx, &elmx, &erow)) != eslOK) return status;
1012 ESL_DPRINTF1(("#DEBUG: cp9_Backward(): CP9 matrix size: %.8f Mb rows: %d.\n", mx->size_Mb, mx->rows));
1013 ESL_DPRINTF1(("#DEBUG: cp9_Backward do_scan: %d\n", do_scan));
1014
1015 /* scA will hold P(seq from i..j0 | Model) for each i in int log odds form */
1016 ESL_ALLOC(scA, sizeof(int) * (j0-i0+3));
1017
1018 /* Initialization of the L (i = j0, cur = (j0-i) = (j0-j0) %2 = 0) row. */
1019 if(be_efficient) cur = 0;
1020 else cur = j0-i0+1; /* L */
1021 ip = j0-i0+1; /*L */
1022 i = j0;
1023
1024 /*******************************************************************
1025 * 0 Handle EL, looking at EL_k->E for all valid k.
1026 * we're going backwards so we have to work out of order, we could get
1027 * around this by storing the nodes each EL goes TO in an el_to_ct[] vec. */
1028 /* init to -INFTY */
1029 for (k = 1; k <= cp9->M; k++)
1030 elmx[cur][k] = -INFTY;
1031 if(cp9->flags & CPLAN9_EL)
1032 {
1033 for(c = 0; c < cp9->el_from_ct[cp9->M+1]; c++) /* el_from_ct[cp9->M+1] holds # ELs that can go to END */
1034 elmx[cur][cp9->el_from_idx[cp9->M+1][c]] = 0.; /* EL<-E, penalty incurred when we enter EL (i.e. leave going backwards) */
1035 }
1036 /*******************************************************************/
1037
1038 /* elmx[cur][cp9->M] is either 0 (if EL_M exists (it would nec be in el_from_idx[cp9->M+1] array if it does, so
1039 * it would be filled with 0 in above loop), or -INFTY if it doesn't exist. We don't add possibility of EL_M -> EL_M
1040 * self loop b/c it's impossible to do that without emitting, and we've already seen our last res emitted.
1041 * either way we don't have to modify it */
1042
1043 mmx[cur][cp9->M] = 0. +
1044 ILogsum(elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M),/* M_M<-EL_M<-E, with 0 self loops in EL_M */
1045 CP9TSC(cp9O_ME,cp9->M)); /* M_M<-E ... everything ends in E (the 0; 2^0=1.0) */
1046 mmx[cur][cp9->M] += cp9->msc[dsq[i]][cp9->M]; /* ... + emitted match symbol */
1047 imx[cur][cp9->M] = 0. + CP9TSC(cp9O_IM,cp9->M); /* I_M<-E ... everything ends in E (the 0; 2^0=1.0) */
1048 imx[cur][cp9->M] += cp9->isc[dsq[i]][cp9->M]; /* ... + emitted insert symbol */
1049 dmx[cur][cp9->M] = CP9TSC(cp9O_DM,cp9->M); /* D_M<-E */
1050
1051 /*******************************************************************
1052 * No need to look at EL_k->M_M b/c elmx[cur] with cur == L means last emitted residue was L+1
1053 * and this is impossible if we've come from M_M (only would be valid if we were coming from
1054 * E which is handled above with the EL_k->E code).
1055 *******************************************************************/
1056
1057 for (k = cp9->M-1; k >= 1; k--)
1058 {
1059 mmx[cur][k] = 0 + CP9TSC(cp9O_ME,k); /*M_k<- E */
1060 mmx[cur][k] = ILogsum(mmx[cur][k], dmx[cur][k+1] + CP9TSC(cp9O_MD,k));
1061 if(cp9->flags & CPLAN9_EL)
1062 mmx[cur][k] = ILogsum(mmx[cur][k], elmx[cur][k] + CP9TSC(cp9O_MEL,k));
1063 mmx[cur][k] += cp9->msc[dsq[i]][k];
1064
1065 /*******************************************************************
1066 * No need to look at EL_k->M_M b/c elmx[cur] with cur == L means last emitted residue was L+1
1067 * and this is impossible if we've come from M_M (only would be valid if we were coming from
1068 * E which is handled above with the EL_k->E code).
1069 *******************************************************************/
1070 imx[cur][k] = dmx[cur][k+1] + CP9TSC(cp9O_ID,k);
1071 imx[cur][k] += cp9->isc[dsq[i]][k];
1072
1073 dmx[cur][k] = dmx[cur][k+1] + CP9TSC(cp9O_DD,k);
1074 /* elmx[cur][k] was set above, out of order */
1075 }
1076
1077 /* remember M_0 is special, the B state, a non-emitter */
1078 mmx[cur][0] = dmx[cur][1] + CP9TSC(cp9O_MD,0); /* M_0(B)->D_1, no seq emitted, all deletes */
1079 /* above line is diff from CPBackwardOLD() which has mmx[cur][0] = -INFTY; */
1080 imx[cur][0] = dmx[cur][1] + CP9TSC(cp9O_ID,0);
1081 imx[cur][0] += cp9->isc[dsq[i]][0];
1082
1083 dmx[cur][0] = -INFTY; /*D_0 doesn't exist*/
1084 elmx[cur][0] = -INFTY; /*EL_0 doesn't exist*/
1085
1086 scA[ip] = mmx[cur][0]; /* all parses must start in M_0, the B state */
1087 fsc = Scorify(scA[ip]);
1088
1089 /*****************************************************************
1090 * The main loop: scan the sequence from position j0-1 to i0.
1091 *****************************************************************/
1092 /* Recursion */
1093 for (i = j0-1; i >= i0; i--)
1094 {
1095 ip = i-i0+1; /* ip is relative index in dsq (0 to L-1) */
1096 if(be_efficient) { cur = (j0-i) %2; prv = (j0-i+1)%2; }
1097 else { cur = ip; prv = ip+1; }
1098
1099 /* init EL mx to -INFTY */
1100 for (k = 0; k <= cp9->M; k++) elmx[cur][k] = -INFTY;
1101
1102 /* elmx[cur][k] is possibly of coming from self (EL_k), we
1103 * can't have come from END b/c we haven't emitted the last res of the seq yet.
1104 */
1105 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[cp9->M]))
1106 elmx[cur][cp9->M] = elmx[cur][cp9->M] + cp9->el_selfsc;
1107
1108 mmx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_MI,cp9->M);
1109 mmx[cur][cp9->M] += cp9->msc[dsq[i]][cp9->M];
1110
1111 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[cp9->M]))
1112 mmx[cur][cp9->M] = ILogsum(mmx[cur][cp9->M],
1113 elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M));
1114
1115 imx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_II,cp9->M);
1116 imx[cur][cp9->M] += cp9->isc[dsq[i]][cp9->M];
1117
1118 dmx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_DI,cp9->M);
1119
1120 /*******************************************************************
1121 * 1b Handle EL, looking at EL_k->M_M for all valid k.
1122 * EL_k->M_M transition, which has no transition penalty */
1123 if(cp9->flags & CPLAN9_EL)
1124 {
1125 for(c = 0; c < cp9->el_from_ct[cp9->M]; c++) /* el_from_ct[cp9->M] holds # ELs that can go to M_M */
1126 elmx[cur][cp9->el_from_idx[cp9->M][c]] = ILogsum(elmx[cur][cp9->el_from_idx[cp9->M][c]], mmx[prv][cp9->M]);
1127 }
1128
1129 /* A main difference between a Backward scanner and
1130 * regular Backward: a scanner can end at the END
1131 * state at any position, regular can only end at
1132 * the final position j0. */
1133 if(do_scan) {
1134 /*******************************************************************
1135 * 2 Handle EL, looking at EL_k->E for all valid k.
1136 * EL_k->M_M transition, which has no transition penalty */
1137 if(cp9->flags & CPLAN9_EL)
1138 {
1139 for(c = 0; c < cp9->el_from_ct[cp9->M+1]; c++) /* el_from_ct[cp9->M] holds # ELs that can go to END */
1140 elmx[cur][cp9->el_from_idx[cp9->M+1][c]] = 0.; /* EL<-E, penalty incurred when we enter EL (i.e. leave going backwards) */
1141 }
1142 /*******************************************************************/
1143 /* elmx[cur][cp9->M] is either 0 (if EL_M exists (it would nec be in el_from_idx[cp9->M+1] array if it does, so
1144 * it would be filled with 0 in above loop), or -INFTY if it doesn't exist. We don't add possibility of EL_M -> EL_M
1145 * self loop b/c it's impossible to do that without emitting, and we've already seen our last res emitted,
1146 * either way we don't have to modify it */
1147
1148 mmx[cur][cp9->M] =
1149 ILogsum(mmx[cur][cp9->M],
1150 ILogsum(elmx[cur][cp9->M] + CP9TSC(cp9O_MEL,cp9->M),/* M_M<-EL_M<-E, with 0 selfs in EL_M */
1151 CP9TSC(cp9O_ME,cp9->M))); /* M_M<-E ... */
1152 /* DO NOT add contribution of emitting i from M, it's been added above */
1153
1154 imx[cur][cp9->M] =
1155 ILogsum(imx[cur][cp9->M],
1156 (CP9TSC(cp9O_IM,cp9->M) + /* I_M<-E + (only in scanner) */
1157 0)); /* all parses end in E, 2^0 = 1.0;*/
1158 /* DO NOT add contribution of emitting i from M, it's been added above */
1159 dmx[cur][cp9->M] =
1160 ILogsum(dmx[cur][cp9->M],
1161 (CP9TSC(cp9O_DM,cp9->M) + /* D_M<-E + (only in scanner) */
1162 0)); /* all parses end in E, 2^0 = 1.0;*/
1163 }
1164 /*printf("mmx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, mmx[cur][cp9->M], cur);
1165 printf("imx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, imx[cur][cp9->M], cur);
1166 printf("dmx[ip:%d][%d]: %d cur: %d\n", ip, cp9->M, dmx[cur][cp9->M], cur);*/
1167
1168 for (k = cp9->M-1; k >= 1; k--)
1169 {
1170 /*******************************************************************
1171 * 3 Handle EL, looking at EL_k->M_k for all valid k and EL_k->EL_k
1172 * we're going backwards so we have to work out of order
1173 * we could get around this by storing the nodes each EL goes TO
1174 * in an el_to_ct[] vector. */
1175 if(cp9->flags & CPLAN9_EL) {
1176 for(c = 0; c < cp9->el_from_ct[k]; c++) /* el_from_ct[k] holds # ELs that can go to M_k */
1177 elmx[cur][cp9->el_from_idx[k][c]] = ILogsum(elmx[cur][cp9->el_from_idx[k][c]], mmx[prv][k]);
1178 /* EL<-M, penalty incurred when we enter EL (i.e. leave going backwards) */
1179 }
1180 /*******************************************************************/
1181
1182 /* Finish off elmx[cur][k] with possibility of coming from self (EL_k),
1183 * elmx[cur][k] will have been filled by block above for ks > current k,
1184 * no M_k -> EL_k' with k' > k */
1185 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[k]))
1186 elmx[cur][k] = ILogsum(elmx[cur][k], elmx[prv][k] + cp9->el_selfsc);
1187
1188 mmx[cur][k] = ILogsum(ILogsum((mmx[prv][k+1] + CP9TSC(cp9O_MM,k)),
1189 (imx[prv][k] + CP9TSC(cp9O_MI,k))),
1190 (dmx[cur][k+1] + CP9TSC(cp9O_MD,k)));
1191 if((cp9->flags & CPLAN9_EL) && (cp9->has_el[k]))
1192 mmx[cur][k] = ILogsum(mmx[cur][k], elmx[cur][k] + CP9TSC(cp9O_MEL,k)); /* penalty for entering EL */
1193 mmx[cur][k] += cp9->msc[dsq[i]][k];
1194
1195 imx[cur][k] = ILogsum(ILogsum((mmx[prv][k+1] + CP9TSC(cp9O_IM,k)),
1196 (imx[prv][k] + CP9TSC(cp9O_II,k))),
1197 (dmx[cur][k+1] + CP9TSC(cp9O_ID,k)));
1198 imx[cur][k] += cp9->isc[dsq[i]][k];
1199
1200 if(do_scan) { /* add possibility of ending at this position from this state */
1201 mmx[cur][k] =
1202 ILogsum(mmx[cur][k],
1203 (CP9TSC(cp9O_ME,k) + /* M_k<-E + (only in scanner) */
1204 0)); /* all parses end in E, 2^0 = 1.0;*/
1205 /* DO NOT add contribution of emitting i from M, it's been added above */
1206 /* No EL contribution here b/c we'd be looking for M_k<-EL_k<-E, but EL_k<-E is impossible
1207 * for k != cp9->M; */
1208 }
1209 dmx[cur][k] = ILogsum(ILogsum((mmx[prv][k+1] + CP9TSC(cp9O_DM,k)),
1210 (imx[prv][k] + CP9TSC(cp9O_DI,k))),
1211 (dmx[cur][k+1] + CP9TSC(cp9O_DD,k)));
1212 }
1213 /* Case when k == 0 */
1214 /* imx[cur][0] is filled same as imx[cur][1..k] in the loop above */
1215 imx[cur][0] = ILogsum(ILogsum((mmx[prv][1] + CP9TSC(cp9O_IM,0)),
1216 (imx[prv][0] + CP9TSC(cp9O_II,0))),
1217 (dmx[cur][1] + CP9TSC(cp9O_ID,k)));
1218 imx[cur][0] += cp9->isc[dsq[i]][k];
1219 dmx[cur][0] = -INFTY; /* D_0 does not exist */
1220 elmx[cur][0] = -INFTY; /* EL_0 does not exist */
1221
1222 /*M_0 is the B state, it doesn't emit, and can be reached from any match via a begin transition */
1223 mmx[cur][0] = -INFTY;
1224 for (k = cp9->M; k >= 1; k--)
1225 mmx[cur][0] = ILogsum(mmx[cur][0], (mmx[prv][k] + CP9TSC(cp9O_BM,k)));
1226 mmx[cur][0] = ILogsum(mmx[cur][0], (imx[prv][0] + CP9TSC(cp9O_MI,0)));
1227 mmx[cur][0] = ILogsum(mmx[cur][0], (dmx[cur][1] + CP9TSC(cp9O_MD,0))); /* B->D_1 */
1228 /* No EL contribution here, can't go B->EL_* */
1229
1230 /* determine isc, the int score of all possible parses starting at the current
1231 * position (i) of the target sequence. */
1232 scA[ip] = mmx[cur][0]; /* all parses must start in M_0, the B state */
1233 fsc = Scorify(scA[ip]);
1234
1235 /* Update best_sc, the little semi-Markov model that deals with multihit parsing:
1236 * There's a 'backwards-specific' off-by-one here, that only occurs b/c we're going backwards,
1237 * this is probably implementation specific (meaning getting rid of it is possible, but
1238 * I can't figure it out), but we deal with it (albeit confusingly) as follows:
1239 *
1240 * '*off-by-one*' marked comments below refers to this issue:
1241 * All Backward hits are rooted in M_O, the B (begin) state, which is a non-emitter.
1242 * let i = ip+i0-1 => ip = i-i0+1;
1243 * so scA[ip] = backward->mmx[ip][0] = summed log prob of all parses that end at j0,
1244 * and start at position i+1 of the sequence (because i+1 is the last residue
1245 * whose emission has been accounted for).
1246 */
1247
1248 if(fsc > best_sc) { best_sc = fsc; best_pos= i+1; } /* *off-by-one* */
1249 }
1250 /*******************************************************************/
1251 /* Special case: ip == 0, i = i0-1; */
1252 ip = i-i0+1; /* ip is relative index in dsq (0 to L-1) */
1253 if(be_efficient) {
1254 cur = (j0-i) %2;
1255 prv = (j0-i+1)%2;
1256 }
1257 else {
1258 cur = ip;
1259 prv = ip+1;
1260 }
1261
1262 /* init EL mx to -INFTY */
1263 for (k = 1; k <= cp9->M; k++) elmx[cur][k] = -INFTY;
1264
1265 mmx[cur][cp9->M] = -INFTY; /* need seq to get here */
1266 imx[cur][cp9->M] = -INFTY; /* need seq to get here */
1267 elmx[cur][cp9->M]= -INFTY; /* first emitted res can't be from an EL, need to see >= 1 matches */
1268 dmx[cur][cp9->M] = imx[prv][cp9->M] + CP9TSC(cp9O_DI,cp9->M);
1269 /* A main difference between a Backward scanner and
1270 * regular Backward: a scanner can end at the END
1271 * state at any position, regular can only end at
1272 * the final position j0. */
1273 if(do_scan)
1274 {
1275 dmx[cur][cp9->M] =
1276 ILogsum(dmx[cur][cp9->M],
1277 (CP9TSC(cp9O_DM,cp9->M) + /* D_M<-E + (only in scanner) */
1278 0)); /* all parses end in E, 2^0 = 1.0;*/
1279 }
1280 for (k = cp9->M-1; k >= 1; k--)
1281 {
1282 mmx[cur][k] = -INFTY; /* need seq to get here, unless we come from E in a scanner (below) */
1283 imx[cur][k] = -INFTY; /* need seq to get here */
1284 elmx[cur][k]= -INFTY; /* first emitted res can't be from an EL, need to see >= 1 matches */
1285 dmx[cur][k] = ILogsum(ILogsum((mmx[prv][k+1] + CP9TSC(cp9O_DM,k)),
1286 (imx[prv][k] + CP9TSC(cp9O_DI,k))),
1287 (dmx[cur][k+1] + CP9TSC(cp9O_DD,k)));
1288 }
1289
1290 /* Case when k == 0 */
1291 /* imx[cur][0] is filled same as imx[cur][1..k] in the loop above */
1292 imx[cur][0] = -INFTY; /* need seq to get here */
1293 dmx[cur][0] = -INFTY; /* D_0 does not exist */
1294 elmx[cur][0] = -INFTY; /* EL_0 does not exist */
1295
1296 /*M_0 is the B state, it doesn't emit, and can be reached from any match via a begin transition */
1297 mmx[cur][0] = -INFTY;
1298 for (k = cp9->M; k >= 1; k--)
1299 mmx[cur][0] = ILogsum(mmx[cur][0], (mmx[prv][k] + CP9TSC(cp9O_BM,k)));
1300 mmx[cur][0] = ILogsum(mmx[cur][0], (imx[prv][0] + CP9TSC(cp9O_MI,0)));
1301 mmx[cur][0] = ILogsum(mmx[cur][0], (dmx[cur][1] + CP9TSC(cp9O_MD,0))); /* B->D_1 */
1302 /* No EL contribution here, can't go B->EL_* */
1303
1304 scA[ip] = mmx[cur][0]; /* all parses must start in M_0, the B state */
1305 fsc = Scorify(scA[ip]);
1306
1307 /* Update best_sc for special case of ip == 0, '* off-by-one *' explained above still applies */
1308 if(fsc > best_sc) { best_sc = fsc; best_pos= i+1; } /* *off-by-one* */
1309
1310 /* end of special case, ip == 0 */
1311 /**********************************************************************************/
1312 /* End of Backward recursion */
1313
1314 if(doing_align) { /* best_sc is the alignment score */
1315 best_sc = Scorify(scA[0]);
1316 best_pos = i0;
1317 }
1318 if(ret_sc != NULL) *ret_sc = best_sc;
1319 if(ret_maxres != NULL) *ret_maxres = best_pos;
1320 if(ret_psc != NULL) *ret_psc = scA;
1321 else free(scA);
1322 ESL_DPRINTF1(("#DEBUG: cp9_Backward() return score: %10.4f\n", best_sc));
1323
1324 return eslOK;
1325
1326 ERROR:
1327 ESL_FAIL(eslEMEM, errbuf, "Memory allocation error.");
1328 }
1329
1330 /* Function: cp9_CheckFB()
1331 *
1332 * Purpose: Debugging function to make sure CP9Forward() and
1333 * CP9Backward are working by checking:
1334 * For all positions i, and states k:
1335 * sum_k f[i][k] * b[i][k] = P(x|hmm)
1336 *
1337 * Args: fmx - forward dp matrix, already filled
1338 * bmx - backward dp matrix, already filled
1339 * hmm - the model
1340 * sc - P(x|hmm) the probability of the entire
1341 * seq given the model
1342 * i0 - start of target subsequence (often 1, beginning of dsq)
1343 * j0 - end of target subsequence (often L, end of dsq)
1344 * dsq - the digitized sequence
1345 *
1346 * Note about sequence position indexing: although this function
1347 * works on a subsequence from i0 to j0, fmx and bmx have offset indices,
1348 * from 1 to W, with W = j0-i0+1.
1349 *
1350 * Return: eslOK on success;
1351 * eslFAIL if any residue fails check
1352 */
1353 int
1354 cp9_CheckFB(CP9_MX *fmx, CP9_MX *bmx, CP9_t *hmm, char *errbuf, float sc, int i0, int j0, ESL_DSQ *dsq)
1355 {
1356 if(fmx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFB(), fmx is NULL.\n");
1357 if(bmx == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFB(), bmx is NULL.\n");
1358 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "cp9_CheckFB(), dsq is NULL.");
1359
1360 int k, i;
1361 float max_diff; /* maximum allowed difference between sc and
1362 * sum_k f[i][k] * b[i][k] for any i */
1363 float diff;
1364 int fb_sum;
1365 float fb_sc;
1366 int W; /* subsequence length */
1367 int ip; /* i': relative position in the subsequence */
1368 int to_add;
1369
1370 W = j0-i0+1; /* the length of the subsequence */
1371 max_diff = 0.1; /* tolerance, must be within .1 bits of original score */
1372
1373 /* In all possible paths through the model, each residue of the sequence must have
1374 * been emitted by exactly 1 insert, match or EL state. */
1375 for (ip = 1; ip <= W; ip++) {
1376 i = i0+ip-1; /* e.g. i is actual index in dsq, runs from i0 to j0 */
1377 fb_sum = -INFTY;
1378 for (k = 0; k <= hmm->M; k++) {
1379 if (fmx->mmx[ip][k] == -INFTY) to_add = -INFTY;
1380 else if(bmx->mmx[ip][k] == -INFTY) to_add = -INFTY;
1381 else {
1382 to_add = fmx->mmx[ip][k] + bmx->mmx[ip][k];
1383 if(k > 0) to_add -= hmm->msc[dsq[i]][k];
1384 }
1385 /* hmm->msc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx
1386 * unless, we're talking about M_0, the B state, it doesn't emit */
1387 fb_sum = ILogsum(fb_sum, to_add);
1388
1389 /*printf("fmx->mmx[ip:%d][k:%d]: %d\n", ip, k, fmx->mmx[ip][k]);
1390 printf("bmx->mmx[ip:%d][k:%d]: %d sum: %d\n", ip, k, (bmx->mmx[ip][k]-hmm->msc[dsq[i]][k]), fb_sum);
1391 */
1392 if (fmx->imx[ip][k] == -INFTY) to_add = -INFTY;
1393 else if(bmx->imx[ip][k] == -INFTY) to_add = -INFTY;
1394 else {
1395 to_add = fmx->imx[ip][k] + bmx->imx[ip][k];
1396 to_add -= hmm->isc[dsq[i]][k];
1397 }
1398 /*hmm->isc[dsq[i]][k] will have been counted in both fmx->mmx and bmx->mmx*/
1399 fb_sum = ILogsum(fb_sum, to_add);
1400
1401 /*printf("fmx->imx[ip:%d][k:%d]: %d\n", ip, k, fmx->imx[ip][k]);
1402 printf("bmx->imx[ip:%d][k:%d]: %d sum: %d\n", ip, k, (bmx->imx[ip][k]-hmm->isc[dsq[i]][k]), fb_sum);
1403 */
1404 if (fmx->elmx[ip][k] == -INFTY) to_add = -INFTY;
1405 else if(bmx->elmx[ip][k] == -INFTY) to_add = -INFTY;
1406 else {
1407 to_add = fmx->elmx[ip][k] + bmx->elmx[ip][k];
1408 /* EL emissions are by definition zero scoring */
1409 }
1410 fb_sum = ILogsum(fb_sum, to_add);
1411
1412 /*printf("fmx->elmx[ip:%d][k:%d]: %d\n", ip, k, fmx->elmx[ip][k]);
1413 printf("bmx->elmx[ip:%d][k:%d]: %d sum: %d\n", ip, k, bmx->elmx[ip][k], fb_sum);
1414 */
1415 }
1416 fb_sc = Scorify(fb_sum);
1417 diff = fabs(fb_sc - sc);
1418 if((fabs(diff) > max_diff))
1419 ESL_FAIL(eslFAIL, errbuf, "cp9_CheckFB(), residue at posn i:%d violates sum_k f[i][k]*b[i][k]=P(x|hmm), sum_k = %.4f bits (should be %.4f)\n", i, fb_sc, sc);
1420 }
1421 ESL_DPRINTF1(("#DEBUG: cp9_CheckFB() passed, Forward/Backward matrices pass check.\n"));
1422 return eslOK;
1423 }
1424
1425
1426 /*****************************************************************
1427 * Benchmark driver
1428 *****************************************************************/
1429 #ifdef IMPL_CP9_DP_BENCHMARK
1430 /* gcc -g -O2 -DHAVE_CONFIG_H -I../easel -c old_cp9_dp.c
1431 * gcc -o benchmark-cp9_dp -g -O2 -I. -L. -I../easel -L../easel -DIMPL_CP9_DP_BENCHMARK cp9_dp.c old_cp9_dp.o -linfernal -leasel -lm
1432 * ./benchmark-cp9_dp <cmfile>
1433 */
1434
1435 #include <esl_config.h>
1436 #include "config.h"
1437
1438 #include <stdio.h>
1439 #include <stdlib.h>
1440 #include <string.h>
1441 #include <time.h>
1442
1443 #include "easel.h"
1444 #include "esl_getopts.h"
1445 #include "esl_histogram.h"
1446 #include "esl_random.h"
1447 #include "esl_randomseq.h"
1448 #include "esl_sqio.h"
1449 #include "esl_stats.h"
1450 #include "esl_stopwatch.h"
1451 #include "esl_vectorops.h"
1452 #include "esl_wuss.h"
1453
1454 #include "infernal.h" /* function declarations */
1455
1456 #include "old_funcs.h" /* function declarations for 0.81 versions */
1457
1458
1459 static ESL_OPTIONS options[] = {
1460 /* name type default env range toggles reqs incomp help docgroup*/
1461 { "-h", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1462 { "-r", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "set random number seed randomly", 0 },
1463 { "-s", eslARG_INT, "33", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1464 { "-L", eslARG_INT, "500000", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
1465 { "-N", eslARG_INT, "1", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
1466 { "-f", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute optimized Forward scan implementation", 0 },
1467 { "-o", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute old (version 0.8) Forward scan implementation", 0},
1468 { "-w", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute slow Viterbi scan implementation", 0 },
1469 { "-z", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute slow Viterbi backward scan implementation", 0 },
1470 { "-g", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "configure HMM for glocal alignment [default: local]", 0 },
1471 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do alignment, don't scan", 0 },
1472 { "--noel", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "turn local ends off [default: on, unless -g]", 0 },
1473 { "--full", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "calculate full matrix, not just 2 rows", 0 },
1474 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1475 };
1476 static char usage[] = "[-options] <cmfile>";
1477 static char banner[] = "benchmark driver for the fast scanning CM plan 9 HMM Viterbi implementation";
1478
1479 int
1480 main(int argc, char **argv)
1481 {
1482 int status;
1483 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 1, argc, argv, banner, usage);
1484 CM_t *cm;
1485 ESL_STOPWATCH *w = esl_stopwatch_Create();
1486 ESL_RANDOMNESS *r = NULL;
1487 ESL_ALPHABET *abc = NULL;
1488 int L = esl_opt_GetInteger(go, "-L");
1489 int N = esl_opt_GetInteger(go, "-N");
1490 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
1491 int i;
1492 float sc;
1493 char *cmfile = esl_opt_GetArg(go, 1);
1494 CMFILE *cmfp; /* open input CM file stream */
1495 int do_scan;
1496 int do_align;
1497 int minL = 0;
1498 int be_safe;
1499 char errbuf[eslERRBUFSIZE];
1500
1501 if (esl_opt_GetBoolean(go, "-r")) r = esl_randomness_CreateTimeseeded();
1502 else r = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1503
1504 if ((cmfp = CMFileOpen(cmfile, NULL)) == NULL) cm_Fail("Failed to open covariance model save file %s\n", cmfile);
1505 if (!(CMFileRead(cmfp, &abc, &cm))) cm_Fail("Failed to read CM");
1506 CMFileClose(cmfp);
1507
1508 if(! esl_opt_GetBoolean(go, "-g")) {
1509 cm->config_opts |= CM_CONFIG_LOCAL;
1510 cm->config_opts |= CM_CONFIG_HMMLOCAL;
1511 }
1512 if(! esl_opt_GetBoolean(go, "--noel")) {
1513 cm->config_opts |= CM_CONFIG_LOCAL;
1514 cm->config_opts |= CM_CONFIG_HMMEL;
1515 }
1516 ConfigCM(cm, TRUE); /* TRUE says: calculate W */
1517 init_ilogsum();
1518
1519 if (esl_opt_GetBoolean(go, "-a")) { do_scan = FALSE; do_align = TRUE; }
1520 else { do_scan = TRUE; do_align = FALSE; }
1521
1522 for (i = 0; i < N; i++)
1523 {
1524 esl_rsq_xfIID(r, cm->null, abc->K, L, dsq);
1525
1526 esl_stopwatch_Start(w);
1527 if((status = cp9_Viterbi(cm->cp9, errbuf, cm->cp9_mx, dsq, 1, L,
1528 do_scan, /* are we scanning? */
1529 do_align, /* are we aligning? */
1530 (! esl_opt_GetBoolean(go, "--full")), /* memory efficient ? */
1531 NULL, /* don't want best score at each posn back */
1532 NULL, /* don't want the max scoring posn back */
1533 NULL, /* don't want traces back */
1534 &sc)) != eslOK) cm_Fail(errbuf);
1535 printf("%4d %-30s %10.4f bits ", (i+1), "cp9_Viterbi(): ", sc);
1536 esl_stopwatch_Stop(w);
1537 esl_stopwatch_Display(stdout, w, " CPU time: ");
1538
1539 if (esl_opt_GetBoolean(go, "-b"))
1540 {
1541 esl_stopwatch_Start(w);
1542 if((status = cp9_ViterbiBackward(cm->cp9, errbuf, cm->cp9_mx, dsq, 1, L,
1543 do_scan, /* are we scanning? */
1544 do_align, /* are we aligning? */
1545 (! esl_opt_GetBoolean(go, "--full")), /* memory efficient ? */
1546 NULL, /* don't want best score at each posn back */
1547 NULL, /* don't want the max scoring posn back */
1548 NULL, /* don't want traces back */
1549 &sc)) != eslOK) cm_Fail(errbuf);
1550 printf("%4d %-30s %10.4f bits ", (i+1), "cp9_ViterbiBackward(): ", sc);
1551 esl_stopwatch_Stop(w);
1552 esl_stopwatch_Display(stdout, w, " CPU time: ");
1553 }
1554
1555 if (esl_opt_GetBoolean(go, "-f"))
1556 {
1557 esl_stopwatch_Start(w);
1558 if((status = cp9_Forward(cm->cp9, errbuf, cm->cp9_mx, dsq, 1, L,
1559 do_scan, /* are we scanning? */
1560 do_align, /* are we aligning? */
1561 (! esl_opt_GetBoolean(go, "--full")), /* memory efficient ? */
1562 NULL, /* don't want best score at each posn back */
1563 NULL, /* don't want the max scoring posn back */
1564 &sc)) != eslOK) cm_Fail(errbuf);
1565 printf("%4d %-30s %10.4f bits ", (i+1), "cp9_Forward(): ", sc);
1566 esl_stopwatch_Stop(w);
1567 esl_stopwatch_Display(stdout, w, " CPU time: ");
1568 }
1569 }
1570 FreeCM(cm);
1571 free(dsq);
1572 esl_alphabet_Destroy(abc);
1573 esl_stopwatch_Destroy(w);
1574 esl_randomness_Destroy(r);
1575 esl_getopts_Destroy(go);
1576 return 0;
1577 }
1578 #endif /*IMPL_CP9_DP_BENCHMARK*/
1579
1580
1581 /*****************************************************************
1582 * Debugging program
1583 *****************************************************************/
1584 #ifdef DEBUG_CP9_DP
1585 /* gcc -o debug-cp9_dp -g -O2 -I. -L. -I../easel -L../easel -I../hmmer/src -L../hmmer/src -DDEBUG_CP9_DP cp9_dp.c -linfernal -lhmmer -leasel -lm
1586 * ./debug-cp9_dp <cmfile> <fafile>
1587 */
1588
1589 #include <esl_config.h>
1590 #include <p7_config.h>
1591 #include "config.h"
1592
1593 #include <stdio.h>
1594 #include <stdlib.h>
1595 #include <string.h>
1596 #include <time.h>
1597
1598 #include "easel.h"
1599 #include "esl_getopts.h"
1600 #include "esl_histogram.h"
1601 #include "esl_random.h"
1602 #include "esl_randomseq.h"
1603 #include "esl_sqio.h"
1604 #include "esl_stats.h"
1605 #include "esl_stopwatch.h"
1606 #include "esl_vectorops.h"
1607 #include "esl_wuss.h"
1608
1609 #include "infernal.h"
1610
1611 static ESL_OPTIONS options[] = {
1612 /* name type default env range toggles reqs incomp help docgroup*/
1613 { "-h", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1614 { "-r", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "set random number seed randomly", 0 },
1615 { "-s", eslARG_INT, "33", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1616 { "-L", eslARG_INT, "500000", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
1617 { "-N", eslARG_INT, "1", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
1618 { "-f", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "also execute optimized Forward scan implementation", 0 },
1619 { "-g", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "configure HMM for glocal alignment [default: local]", 0 },
1620 { "-a", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "do alignment, don't scan", 0 },
1621 { "--noel", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "turn local ends off [default: on, unless -g]", 0 },
1622 { "--full", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "calculate full matrix, not just 2 rows", 0 },
1623 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1624 };
1625 static char usage[] = "[-options] <cmfile>";
1626 static char banner[] = "benchmark driver for the fast scanning CM plan 9 HMM Viterbi implementation";
1627
1628 int
1629 main(int argc, char **argv)
1630 {
1631 int status;
1632 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 2, argc, argv, banner, usage);
1633 CM_t *cm;
1634 ESL_STOPWATCH *w = esl_stopwatch_Create();
1635 ESL_ALPHABET *abc = NULL;
1636 ESL_SQ *sq = NULL;
1637 float sc;
1638 char *cmfile = esl_opt_GetArg(go, 1);
1639 char *sqfile = esl_opt_GetArg(go, 2);
1640 CMFILE *cmfp; /* open input CM file stream */
1641 int do_scan;
1642 int do_align;
1643 char errbuf[eslERRBUFSIZE];
1644 ESL_SQFILE *sqfp; /* open sequence input file stream */
1645 int maxi, maxj, maxi2;
1646
1647 /* open input sequence file */
1648 status = esl_sqfile_Open(sqfile, eslSQFILE_UNKNOWN, NULL, &sqfp);
1649 if (status == eslENOTFOUND) ESL_FAIL(status, errbuf, "File %s doesn't exist or is not readable\n", sqfile);
1650 else if (status == eslEFORMAT) ESL_FAIL(status, errbuf, "Couldn't determine format of sequence file %s\n", sqfile);
1651 else if (status == eslEINVAL) ESL_FAIL(status, errbuf, "Can’t autodetect stdin or .gz.");
1652 else if (status != eslOK) ESL_FAIL(status, errbuf, "Sequence file open failed with error %d\n", status);
1653
1654 if ((cmfp = CMFileOpen(cmfile, NULL)) == NULL) cm_Fail("Failed to open covariance model save file %s\n", cmfile);
1655 if ((status = (CMFileRead(cmfp, NULL, &abc, &cm))) != eslOK) cm_Fail("Failed to read CM");
1656 CMFileClose(cmfp);
1657 esl_sqfile_SetDigital(sqfp, abc);
1658
1659 if(! esl_opt_GetBoolean(go, "-g")) {
1660 cm->config_opts |= CM_CONFIG_LOCAL;
1661 cm->config_opts |= CM_CONFIG_HMMLOCAL;
1662 if(! esl_opt_GetBoolean(go, "--noel")) {
1663 cm->config_opts |= CM_CONFIG_HMMEL;
1664 }
1665 }
1666 ConfigCM(cm, NULL, TRUE, NULL, NULL); /* TRUE says: calculate W */
1667 init_ilogsum();
1668
1669 if (esl_opt_GetBoolean(go, "-a")) { do_scan = FALSE; do_align = TRUE; }
1670 else { do_scan = TRUE; do_align = FALSE; }
1671
1672 sq = esl_sq_CreateDigital(abc);
1673 while((status = esl_sqio_Read(sqfp, sq)) == eslOK) {
1674 esl_stopwatch_Start(w);
1675 if((status = cp9_Viterbi(cm->cp9, errbuf, cm->cp9_mx, sq->dsq, 1, sq->n, cm->W, cm->W, 0., NULL,
1676 do_scan, /* are we scanning? */
1677 do_align, /* are we aligning? */
1678 (! esl_opt_GetBoolean(go, "--full")), /* memory efficient ? */
1679 FALSE, /* don't do NULL3 */
1680 NULL, /* don't want best score at each posn back */
1681 &maxj, /* return the max scoring end posn */
1682 NULL, /* don't want traces back */
1683 &sc)) != eslOK) cm_Fail(errbuf);
1684 printf("%-30s %10.4f bits endpoint: %4d", "cp9_Viterbi(): ", sc, maxj);
1685 esl_stopwatch_Stop(w);
1686 esl_stopwatch_Display(stdout, w, " CPU time: ");
1687
1688 esl_stopwatch_Start(w);
1689 if((status = cp9_ViterbiBackward(cm->cp9, errbuf, cm->cp9_mx, sq->dsq, 1,
1690 (do_align) ? sq->n : maxj,
1691 cm->W, cm->W, 0., NULL,
1692 do_scan, /* are we scanning? */
1693 do_align, /* are we aligning? */
1694 (! esl_opt_GetBoolean(go, "--full")), /* memory efficient ? */
1695 FALSE, /* don't do NULL3 */
1696 NULL, /* don't want best score at each posn back */
1697 &maxi, /* return the max scoring start posn */
1698 NULL, /* don't want traces back */
1699 &sc)) != eslOK) cm_Fail(errbuf);
1700 printf("%-30s %10.4f bits startpnt: %4d", "cp9_ViterbiBackward(): ", sc, maxi);
1701 esl_stopwatch_Stop(w);
1702 esl_stopwatch_Display(stdout, w, " CPU time: ");
1703
1704 esl_sq_Reuse(sq);
1705
1706 printf("\n");
1707 }
1708 FreeCM(cm);
1709 esl_sq_Destroy(sq);
1710 esl_alphabet_Destroy(abc);
1711 esl_stopwatch_Destroy(w);
1712 esl_getopts_Destroy(go);
1713 return 0;
1714 }
1715 #endif /*DEBUG_CP9_DP*/