Debian Codegraph @

hmmer/src/generic_fwdback.c

raw symbols SCIP
1 /* Forward/Backward algorithms; generic (non-SIMD) versions.
2 *
3 * Contents:
4 * 1. Forward, Backward, Hybrid implementations.
5 * 2. Benchmark driver.
6 * 3. Unit tests.
7 * 4. Test driver.
8 * 5. Example.
9 */
10 #include <p7_config.h>
11
12 #include "easel.h"
13 #include "esl_alphabet.h"
14
15 #include "hmmer.h"
16
17 /*****************************************************************
18 * 1. Forward, Backward, Hybrid implementations.
19 *****************************************************************/
20
21 /* Function: p7_GForward()
22 * Synopsis: The Forward algorithm.
23 *
24 * Purpose: The Forward dynamic programming algorithm.
25 *
26 * Given a digital sequence <dsq> of length <L>, a profile
27 * <gm>, and DP matrix <gx> allocated for at least <gm->M>
28 * by <L> cells; calculate the probability of the sequence
29 * given the model using the Forward algorithm; return the
30 * Forward matrix in <gx>, and the Forward score in <ret_sc>.
31 *
32 * The Forward score is in lod score form. To convert to a
33 * bitscore, the caller needs to subtract a null model lod
34 * score, then convert to bits.
35 *
36 * Caller must have initialized the log-sum calculation
37 * with a call to <p7_FLogsumInit()>.
38 *
39 * Args: dsq - sequence in digitized form, 1..L
40 * L - length of dsq
41 * gm - profile.
42 * gx - DP matrix with room for an MxL alignment
43 * opt_sc - optRETURN: Forward lod score in nats
44 *
45 * Return: <eslOK> on success.
46 */
47 int
48 p7_GForward(const ESL_DSQ *dsq, int L, const P7_PROFILE *gm, P7_GMX *gx, float *opt_sc)
49 {
50 float const *tsc = gm->tsc;
51 float **dp = gx->dp;
52 float *xmx = gx->xmx;
53 int M = gm->M;
54 int i, k;
55 float esc = p7_profile_IsLocal(gm) ? 0 : -eslINFINITY;
56
57 p7_FLogsumInit(); /* Would like to get rid of this -- have main()'s all initialize instead, more efficient */
58
59 /* Initialization of the zero row. */
60 XMX(0,p7G_N) = 0; /* S->N, p=1 */
61 XMX(0,p7G_B) = gm->xsc[p7P_N][p7P_MOVE]; /* S->N->B, no N-tail */
62 XMX(0,p7G_E) = XMX(0,p7G_C) = XMX(0,p7G_J) = -eslINFINITY; /* need seq to get here */
63 for (k = 0; k <= M; k++)
64 MMX(0,k) = IMX(0,k) = DMX(0,k) = -eslINFINITY; /* need seq to get here */
65
66 /* Recursion. Done as a pull.
67 * Note some slightly wasteful boundary conditions:
68 * tsc[0] = impossible for all eight transitions (no node 0)
69 * D_1 is wastefully calculated (doesn't exist)
70 */
71 for (i = 1; i <= L; i++)
72 {
73 float const *rsc = gm->rsc[dsq[i]];
74 float sc;
75
76 MMX(i,0) = IMX(i,0) = DMX(i,0) = -eslINFINITY;
77 XMX(i, p7G_E) = -eslINFINITY;
78
79 for (k = 1; k < M; k++)
80 {
81 /* match state */
82 sc = p7_FLogsum(p7_FLogsum(MMX(i-1,k-1) + TSC(p7P_MM,k-1),
83 IMX(i-1,k-1) + TSC(p7P_IM,k-1)),
84 p7_FLogsum(XMX(i-1,p7G_B) + TSC(p7P_BM,k-1),
85 DMX(i-1,k-1) + TSC(p7P_DM,k-1)));
86 MMX(i,k) = sc + MSC(k);
87
88 /* insert state */
89 sc = p7_FLogsum(MMX(i-1,k) + TSC(p7P_MI,k),
90 IMX(i-1,k) + TSC(p7P_II,k));
91 IMX(i,k) = sc + ISC(k);
92
93 /* delete state */
94 DMX(i,k) = p7_FLogsum(MMX(i,k-1) + TSC(p7P_MD,k-1),
95 DMX(i,k-1) + TSC(p7P_DD,k-1));
96
97 /* E state update */
98 XMX(i,p7G_E) = p7_FLogsum(p7_FLogsum(MMX(i,k) + esc,
99 DMX(i,k) + esc),
100 XMX(i,p7G_E));
101 }
102 /* unrolled match state M_M */
103 sc = p7_FLogsum(p7_FLogsum(MMX(i-1,M-1) + TSC(p7P_MM,M-1),
104 IMX(i-1,M-1) + TSC(p7P_IM,M-1)),
105 p7_FLogsum(XMX(i-1,p7G_B) + TSC(p7P_BM,M-1),
106 DMX(i-1,M-1) + TSC(p7P_DM,M-1)));
107 MMX(i,M) = sc + MSC(M);
108 IMX(i,M) = -eslINFINITY;
109
110 /* unrolled delete state D_M */
111 DMX(i,M) = p7_FLogsum(MMX(i,M-1) + TSC(p7P_MD,M-1),
112 DMX(i,M-1) + TSC(p7P_DD,M-1));
113
114 /* unrolled E state update */
115 XMX(i,p7G_E) = p7_FLogsum(p7_FLogsum(MMX(i,M),
116 DMX(i,M)),
117 XMX(i,p7G_E));
118
119 /* J state */
120 XMX(i,p7G_J) = p7_FLogsum(XMX(i-1,p7G_J) + gm->xsc[p7P_J][p7P_LOOP],
121 XMX(i, p7G_E) + gm->xsc[p7P_E][p7P_LOOP]);
122 /* C state */
123 XMX(i,p7G_C) = p7_FLogsum(XMX(i-1,p7G_C) + gm->xsc[p7P_C][p7P_LOOP],
124 XMX(i, p7G_E) + gm->xsc[p7P_E][p7P_MOVE]);
125 /* N state */
126 XMX(i,p7G_N) = XMX(i-1,p7G_N) + gm->xsc[p7P_N][p7P_LOOP];
127
128 /* B state */
129 XMX(i,p7G_B) = p7_FLogsum(XMX(i, p7G_N) + gm->xsc[p7P_N][p7P_MOVE],
130 XMX(i, p7G_J) + gm->xsc[p7P_J][p7P_MOVE]);
131 }
132
133 if (opt_sc != NULL) *opt_sc = XMX(L,p7G_C) + gm->xsc[p7P_C][p7P_MOVE];
134 gx->M = M;
135 gx->L = L;
136 return eslOK;
137 }
138
139
140 /* Function: p7_GBackward()
141 * Synopsis: The Backward algorithm.
142 *
143 * Purpose: The Backward dynamic programming algorithm.
144 *
145 * Given a digital sequence <dsq> of length <L>, a profile
146 * <gm>, and DP matrix <gx> allocated for at least <gm->M>
147 * by <L> cells; calculate the probability of the sequence
148 * given the model using the Backward algorithm; return the
149 * Backward matrix in <gx>, and the Backward score in <ret_sc>.
150 *
151 * The Backward score is in lod score form. To convert to a
152 * bitscore, the caller needs to subtract a null model lod
153 * score, then convert to bits.
154 *
155 * Args: dsq - sequence in digitized form, 1..L
156 * L - length of dsq
157 * gm - profile
158 * gx - DP matrix with room for an MxL alignment
159 * opt_sc - optRETURN: Backward lod score in nats
160 *
161 * Return: <eslOK> on success.
162 */
163 int
164 p7_GBackward(const ESL_DSQ *dsq, int L, const P7_PROFILE *gm, P7_GMX *gx, float *opt_sc)
165 {
166 float const *tsc = gm->tsc;
167 float const *rsc = NULL;
168 float **dp = gx->dp;
169 float *xmx = gx->xmx;
170 int M = gm->M;
171 int i, k;
172 float esc = p7_profile_IsLocal(gm) ? 0 : -eslINFINITY;
173
174 /* Note: backward calculates the probability we can get *out* of
175 * cell i,k; exclusive of emitting residue x_i.
176 */
177 p7_FLogsumInit();
178
179 /* Initialize the L row. */
180 XMX(L,p7G_J) = XMX(L,p7G_B) = XMX(L,p7G_N) = -eslINFINITY;
181 XMX(L,p7G_C) = gm->xsc[p7P_C][p7P_MOVE]; /* C<-T */
182 XMX(L,p7G_E) = XMX(L,p7G_C) + gm->xsc[p7P_E][p7P_MOVE]; /* E<-C, no tail */
183
184 MMX(L,M) = DMX(L,M) = XMX(L,p7G_E); /* {MD}_M <- E (prob 1.0) */
185 IMX(L,M) = -eslINFINITY; /* no I_M state */
186 for (k = M-1; k >= 1; k--) {
187 MMX(L,k) = p7_FLogsum( XMX(L,p7G_E) + esc,
188 DMX(L, k+1) + TSC(p7P_MD,k));
189 DMX(L,k) = p7_FLogsum( XMX(L,p7G_E) + esc,
190 DMX(L, k+1) + TSC(p7P_DD,k));
191 IMX(L,k) = -eslINFINITY;
192 }
193
194 /* Main recursion */
195 for (i = L-1; i >= 1; i--)
196 {
197 rsc = gm->rsc[dsq[i+1]];
198
199 XMX(i,p7G_B) = MMX(i+1,1) + TSC(p7P_BM,0) + MSC(1); /* t_BM index is 0 because it's stored off-by-one. */
200 for (k = 2; k <= M; k++)
201 XMX(i,p7G_B) = p7_FLogsum(XMX(i, p7G_B), MMX(i+1,k) + TSC(p7P_BM,k-1) + MSC(k));
202
203 XMX(i,p7G_J) = p7_FLogsum( XMX(i+1,p7G_J) + gm->xsc[p7P_J][p7P_LOOP],
204 XMX(i, p7G_B) + gm->xsc[p7P_J][p7P_MOVE]);
205
206 XMX(i,p7G_C) = XMX(i+1,p7G_C) + gm->xsc[p7P_C][p7P_LOOP];
207
208 XMX(i,p7G_E) = p7_FLogsum( XMX(i, p7G_J) + gm->xsc[p7P_E][p7P_LOOP],
209 XMX(i, p7G_C) + gm->xsc[p7P_E][p7P_MOVE]);
210
211 XMX(i,p7G_N) = p7_FLogsum( XMX(i+1,p7G_N) + gm->xsc[p7P_N][p7P_LOOP],
212 XMX(i, p7G_B) + gm->xsc[p7P_N][p7P_MOVE]);
213
214
215 MMX(i,M) = DMX(i,M) = XMX(i,p7G_E);
216 IMX(i,M) = -eslINFINITY;
217 for (k = M-1; k >= 1; k--)
218 {
219 MMX(i,k) = p7_FLogsum( p7_FLogsum(MMX(i+1,k+1) + TSC(p7P_MM,k) + MSC(k+1),
220 IMX(i+1,k) + TSC(p7P_MI,k) + ISC(k)),
221 p7_FLogsum(XMX(i,p7G_E) + esc,
222 DMX(i, k+1) + TSC(p7P_MD,k)));
223
224 IMX(i,k) = p7_FLogsum( MMX(i+1,k+1) + TSC(p7P_IM,k) + MSC(k+1),
225 IMX(i+1,k) + TSC(p7P_II,k) + ISC(k));
226
227 DMX(i,k) = p7_FLogsum( MMX(i+1,k+1) + TSC(p7P_DM,k) + MSC(k+1),
228 p7_FLogsum( DMX(i, k+1) + TSC(p7P_DD,k),
229 XMX(i, p7G_E) + esc));
230 }
231 }
232
233 /* At i=0, only N,B states are reachable. */
234 rsc = gm->rsc[dsq[1]];
235 XMX(0,p7G_B) = MMX(1,1) + TSC(p7P_BM,0) + MSC(1); /* t_BM index is 0 because it's stored off-by-one. */
236 for (k = 2; k <= M; k++)
237 XMX(0,p7G_B) = p7_FLogsum(XMX(0, p7G_B), MMX(1,k) + TSC(p7P_BM,k-1) + MSC(k));
238 XMX(i,p7G_J) = -eslINFINITY;
239 XMX(i,p7G_C) = -eslINFINITY;
240 XMX(i,p7G_E) = -eslINFINITY;
241 XMX(i,p7G_N) = p7_FLogsum( XMX(1, p7G_N) + gm->xsc[p7P_N][p7P_LOOP],
242 XMX(0, p7G_B) + gm->xsc[p7P_N][p7P_MOVE]);
243 for (k = M; k >= 1; k--)
244 MMX(i,k) = IMX(i,k) = DMX(i,k) = -eslINFINITY;
245
246
247 if (opt_sc != NULL) *opt_sc = XMX(0,p7G_N);
248 gx->M = M;
249 gx->L = L;
250 return eslOK;
251 }
252
253
254
255 /* Function: p7_GHybrid()
256 * Synopsis: The "hybrid" algorithm.
257 *
258 * Purpose: The profile HMM version of the Hwa "hybrid" alignment
259 * algorithm \citep{YuHwa02}. The "hybrid" score is the
260 * maximum score in the Forward matrix.
261 *
262 * Given a digital sequence <dsq> of length <L>, a profile
263 * <gm>, and DP matrix <mx> allocated for at least <gm->M>
264 * by <L> cells; calculate the probability of the sequence
265 * given the model using the Forward algorithm; return
266 * the calculated Forward matrix in <mx>, and optionally
267 * return the Forward score in <opt_fwdscore> and/or the
268 * Hybrid score in <opt_hybscore>.
269 *
270 * This is implemented as a wrapper around <p7_GForward()>.
271 * The Forward matrix and the Forward score obtained from
272 * this routine are identical to what <p7_GForward()> would
273 * return.
274 *
275 * The scores are returned in lod form. To convert to a
276 * bitscore, the caller needs to subtract a null model lod
277 * score, then convert to bits.
278 *
279 * Args: dsq - sequence in digitized form, 1..L
280 * L - length of dsq
281 * gm - profile.
282 * gx - DP matrix with room for an MxL alignment
283 * opt_fwdscore - optRETURN: Forward lod score in nats.
284 * opt_hybscore - optRETURN: Hybrid lod score in nats.
285 *
286 * Returns: <eslOK> on success, and results are in <mx>, <opt_fwdscore>,
287 * and <opt_hybscore>.
288 */
289 int
290 p7_GHybrid(const ESL_DSQ *dsq, int L, const P7_PROFILE *gm, P7_GMX *gx, float *opt_fwdscore, float *opt_hybscore)
291 {
292 float F = -eslINFINITY;
293 float H = -eslINFINITY;
294 float **dp = gx->dp;
295 int i,k;
296 int status;
297
298 if ((status = p7_GForward(dsq, L, gm, gx, &F)) != eslOK) goto ERROR;
299 for (i = 1; i <= L; i++)
300 for (k = 1 ; k <= gm->M; k++)
301 H = ESL_MAX(H, MMX(i,k));
302
303 gx->M = gm->M;
304 gx->L = L;
305 if (opt_fwdscore != NULL) *opt_fwdscore = F;
306 if (opt_hybscore != NULL) *opt_hybscore = H;
307 return eslOK;
308
309 ERROR:
310 if (opt_fwdscore != NULL) *opt_fwdscore = 0;
311 if (opt_hybscore != NULL) *opt_hybscore = 0;
312 return status;
313 }
314 /*------------- end: forward, backward, hybrid ------------------*/
315
316
317
318
319 /*****************************************************************
320 * 2. Benchmark driver.
321 *****************************************************************/
322 #ifdef p7GENERIC_FWDBACK_BENCHMARK
323 /*
324 gcc -g -O2 -o generic_fwdback_benchmark -I. -L. -I../easel -L../easel -Dp7GENERIC_FWDBACK_BENCHMARK generic_fwdback.c -lhmmer -leasel -lm
325 icc -O3 -static -o generic_fwdback_benchmark -I. -L. -I../easel -L../easel -Dp7GENERIC_FWDBACK_BENCHMARK generic_fwdback.c -lhmmer -leasel -lm
326 ./generic_fwdback_benchmark <hmmfile>
327 */
328 /* As of Fri Dec 28 14:48:39 2007
329 * Viterbi = 61.8 Mc/s
330 * Forward = 8.6 Mc/s
331 * Backward = 7.1 Mc/s
332 * MSV = 55.9 Mc/s
333 * (gcc -g -O2, 3.2GHz Xeon, N=50K, L=400, M=72 RRM_1 model)
334 */
335 #include <p7_config.h>
336
337 #include "easel.h"
338 #include "esl_alphabet.h"
339 #include "esl_getopts.h"
340 #include "esl_random.h"
341 #include "esl_randomseq.h"
342 #include "esl_stopwatch.h"
343
344 #include "hmmer.h"
345
346 static ESL_OPTIONS options[] = {
347 /* name type default env range toggles reqs incomp help docgroup*/
348 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
349 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
350 { "-L", eslARG_INT, "400", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
351 { "-N", eslARG_INT, "2000", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
352 { "-B", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "only benchmark GBackward()", 0 },
353 { "-F", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "only benchmark GForward()", 0 },
354 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
355 };
356 static char usage[] = "[-options] <hmmfile>";
357 static char banner[] = "benchmark driver for generic Forward/Backward";
358
359 int
360 main(int argc, char **argv)
361 {
362 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
363 char *hmmfile = esl_opt_GetArg(go, 1);
364 ESL_STOPWATCH *w = esl_stopwatch_Create();
365 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
366 ESL_ALPHABET *abc = NULL;
367 P7_HMMFILE *hfp = NULL;
368 P7_HMM *hmm = NULL;
369 P7_BG *bg = NULL;
370 P7_PROFILE *gm = NULL;
371 P7_GMX *fwd = NULL;
372 P7_GMX *bck = NULL;
373 int L = esl_opt_GetInteger(go, "-L");
374 int N = esl_opt_GetInteger(go, "-N");
375 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
376 int i;
377 float sc;
378 double base_time, bench_time, Mcs;
379
380 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
381 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
382
383 bg = p7_bg_Create(abc);
384 p7_bg_SetLength(bg, L);
385 gm = p7_profile_Create(hmm->M, abc);
386 p7_ProfileConfig(hmm, bg, gm, L, p7_UNILOCAL);
387 fwd = p7_gmx_Create(gm->M, L);
388 bck = p7_gmx_Create(gm->M, L);
389
390 /* Baseline time. */
391 esl_stopwatch_Start(w);
392 for (i = 0; i < N; i++) esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
393 esl_stopwatch_Stop(w);
394 base_time = w->user;
395
396 /* Benchmark time. */
397 esl_stopwatch_Start(w);
398 for (i = 0; i < N; i++)
399 {
400 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
401 if (! esl_opt_GetBoolean(go, "-B")) p7_GForward (dsq, L, gm, fwd, &sc);
402 if (! esl_opt_GetBoolean(go, "-F")) p7_GBackward(dsq, L, gm, bck, NULL);
403
404 p7_gmx_Reuse(fwd);
405 p7_gmx_Reuse(bck);
406 }
407 esl_stopwatch_Stop(w);
408 bench_time = w->user - base_time;
409 Mcs = (double) N * (double) L * (double) gm->M * 1e-6 / (double) bench_time;
410 esl_stopwatch_Display(stdout, w, "# CPU time: ");
411 printf("# M = %d\n", gm->M);
412 printf("# %.1f Mc/s\n", Mcs);
413
414 free(dsq);
415 p7_gmx_Destroy(bck);
416 p7_gmx_Destroy(fwd);
417 p7_profile_Destroy(gm);
418 p7_bg_Destroy(bg);
419 p7_hmm_Destroy(hmm);
420 p7_hmmfile_Close(hfp);
421 esl_alphabet_Destroy(abc);
422 esl_stopwatch_Destroy(w);
423 esl_randomness_Destroy(r);
424 esl_getopts_Destroy(go);
425 return 0;
426 }
427 #endif /*p7GENERIC_FWDBACK_BENCHMARK*/
428 /*----------------- end, benchmark ------------------------------*/
429
430
431
432
433 /*****************************************************************
434 * 3. Unit tests
435 *****************************************************************/
436 #ifdef p7GENERIC_FWDBACK_TESTDRIVE
437 #include <string.h>
438 #include "esl_getopts.h"
439 #include "esl_random.h"
440 #include "esl_randomseq.h"
441
442 /* Forward is hard to validate.
443 * We do know that the Forward score is >= Viterbi.
444 * We also know that the expected score on random seqs is <= 0 (not
445 * exactly - we'd have to sample the random length from the background
446 * model too, not just use a fixed L - but it's close enough to
447 * being true to be a useful test.)
448 */
449 static void
450 utest_forward(ESL_GETOPTS *go, ESL_RANDOMNESS *r, ESL_ALPHABET *abc, P7_BG *bg, P7_PROFILE *gm, int nseq, int L)
451 {
452 float avg_sc;
453 ESL_DSQ *dsq = NULL;
454 P7_GMX *fwd = NULL;
455 P7_GMX *bck = NULL;
456 int idx;
457 float fsc, bsc;
458 float vsc, nullsc;
459
460 if ((dsq = malloc(sizeof(ESL_DSQ) *(L+2))) == NULL) esl_fatal("malloc failed");
461 if ((fwd = p7_gmx_Create(gm->M, L)) == NULL) esl_fatal("matrix creation failed");
462 if ((bck = p7_gmx_Create(gm->M, L)) == NULL) esl_fatal("matrix creation failed");
463
464 avg_sc = 0.;
465 for (idx = 0; idx < nseq; idx++)
466 {
467 if (esl_rsq_xfIID(r, bg->f, abc->K, L, dsq) != eslOK) esl_fatal("seq generation failed");
468 if (p7_GViterbi(dsq, L, gm, fwd, &vsc) != eslOK) esl_fatal("viterbi failed");
469 if (p7_GForward(dsq, L, gm, fwd, &fsc) != eslOK) esl_fatal("forward failed");
470 if (p7_GBackward(dsq, L, gm, bck, &bsc) != eslOK) esl_fatal("backward failed");
471
472 if (fsc < vsc) esl_fatal("Forward score can't be less than Viterbi score");
473 if (fabs(fsc-bsc) > 0.001) esl_fatal("Forward/Backward failed: %f %f\n", fsc, bsc);
474
475 if (p7_bg_NullOne(bg, dsq, L, &nullsc) != eslOK) esl_fatal("null score failed");
476
477 avg_sc += fsc - nullsc;
478
479 if (esl_opt_GetBoolean(go, "--vv"))
480 printf("utest_forward: Forward score: %.4f (total so far: %.4f)\n", fsc, avg_sc);
481 }
482
483 avg_sc /= (float) nseq;
484 if (avg_sc > 0.) esl_fatal("Forward scores have positive expectation (%f nats)", avg_sc);
485
486 p7_gmx_Destroy(fwd);
487 p7_gmx_Destroy(bck);
488 free(dsq);
489 return;
490 }
491
492 /* The "generation" test scores sequences generated by the same profile.
493 * Each Viterbi and Forward score should be >= the trace score of the emitted seq.
494 * The expectation of Forward scores should be positive.
495 */
496 static void
497 utest_generation(ESL_GETOPTS *go, ESL_RANDOMNESS *r, ESL_ALPHABET *abc,
498 P7_PROFILE *gm, P7_HMM *hmm, P7_BG *bg, int nseq)
499 {
500 ESL_SQ *sq = esl_sq_CreateDigital(abc);
501 P7_GMX *gx = p7_gmx_Create(gm->M, 100);
502 P7_TRACE *tr = p7_trace_Create();
503 float vsc, fsc, nullsc, tracesc;
504 float avg_fsc;
505 int idx;
506
507 avg_fsc = 0.0;
508 for (idx = 0; idx < nseq; idx++)
509 {
510 if (p7_ProfileEmit(r, hmm, gm, bg, sq, tr) != eslOK) esl_fatal("profile emission failed");
511
512 if (p7_gmx_GrowTo(gx, gm->M, sq->n) != eslOK) esl_fatal("failed to reallocate gmx");
513 if (p7_GViterbi(sq->dsq, sq->n, gm, gx, &vsc) != eslOK) esl_fatal("viterbi failed");
514 if (p7_GForward(sq->dsq, sq->n, gm, gx, &fsc) != eslOK) esl_fatal("forward failed");
515 if (p7_trace_Score(tr, sq->dsq, gm, &tracesc) != eslOK) esl_fatal("trace score failed");
516 if (p7_bg_NullOne(bg, sq->dsq, sq->n, &nullsc) != eslOK) esl_fatal("null score failed");
517
518 if (vsc < tracesc) esl_fatal("viterbi score is less than trace");
519 if (fsc < tracesc) esl_fatal("forward score is less than trace");
520 if (vsc > fsc) esl_fatal("viterbi score is greater than forward");
521
522 if (esl_opt_GetBoolean(go, "--vv"))
523 printf("generated: len=%d v=%8.4f f=%8.4f t=%8.4f\n", (int) sq->n, vsc, fsc, tracesc);
524
525 avg_fsc += (fsc - nullsc);
526 }
527
528 avg_fsc /= (float) nseq;
529 if (avg_fsc < 0.) esl_fatal("generation: Forward scores have negative expectation (%f nats)", avg_fsc);
530
531 p7_gmx_Destroy(gx);
532 p7_trace_Destroy(tr);
533 esl_sq_Destroy(sq);
534 }
535
536
537 /* The "enumeration" test samples a random enumerable HMM (transitions to insert are 0,
538 * so the generated seq space only includes seqs of L<=M).
539 *
540 * The test scores all seqs of length <=M by both Viterbi and Forward, verifies that
541 * the two scores are identical, and verifies that the sum of all the probabilities is
542 * 1.0. It also verifies that the score of a sequence of length M+1 is indeed -infinity.
543 *
544 * Because this function is going to work in unscaled probabilities, adding them up,
545 * all P(seq) terms must be >> DBL_EPSILON. That means M must be small; on the order
546 * of <= 10.
547 */
548 static void
549 utest_enumeration(ESL_GETOPTS *go, ESL_RANDOMNESS *r, ESL_ALPHABET *abc, int M)
550 {
551 char errbuf[eslERRBUFSIZE];
552 P7_HMM *hmm = NULL;
553 P7_PROFILE *gm = NULL;
554 P7_BG *bg = NULL;
555 ESL_DSQ *dsq = NULL;
556 P7_GMX *gx = NULL;
557 float vsc, fsc;
558 float bg_ll; /* log P(seq | bg) */
559 double fp; /* P(seq | model) */
560 int L;
561 int i;
562 double total_p;
563 char *seq;
564
565 /* Sample an enumerable HMM & profile of length M. */
566 if (p7_hmm_SampleEnumerable(r, M, abc, &hmm) != eslOK) esl_fatal("failed to sample an enumerable HMM");
567 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
568 if ((gm = p7_profile_Create(hmm->M, abc)) == NULL) esl_fatal("failed to create profile");
569 if (p7_ProfileConfig(hmm, bg, gm, 0, p7_UNILOCAL) != eslOK) esl_fatal("failed to config profile");
570 if (p7_hmm_Validate (hmm, errbuf, 0.0001) != eslOK) esl_fatal("whoops, HMM is bad!: %s", errbuf);
571 if (p7_profile_Validate(gm, errbuf, 0.0001) != eslOK) esl_fatal("whoops, profile is bad!: %s", errbuf);
572
573 if ( (dsq = malloc(sizeof(ESL_DSQ) * (M+3))) == NULL) esl_fatal("allocation failed");
574 if ( (seq = malloc(sizeof(char) * (M+2))) == NULL) esl_fatal("allocation failed");
575 if ((gx = p7_gmx_Create(hmm->M, M+3)) == NULL) esl_fatal("matrix creation failed");
576
577 /* Enumerate all sequences of length L <= M
578 */
579 total_p = 0;
580 for (L = 0; L <= M; L++)
581 {
582 /* Initialize dsq of length L at 0000... */
583 dsq[0] = dsq[L+1] = eslDSQ_SENTINEL;
584 for (i = 1; i <= L; i++) dsq[i] = 0;
585
586 while (1) /* enumeration of seqs of length L*/
587 {
588 if (p7_GViterbi(dsq, L, gm, gx, &vsc) != eslOK) esl_fatal("viterbi failed");
589 if (p7_GForward(dsq, L, gm, gx, &fsc) != eslOK) esl_fatal("forward failed");
590
591 /* calculate bg log likelihood component of the scores */
592 for (bg_ll = 0., i = 1; i <= L; i++) bg_ll += log(bg->f[dsq[i]]);
593
594 /* convert to probability, adding the bg LL back to the LLR */
595 fp = exp(fsc + bg_ll);
596
597 if (esl_opt_GetBoolean(go, "--vv")) {
598 esl_abc_Textize(abc, dsq, L, seq);
599 printf("probability of sequence: %10s %16g (lod v=%8.4f f=%8.4f)\n", seq, fp, vsc, fsc);
600 }
601 total_p += fp;
602
603 /* Increment dsq like a reversed odometer */
604 for (i = 1; i <= L; i++)
605 if (dsq[i] < abc->K-1) { dsq[i]++; break; } else { dsq[i] = 0; }
606 if (i > L) break; /* we're done enumerating sequences */
607 }
608 }
609
610 /* That sum is subject to significant numerical error because of
611 * discretization error in FLogsum(); don't expect it to be too close.
612 */
613 if (total_p < 0.999 || total_p > 1.001) esl_fatal("Enumeration unit test failed: total Forward p isn't near 1.0 (%g)", total_p);
614 if (esl_opt_GetBoolean(go, "-v")) {
615 printf("enumeration test: total p is %g\n", total_p);
616 }
617
618 p7_gmx_Destroy(gx);
619 p7_bg_Destroy(bg);
620 p7_profile_Destroy(gm);
621 p7_hmm_Destroy(hmm);
622 free(dsq);
623 free(seq);
624 }
625 #endif /*p7GENERIC_FWDBACK_TESTDRIVE*/
626 /*------------------------- end, unit tests ---------------------*/
627
628 /*****************************************************************
629 * 4. Test driver.
630 *****************************************************************/
631
632 /* gcc -g -Wall -Dp7GENERIC_FWDBACK_TESTDRIVE -I. -I../easel -L. -L../easel -o generic_fwdback_utest generic_fwdback.c -lhmmer -leasel -lm
633 */
634 #ifdef p7GENERIC_FWDBACK_TESTDRIVE
635 #include "easel.h"
636 #include "esl_getopts.h"
637 #include "esl_msa.h"
638
639 #include <p7_config.h>
640 #include "hmmer.h"
641
642 static ESL_OPTIONS options[] = {
643 /* name type default env range toggles reqs incomp help docgroup*/
644 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
645 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
646 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose", 0 },
647 { "--vv", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be very verbose", 0 },
648 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
649 };
650 static char usage[] = "[-options]";
651 static char banner[] = "unit test driver for the generic Forward/Backward implementation";
652
653 int
654 main(int argc, char **argv)
655 {
656 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
657 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
658 ESL_ALPHABET *abc = NULL;
659 P7_HMM *hmm = NULL;
660 P7_PROFILE *gm = NULL;
661 P7_BG *bg = NULL;
662 int M = 100;
663 int L = 200;
664 int nseq = 20;
665 char errbuf[eslERRBUFSIZE];
666
667 p7_FLogsumInit();
668
669 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal("failed to create alphabet");
670 if (p7_hmm_Sample(r, M, abc, &hmm) != eslOK) esl_fatal("failed to sample an HMM");
671 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
672 if ((gm = p7_profile_Create(hmm->M, abc)) == NULL) esl_fatal("failed to create profile");
673 if (p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL) != eslOK) esl_fatal("failed to config profile");
674 if (p7_hmm_Validate (hmm, errbuf, 0.0001) != eslOK) esl_fatal("whoops, HMM is bad!: %s", errbuf);
675 if (p7_profile_Validate(gm, errbuf, 0.0001) != eslOK) esl_fatal("whoops, profile is bad!: %s", errbuf);
676
677 utest_forward (go, r, abc, bg, gm, nseq, L);
678 utest_generation (go, r, abc, gm, hmm, bg, nseq);
679 utest_enumeration(go, r, abc, 4); /* can't go much higher than 5; enumeration test is cpu-intensive. */
680
681 p7_profile_Destroy(gm);
682 p7_bg_Destroy(bg);
683 p7_hmm_Destroy(hmm);
684 esl_alphabet_Destroy(abc);
685 esl_randomness_Destroy(r);
686 esl_getopts_Destroy(go);
687 return 0;
688 }
689 #endif /*p7GENERIC_FWDBACK_TESTDRIVE*/
690 /*-------------------- end, test driver -------------------------*/
691
692
693 /*****************************************************************
694 * 5. Example
695 *****************************************************************/
696 #ifdef p7GENERIC_FWDBACK_EXAMPLE
697 /*
698 gcc -g -O2 -o generic_fwdback_example -Dp7GENERIC_FWDBACK_EXAMPLE -I. -I../easel -L. -L../easel generic_fwdback.c -lhmmer -leasel -lm
699 */
700 #include <p7_config.h>
701
702 #include "easel.h"
703 #include "esl_alphabet.h"
704 #include "esl_getopts.h"
705 #include "esl_sq.h"
706 #include "esl_sqio.h"
707
708 #include "hmmer.h"
709
710 #define STYLES "--fs,--sw,--ls,--s" /* Exclusive choice for alignment mode */
711
712 static ESL_OPTIONS options[] = {
713 /* name type default env range toggles reqs incomp help docgroup*/
714 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
715 { "--fs", eslARG_NONE,"default",NULL, NULL, STYLES, NULL, NULL, "multihit local alignment", 0 },
716 { "--sw", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "unihit local alignment", 0 },
717 { "--ls", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "multihit glocal alignment", 0 },
718 { "--s", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "unihit glocal alignment", 0 },
719 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
720 };
721 static char usage[] = "[-options] <hmmfile> <seqfile>";
722 static char banner[] = "example of Forward/Backward, generic implementation";
723
724 int
725 main(int argc, char **argv)
726 {
727 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 2, argc, argv, banner, usage);
728 char *hmmfile = esl_opt_GetArg(go, 1);
729 char *seqfile = esl_opt_GetArg(go, 2);
730 ESL_ALPHABET *abc = NULL;
731 P7_HMMFILE *hfp = NULL;
732 P7_HMM *hmm = NULL;
733 P7_BG *bg = NULL;
734 P7_PROFILE *gm = NULL;
735 P7_GMX *fwd = NULL;
736 P7_GMX *bck = NULL;
737 ESL_SQ *sq = NULL;
738 ESL_SQFILE *sqfp = NULL;
739 int format = eslSQFILE_UNKNOWN;
740 float fsc, bsc;
741 float nullsc;
742 int status;
743
744 /* Initialize log-sum calculator */
745 p7_FLogsumInit();
746
747 /* Read in one HMM */
748 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
749 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
750 p7_hmmfile_Close(hfp);
751
752 /* Read in one sequence */
753 sq = esl_sq_CreateDigital(abc);
754 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
755 if (status == eslENOTFOUND) p7_Fail("No such file.");
756 else if (status == eslEFORMAT) p7_Fail("Format unrecognized.");
757 else if (status == eslEINVAL) p7_Fail("Can't autodetect stdin or .gz.");
758 else if (status != eslOK) p7_Fail("Open failed, code %d.", status);
759
760 /* Configure a profile from the HMM */
761 bg = p7_bg_Create(abc);
762 gm = p7_profile_Create(hmm->M, abc);
763
764 /* Now reconfig the models however we were asked to */
765 if (esl_opt_GetBoolean(go, "--fs")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_LOCAL);
766 else if (esl_opt_GetBoolean(go, "--sw")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_UNILOCAL);
767 else if (esl_opt_GetBoolean(go, "--ls")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_GLOCAL);
768 else if (esl_opt_GetBoolean(go, "--s")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_UNIGLOCAL);
769
770 /* Allocate matrices */
771 fwd = p7_gmx_Create(gm->M, sq->n);
772 bck = p7_gmx_Create(gm->M, sq->n);
773
774 printf("%-30s %-10s %-10s %-10s %-10s\n", "# seq name", "fwd (raw)", "bck (raw) ", "fwd (bits)", "bck (bits)");
775 printf("%-30s %10s %10s %10s %10s\n", "#--------------", "----------", "----------", "----------", "----------");
776
777 while ( (status = esl_sqio_Read(sqfp, sq)) != eslEOF)
778 {
779 if (status == eslEFORMAT) p7_Fail("Parse failed (sequence file %s)\n%s\n", sqfp->filename, sqfp->get_error(sqfp));
780 else if (status != eslOK) p7_Fail("Unexpected error %d reading sequence file %s", status, sqfp->filename);
781
782 /* Resize the DP matrices if necessary */
783 p7_gmx_GrowTo(fwd, gm->M, sq->n);
784 p7_gmx_GrowTo(bck, gm->M, sq->n);
785
786 /* Set the profile and null model's target length models */
787 p7_bg_SetLength(bg, sq->n);
788 p7_ReconfigLength(gm, sq->n);
789
790 /* Run Forward, Backward */
791 p7_GForward (sq->dsq, sq->n, gm, fwd, &fsc);
792 p7_GBackward(sq->dsq, sq->n, gm, bck, &bsc);
793
794 p7_gmx_Dump(stdout, fwd, p7_DEFAULT);
795
796 /* Those scores are partial log-odds likelihoods in nats.
797 * Subtract off the rest of the null model, convert to bits.
798 */
799 p7_bg_NullOne(bg, sq->dsq, sq->n, &nullsc);
800
801 printf("%-30s %10.4f %10.4f %10.4f %10.4f\n",
802 sq->name,
803 fsc, bsc,
804 (fsc - nullsc) / eslCONST_LOG2, (bsc - nullsc) / eslCONST_LOG2);
805
806 p7_gmx_Reuse(fwd);
807 p7_gmx_Reuse(bck);
808 esl_sq_Reuse(sq);
809 }
810
811 /* Cleanup */
812 esl_sqfile_Close(sqfp);
813 esl_sq_Destroy(sq);
814 p7_gmx_Destroy(fwd);
815 p7_gmx_Destroy(bck);
816 p7_profile_Destroy(gm);
817 p7_bg_Destroy(bg);
818 p7_hmm_Destroy(hmm);
819 esl_alphabet_Destroy(abc);
820 esl_getopts_Destroy(go);
821 return 0;
822 }
823 #endif /*p7GENERIC_FWDBACK_EXAMPLE*/
824 /*-------------------- end, example -----------------------------*/
825
826