Debian Codegraph @

hmmer/src/impl_sse/fwdback.c

raw symbols SCIP
1 /* SSE implementation of Forward and Backward algorithms.
2 *
3 * Both profile and DP matrix are striped and interleaved, for fast
4 * SIMD vector operations. Calculations are in probability space
5 * (scaled odds ratios, actually) rather than log probabilities,
6 * allowing fast multiply/add operations rather than slow Logsum()
7 * calculations. Sparse rescaling is used to achieve full dynamic
8 * range of scores.
9 *
10 * The Forward and Backward implementations may be used either in a
11 * full O(ML) mode that keeps an entire DP matrix, or in a O(M+L)
12 * linear memory "parsing" mode that only keeps one row of memory for
13 * the main MDI states and one column 0..L for the special states
14 * B,E,N,C,J. Keeping a full matrix allows subsequent stochastic
15 * traceback or posterior decoding of any state. In parsing mode, we
16 * can do posterior decoding on the special states and determine
17 * regions of the target sequence that are generated by the
18 * nonhomology states (NCJ) versus not -- thus, identifying where
19 * high-probability "regions" are, the first step of identifying the
20 * domain structure of a target sequence.
21 *
22 * Contents:
23 * 1. Forward/Backward wrapper API
24 * 2. Forward and Backward engine implementations
25 * 4. Benchmark driver.
26 * 5. Unit tests.
27 * 6. Test driver.
28 * 7. Example.
29 *
30 * SRE, Thu Jul 31 08:43:20 2008 [Janelia]
31 */
32 #include <p7_config.h>
33
34 #include <stdio.h>
35 #include <math.h>
36
37 #include <xmmintrin.h> /* SSE */
38 #include <emmintrin.h> /* SSE2 */
39
40 #include "easel.h"
41 #include "esl_sse.h"
42
43 #include "hmmer.h"
44 #include "impl_sse.h"
45
46 static int forward_engine (int do_full, const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *fwd, float *opt_sc);
47 static int backward_engine(int do_full, const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, const P7_OMX *fwd, P7_OMX *bck, float *opt_sc);
48
49
50 /*****************************************************************
51 * 1. Forward/Backward API.
52 *****************************************************************/
53
54 /* Function: p7_Forward()
55 * Synopsis: The Forward algorithm, full matrix fill version.
56 * Incept: SRE, Fri Aug 15 18:59:43 2008 [Casa de Gatos]
57 *
58 * Purpose: Calculates the Forward algorithm for sequence <dsq> of
59 * length <L> residues, using optimized profile <om>, and a
60 * preallocated DP matrix <ox>. Upon successful return, <ox>
61 * contains the filled Forward matrix, and <*opt_sc>
62 * optionally contains the raw Forward score in nats.
63 *
64 * This calculation requires $O(ML)$ memory and time.
65 * The caller must provide a suitably allocated full <ox>
66 * by calling <ox = p7_omx_Create(M, L, L)> or
67 * <p7_omx_GrowTo(ox, M, L, L)>.
68 *
69 * The model <om> must be configured in local alignment
70 * mode. The sparse rescaling method used to keep
71 * probability values within single-precision floating
72 * point dynamic range cannot be safely applied to models in
73 * glocal or global mode.
74 *
75 * Args: dsq - digital target sequence, 1..L
76 * L - length of dsq in residues
77 * om - optimized profile
78 * ox - RETURN: Forward DP matrix
79 * opt_sc - RETURN: Forward score (in nats)
80 *
81 * Returns: <eslOK> on success.
82 *
83 * Throws: <eslEINVAL> if <ox> allocation is too small, or if the profile
84 * isn't in local alignment mode.
85 * <eslERANGE> if the score exceeds the limited range of
86 * a probability-space odds ratio.
87 * In either case, <*opt_sc> is undefined.
88 */
89 int
90 p7_Forward(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox, float *opt_sc)
91 {
92 #if eslDEBUGLEVEL > 0
93 if (om->M > ox->allocQ4*4) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few columns)");
94 if (L >= ox->validR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few MDI rows)");
95 if (L >= ox->allocXR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few X rows)");
96 if (! p7_oprofile_IsLocal(om)) ESL_EXCEPTION(eslEINVAL, "Forward implementation makes assumptions that only work for local alignment");
97 #endif
98
99 return forward_engine(TRUE, dsq, L, om, ox, opt_sc);
100 }
101
102 /* Function: p7_ForwardParser()
103 * Synopsis: The Forward algorithm, linear memory parsing version.
104 * Incept: SRE, Fri Aug 15 19:05:26 2008 [Casa de Gatos]
105 *
106 * Purpose: Same as <p7_Forward() except that the full matrix isn't
107 * kept. Instead, a linear $O(M+L)$ memory algorithm is
108 * used, keeping only the DP matrix values for the special
109 * (BENCJ) states. These are sufficient to do posterior
110 * decoding to identify high-probability regions where
111 * domains are.
112 *
113 * The caller must provide a suitably allocated "parsing"
114 * <ox> by calling <ox = p7_omx_Create(M, 0, L)> or
115 * <p7_omx_GrowTo(ox, M, 0, L)>.
116 *
117 * Args: dsq - digital target sequence, 1..L
118 * L - length of dsq in residues
119 * om - optimized profile
120 * ox - RETURN: Forward DP matrix
121 * ret_sc - RETURN: Forward score (in nats)
122 *
123 * Returns: <eslOK> on success.
124 *
125 * Throws: <eslEINVAL> if <ox> allocation is too small, or if the profile
126 * isn't in local alignment mode.
127 * <eslERANGE> if the score exceeds the limited range of
128 * a probability-space odds ratio.
129 * In either case, <*opt_sc> is undefined.
130 */
131 int
132 p7_ForwardParser(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox, float *opt_sc)
133 {
134 #if eslDEBUGLEVEL > 0
135 if (om->M > ox->allocQ4*4) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few columns)");
136 if (ox->validR < 1) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few MDI rows)");
137 if (L >= ox->allocXR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few X rows)");
138 if (! p7_oprofile_IsLocal(om)) ESL_EXCEPTION(eslEINVAL, "Forward implementation makes assumptions that only work for local alignment");
139 #endif
140
141 return forward_engine(FALSE, dsq, L, om, ox, opt_sc);
142 }
143
144
145
146 /* Function: p7_Backward()
147 * Synopsis: The Backward algorithm; full matrix fill version.
148 * Incept: SRE, Sat Aug 16 08:34:22 2008 [Janelia]
149 *
150 * Purpose: Calculates the Backward algorithm for sequence <dsq> of
151 * length <L> residues, using optimized profile <om>, and a
152 * preallocated DP matrix <bck>. A filled Forward matrix
153 * must also be provided in <fwd>, because we need to use
154 * the same sparse scaling factors that Forward used. The
155 * <bck> matrix is filled in, and the Backward score (in
156 * nats) is optionally returned in <opt_sc>.
157 *
158 * This calculation requires $O(ML)$ memory and time. The
159 * caller must provide a suitably allocated full <bck> by
160 * calling <bck = p7_omx_Create(M, L, L)> or
161 * <p7_omx_GrowTo(bck, M, L, L)>.
162 *
163 * Because only the sparse scaling factors are needed from
164 * the <fwd> matrix, the caller may have this matrix
165 * calculated either in full or parsing mode.
166 *
167 * The model <om> must be configured in local alignment
168 * mode. The sparse rescaling method used to keep
169 * probability values within single-precision floating
170 * point dynamic range cannot be safely applied to models in
171 * glocal or global mode.
172 *
173 * Args: dsq - digital target sequence, 1..L
174 * L - length of dsq in residues
175 * om - optimized profile
176 * fwd - filled Forward DP matrix, for scale factors
177 * do_full - TRUE=full matrix; FALSE=linear memory parse mode
178 * bck - RETURN: filled Backward matrix
179 * opt_sc - optRETURN: Backward score (in nats)
180 *
181 * Returns: <eslOK> on success.
182 *
183 * Throws: <eslEINVAL> if <ox> allocation is too small, or if the profile
184 * isn't in local alignment mode.
185 * <eslERANGE> if the score exceeds the limited range of
186 * a probability-space odds ratio.
187 * In either case, <*opt_sc> is undefined.
188 */
189 int
190 p7_Backward(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, const P7_OMX *fwd, P7_OMX *bck, float *opt_sc)
191 {
192 #if eslDEBUGLEVEL > 0
193 if (om->M > bck->allocQ4*4) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few columns)");
194 if (L >= bck->validR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few MDI rows)");
195 if (L >= bck->allocXR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few X rows)");
196 if (L != fwd->L) ESL_EXCEPTION(eslEINVAL, "fwd matrix size doesn't agree with length L");
197 if (! p7_oprofile_IsLocal(om)) ESL_EXCEPTION(eslEINVAL, "Forward implementation makes assumptions that only work for local alignment");
198 #endif
199
200 return backward_engine(TRUE, dsq, L, om, fwd, bck, opt_sc);
201 }
202
203
204
205 /* Function: p7_BackwardParser()
206 * Synopsis: The Backward algorithm, linear memory parsing version.
207 * Incept: SRE, Sat Aug 16 08:34:13 2008 [Janelia]
208 *
209 * Purpose: Same as <p7_Backward()> except that the full matrix isn't
210 * kept. Instead, a linear $O(M+L)$ memory algorithm is
211 * used, keeping only the DP matrix values for the special
212 * (BENCJ) states. These are sufficient to do posterior
213 * decoding to identify high-probability regions where
214 * domains are.
215 *
216 * The caller must provide a suitably allocated "parsing"
217 * <bck> by calling <bck = p7_omx_Create(M, 0, L)> or
218 * <p7_omx_GrowTo(bck, M, 0, L)>.
219 *
220 * Args: dsq - digital target sequence, 1..L
221 * L - length of dsq in residues
222 * om - optimized profile
223 * fwd - filled Forward DP matrix, for scale factors
224 * bck - RETURN: filled Backward matrix
225 * opt_sc - optRETURN: Backward score (in nats)
226 *
227 * Returns: <eslOK> on success.
228 *
229 * Throws: <eslEINVAL> if <ox> allocation is too small, or if the profile
230 * isn't in local alignment mode.
231 * <eslERANGE> if the score exceeds the limited range of
232 * a probability-space odds ratio.
233 * In either case, <*opt_sc> is undefined.
234 */
235 int
236 p7_BackwardParser(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, const P7_OMX *fwd, P7_OMX *bck, float *opt_sc)
237 {
238 #if eslDEBUGLEVEL > 0
239 if (om->M > bck->allocQ4*4) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few columns)");
240 if (bck->validR < 1) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few MDI rows)");
241 if (L >= bck->allocXR) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small (too few X rows)");
242 if (L != fwd->L) ESL_EXCEPTION(eslEINVAL, "fwd matrix size doesn't agree with length L");
243 if (! p7_oprofile_IsLocal(om)) ESL_EXCEPTION(eslEINVAL, "Forward implementation makes assumptions that only work for local alignment");
244 #endif
245
246 return backward_engine(FALSE, dsq, L, om, fwd, bck, opt_sc);
247 }
248
249
250
251 /*****************************************************************
252 * 2. Forward/Backward engine implementations (called thru API)
253 *****************************************************************/
254
255 static int
256 forward_engine(int do_full, const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox, float *opt_sc)
257 {
258 register __m128 mpv, dpv, ipv; /* previous row values */
259 register __m128 sv; /* temp storage of 1 curr row value in progress */
260 register __m128 dcv; /* delayed storage of D(i,q+1) */
261 register __m128 xEv; /* E state: keeps max for Mk->E as we go */
262 register __m128 xBv; /* B state: splatted vector of B[i-1] for B->Mk calculations */
263 __m128 zerov; /* splatted 0.0's in a vector */
264 float xN, xE, xB, xC, xJ; /* special states' scores */
265 int i; /* counter over sequence positions 1..L */
266 int q; /* counter over quads 0..nq-1 */
267 int j; /* counter over DD iterations (4 is full serialization) */
268 int Q = p7O_NQF(om->M); /* segment length: # of vectors */
269 __m128 *dpc = ox->dpf[0]; /* current row, for use in {MDI}MO(dpp,q) access macro */
270 __m128 *dpp; /* previous row, for use in {MDI}MO(dpp,q) access macro */
271 __m128 *rp; /* will point at om->rfv[x] for residue x[i] */
272 __m128 *tp; /* will point into (and step thru) om->tfv */
273
274 /* Initialization. */
275 ox->M = om->M;
276 ox->L = L;
277 ox->has_own_scales = TRUE; /* all forward matrices control their own scalefactors */
278 zerov = _mm_setzero_ps();
279 for (q = 0; q < Q; q++)
280 MMO(dpc,q) = IMO(dpc,q) = DMO(dpc,q) = zerov;
281 xE = ox->xmx[p7X_E] = 0.;
282 xN = ox->xmx[p7X_N] = 1.;
283 xJ = ox->xmx[p7X_J] = 0.;
284 xB = ox->xmx[p7X_B] = om->xf[p7O_N][p7O_MOVE];
285 xC = ox->xmx[p7X_C] = 0.;
286
287 ox->xmx[p7X_SCALE] = 1.0;
288 ox->totscale = 0.0;
289
290 #if eslDEBUGLEVEL > 0
291 if (ox->debugging) p7_omx_DumpFBRow(ox, TRUE, 0, 9, 5, xE, xN, xJ, xB, xC); /* logify=TRUE, <rowi>=0, width=8, precision=5*/
292 #endif
293
294 for (i = 1; i <= L; i++)
295 {
296 dpp = dpc;
297 dpc = ox->dpf[do_full * i]; /* avoid conditional, use do_full as kronecker delta */
298 rp = om->rfv[dsq[i]];
299 tp = om->tfv;
300 dcv = _mm_setzero_ps();
301 xEv = _mm_setzero_ps();
302 xBv = _mm_set1_ps(xB);
303
304 /* Right shifts by 4 bytes. 4,8,12,x becomes x,4,8,12. Shift zeros on. */
305 mpv = esl_sse_rightshiftz_float(MMO(dpp,Q-1));
306 dpv = esl_sse_rightshiftz_float(DMO(dpp,Q-1));
307 ipv = esl_sse_rightshiftz_float(IMO(dpp,Q-1));
308
309 for (q = 0; q < Q; q++)
310 {
311 /* Calculate new MMO(i,q); don't store it yet, hold it in sv. */
312 sv = _mm_mul_ps(xBv, *tp); tp++;
313 sv = _mm_add_ps(sv, _mm_mul_ps(mpv, *tp)); tp++;
314 sv = _mm_add_ps(sv, _mm_mul_ps(ipv, *tp)); tp++;
315 sv = _mm_add_ps(sv, _mm_mul_ps(dpv, *tp)); tp++;
316 sv = _mm_mul_ps(sv, *rp); rp++;
317 xEv = _mm_add_ps(xEv, sv);
318
319 /* Load {MDI}(i-1,q) into mpv, dpv, ipv;
320 * {MDI}MX(q) is then the current, not the prev row
321 */
322 mpv = MMO(dpp,q);
323 dpv = DMO(dpp,q);
324 ipv = IMO(dpp,q);
325
326 /* Do the delayed stores of {MD}(i,q) now that memory is usable */
327 MMO(dpc,q) = sv;
328 DMO(dpc,q) = dcv;
329
330 /* Calculate the next D(i,q+1) partially: M->D only;
331 * delay storage, holding it in dcv
332 */
333 dcv = _mm_mul_ps(sv, *tp); tp++;
334
335 /* Calculate and store I(i,q); assumes odds ratio for emission is 1.0 */
336 sv = _mm_mul_ps(mpv, *tp); tp++;
337 IMO(dpc,q) = _mm_add_ps(sv, _mm_mul_ps(ipv, *tp)); tp++;
338 }
339
340 /* Now the DD paths. We would rather not serialize them but
341 * in an accurate Forward calculation, we have few options.
342 */
343 /* dcv has carried through from end of q loop above; store it
344 * in first pass, we add M->D and D->D path into DMX
345 */
346 /* We're almost certainly're obligated to do at least one complete
347 * DD path to be sure:
348 */
349 dcv = esl_sse_rightshiftz_float(dcv);
350 DMO(dpc,0) = zerov;
351 tp = om->tfv + 7*Q; /* set tp to start of the DD's */
352 for (q = 0; q < Q; q++)
353 {
354 DMO(dpc,q) = _mm_add_ps(dcv, DMO(dpc,q));
355 dcv = _mm_mul_ps(DMO(dpc,q), *tp); tp++; /* extend DMO(q), so we include M->D and D->D paths */
356 }
357
358 /* now. on small models, it seems best (empirically) to just go
359 * ahead and serialize. on large models, we can do a bit better,
360 * by testing for when dcv (DD path) accrued to DMO(q) is below
361 * machine epsilon for all q, in which case we know DMO(q) are all
362 * at their final values. The tradeoff point is (empirically) somewhere around M=100,
363 * at least on my desktop. We don't worry about the conditional here;
364 * it's outside any inner loops.
365 */
366 if (om->M < 100)
367 { /* Fully serialized version */
368 for (j = 1; j < 4; j++)
369 {
370 dcv = esl_sse_rightshiftz_float(dcv);
371 tp = om->tfv + 7*Q; /* set tp to start of the DD's */
372 for (q = 0; q < Q; q++)
373 { /* note, extend dcv, not DMO(q); only adding DD paths now */
374 DMO(dpc,q) = _mm_add_ps(dcv, DMO(dpc,q));
375 dcv = _mm_mul_ps(dcv, *tp); tp++;
376 }
377 }
378 }
379 else
380 { /* Slightly parallelized version, but which incurs some overhead */
381 for (j = 1; j < 4; j++)
382 {
383 register __m128 cv; /* keeps track of whether any DD's change DMO(q) */
384
385 dcv = esl_sse_rightshiftz_float(dcv);
386 tp = om->tfv + 7*Q; /* set tp to start of the DD's */
387 cv = zerov;
388 for (q = 0; q < Q; q++)
389 { /* using cmpgt below tests if DD changed any DMO(q) *without* conditional branch */
390 sv = _mm_add_ps(dcv, DMO(dpc,q));
391 cv = _mm_or_ps(cv, _mm_cmpgt_ps(sv, DMO(dpc,q)));
392 DMO(dpc,q) = sv; /* store new DMO(q) */
393 dcv = _mm_mul_ps(dcv, *tp); tp++; /* note, extend dcv, not DMO(q) */
394 }
395 if (! _mm_movemask_ps(cv)) break; /* DD's didn't change any DMO(q)? Then done, break out. */
396 }
397 }
398
399 /* Add D's to xEv */
400 for (q = 0; q < Q; q++) xEv = _mm_add_ps(DMO(dpc,q), xEv);
401
402 /* Finally the "special" states, which start from Mk->E (->C, ->J->B) */
403 /* The following incantation is a horizontal sum of xEv's elements */
404 /* These must follow DD calculations, because D's contribute to E in Forward
405 * (as opposed to Viterbi)
406 */
407 xEv = _mm_add_ps(xEv, _mm_shuffle_ps(xEv, xEv, _MM_SHUFFLE(0, 3, 2, 1)));
408 xEv = _mm_add_ps(xEv, _mm_shuffle_ps(xEv, xEv, _MM_SHUFFLE(1, 0, 3, 2)));
409 _mm_store_ss(&xE, xEv);
410
411 xN = xN * om->xf[p7O_N][p7O_LOOP];
412 xC = (xC * om->xf[p7O_C][p7O_LOOP]) + (xE * om->xf[p7O_E][p7O_MOVE]);
413 xJ = (xJ * om->xf[p7O_J][p7O_LOOP]) + (xE * om->xf[p7O_E][p7O_LOOP]);
414 xB = (xJ * om->xf[p7O_J][p7O_MOVE]) + (xN * om->xf[p7O_N][p7O_MOVE]);
415 /* and now xB will carry over into next i, and xC carries over after i=L */
416
417 /* Sparse rescaling. xE above threshold? trigger a rescaling event. */
418 if (xE > 1.0e4) /* that's a little less than e^10, ~10% of our dynamic range */
419 {
420 xN = xN / xE;
421 xC = xC / xE;
422 xJ = xJ / xE;
423 xB = xB / xE;
424 xEv = _mm_set1_ps(1.0 / xE);
425 for (q = 0; q < Q; q++)
426 {
427 MMO(dpc,q) = _mm_mul_ps(MMO(dpc,q), xEv);
428 DMO(dpc,q) = _mm_mul_ps(DMO(dpc,q), xEv);
429 IMO(dpc,q) = _mm_mul_ps(IMO(dpc,q), xEv);
430 }
431 ox->xmx[i*p7X_NXCELLS+p7X_SCALE] = xE;
432 ox->totscale += log(xE);
433 xE = 1.0;
434 }
435 else ox->xmx[i*p7X_NXCELLS+p7X_SCALE] = 1.0;
436
437 /* Storage of the specials. We could've stored these already
438 * but using xE, etc. variables makes it easy to convert this
439 * code to O(M) memory versions just by deleting storage steps.
440 */
441 ox->xmx[i*p7X_NXCELLS+p7X_E] = xE;
442 ox->xmx[i*p7X_NXCELLS+p7X_N] = xN;
443 ox->xmx[i*p7X_NXCELLS+p7X_J] = xJ;
444 ox->xmx[i*p7X_NXCELLS+p7X_B] = xB;
445 ox->xmx[i*p7X_NXCELLS+p7X_C] = xC;
446
447 #if eslDEBUGLEVEL > 0
448 if (ox->debugging) p7_omx_DumpFBRow(ox, TRUE, i, 9, 5, xE, xN, xJ, xB, xC); /* logify=TRUE, <rowi>=i, width=9, precision=5*/
449 #endif
450 } /* end loop over sequence residues 1..L */
451
452 /* finally C->T, and flip total score back to log space (nats) */
453 /* On overflow, xC is inf or nan (nan arises because inf*0 = nan). */
454 /* On an underflow (which shouldn't happen), we counterintuitively return infinity:
455 * the effect of this is to force the caller to rescore us with full range.
456 */
457 if (isnan(xC)) ESL_EXCEPTION(eslERANGE, "forward score is NaN");
458 else if (L>0 && xC == 0.0) ESL_EXCEPTION(eslERANGE, "forward score underflow (is 0.0)"); /* if L==0, xC *should* be 0.0; J5/118 */
459 else if (isinf(xC) == 1) ESL_EXCEPTION(eslERANGE, "forward score overflow (is infinity)");
460
461 if (opt_sc != NULL) *opt_sc = ox->totscale + log(xC * om->xf[p7O_C][p7O_MOVE]);
462 return eslOK;
463 }
464
465
466
467 static int
468 backward_engine(int do_full, const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, const P7_OMX *fwd, P7_OMX *bck, float *opt_sc)
469 {
470 register __m128 mpv, ipv, dpv; /* previous row values */
471 register __m128 mcv, dcv; /* current row values */
472 register __m128 tmmv, timv, tdmv; /* tmp vars for accessing rotated transition scores */
473 register __m128 xBv; /* collects B->Mk components of B(i) */
474 register __m128 xEv; /* splatted E(i) */
475 __m128 zerov; /* splatted 0.0's in a vector */
476 float xN, xE, xB, xC, xJ; /* special states' scores */
477 int i; /* counter over sequence positions 0,1..L */
478 int q; /* counter over quads 0..Q-1 */
479 int Q = p7O_NQF(om->M); /* segment length: # of vectors */
480 int j; /* DD segment iteration counter (4 = full serialization) */
481 __m128 *dpc; /* current DP row */
482 __m128 *dpp; /* next ("previous") DP row */
483 __m128 *rp; /* will point into om->rfv[x] for residue x[i+1] */
484 __m128 *tp; /* will point into (and step thru) om->tfv transition scores */
485
486 /* initialize the L row. */
487 bck->M = om->M;
488 bck->L = L;
489 bck->has_own_scales = FALSE; /* backwards scale factors are *usually* given by <fwd> */
490 dpc = bck->dpf[L * do_full];
491 xJ = 0.0;
492 xB = 0.0;
493 xN = 0.0;
494 xC = om->xf[p7O_C][p7O_MOVE]; /* C<-T */
495 xE = xC * om->xf[p7O_E][p7O_MOVE]; /* E<-C, no tail */
496 xEv = _mm_set1_ps(xE);
497 zerov = _mm_setzero_ps();
498 dcv = zerov; /* solely to silence a compiler warning */
499 for (q = 0; q < Q; q++) MMO(dpc,q) = DMO(dpc,q) = xEv;
500 for (q = 0; q < Q; q++) IMO(dpc,q) = zerov;
501
502 /* init row L's DD paths, 1) first segment includes xE, from DMO(q) */
503 tp = om->tfv + 8*Q - 1; /* <*tp> now the [4 8 12 x] TDD quad */
504 dpv = _mm_move_ss(DMO(dpc,Q-1), zerov); /* start leftshift: [1 5 9 13] -> [x 5 9 13] */
505 dpv = _mm_shuffle_ps(dpv, dpv, _MM_SHUFFLE(0,3,2,1)); /* finish leftshift:[x 5 9 13] -> [5 9 13 x] */
506 for (q = Q-1; q >= 0; q--)
507 {
508 dcv = _mm_mul_ps(dpv, *tp); tp--;
509 DMO(dpc,q) = _mm_add_ps(DMO(dpc,q), dcv);
510 dpv = DMO(dpc,q);
511 }
512 /* 2) three more passes, only extending DD component (dcv only; no xE contrib from DMO(q)) */
513 for (j = 1; j < 4; j++)
514 {
515 tp = om->tfv + 8*Q - 1; /* <*tp> now the [4 8 12 x] TDD quad */
516 dcv = _mm_move_ss(dcv, zerov); /* start leftshift: [1 5 9 13] -> [x 5 9 13] */
517 dcv = _mm_shuffle_ps(dcv, dcv, _MM_SHUFFLE(0,3,2,1)); /* finish leftshift:[x 5 9 13] -> [5 9 13 x] */
518 for (q = Q-1; q >= 0; q--)
519 {
520 dcv = _mm_mul_ps(dcv, *tp); tp--;
521 DMO(dpc,q) = _mm_add_ps(DMO(dpc,q), dcv);
522 }
523 }
524 /* now MD init */
525 tp = om->tfv + 7*Q - 3; /* <*tp> now the [4 8 12 x] Mk->Dk+1 quad */
526 dcv = _mm_move_ss(DMO(dpc,0), zerov); /* start leftshift: [1 5 9 13] -> [x 5 9 13] */
527 dcv = _mm_shuffle_ps(dcv, dcv, _MM_SHUFFLE(0,3,2,1)); /* finish leftshift:[x 5 9 13] -> [5 9 13 x] */
528 for (q = Q-1; q >= 0; q--)
529 {
530 MMO(dpc,q) = _mm_add_ps(MMO(dpc,q), _mm_mul_ps(dcv, *tp)); tp -= 7;
531 dcv = DMO(dpc,q);
532 }
533
534 /* Sparse rescaling: same scale factors as fwd matrix */
535 if (fwd->xmx[L*p7X_NXCELLS+p7X_SCALE] > 1.0)
536 {
537 xE = xE / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
538 xN = xN / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
539 xC = xC / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
540 xJ = xJ / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
541 xB = xB / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
542 xEv = _mm_set1_ps(1.0 / fwd->xmx[L*p7X_NXCELLS+p7X_SCALE]);
543 for (q = 0; q < Q; q++) {
544 MMO(dpc,q) = _mm_mul_ps(MMO(dpc,q), xEv);
545 DMO(dpc,q) = _mm_mul_ps(DMO(dpc,q), xEv);
546 IMO(dpc,q) = _mm_mul_ps(IMO(dpc,q), xEv);
547 }
548 }
549 bck->xmx[L*p7X_NXCELLS+p7X_SCALE] = fwd->xmx[L*p7X_NXCELLS+p7X_SCALE];
550 bck->totscale = log(bck->xmx[L*p7X_NXCELLS+p7X_SCALE]);
551
552 /* Stores */
553 bck->xmx[L*p7X_NXCELLS+p7X_E] = xE;
554 bck->xmx[L*p7X_NXCELLS+p7X_N] = xN;
555 bck->xmx[L*p7X_NXCELLS+p7X_J] = xJ;
556 bck->xmx[L*p7X_NXCELLS+p7X_B] = xB;
557 bck->xmx[L*p7X_NXCELLS+p7X_C] = xC;
558
559 #if eslDEBUGLEVEL > 0
560 if (bck->debugging) p7_omx_DumpFBRow(bck, TRUE, L, 9, 4, xE, xN, xJ, xB, xC); /* logify=TRUE, <rowi>=L, width=9, precision=4*/
561 #endif
562
563 /* main recursion */
564 for (i = L-1; i >= 1; i--) /* backwards stride */
565 {
566 /* phase 1. B(i) collected. Old row destroyed, new row contains
567 * complete I(i,k), partial {MD}(i,k) w/ no {MD}->{DE} paths yet.
568 */
569 dpc = bck->dpf[i * do_full];
570 dpp = bck->dpf[(i+1) * do_full];
571 rp = om->rfv[dsq[i+1]] + Q-1; /* <*rp> is now the [4 8 12 x] match emission quad */
572 tp = om->tfv + 7*Q - 1; /* <*tp> is now the [4 8 12 x] TII transition quad */
573
574 /* leftshift the first transition quads */
575 tmmv = _mm_move_ss(om->tfv[1], zerov); tmmv = _mm_shuffle_ps(tmmv, tmmv, _MM_SHUFFLE(0,3,2,1));
576 timv = _mm_move_ss(om->tfv[2], zerov); timv = _mm_shuffle_ps(timv, timv, _MM_SHUFFLE(0,3,2,1));
577 tdmv = _mm_move_ss(om->tfv[3], zerov); tdmv = _mm_shuffle_ps(tdmv, tdmv, _MM_SHUFFLE(0,3,2,1));
578
579 mpv = _mm_mul_ps(MMO(dpp,0), om->rfv[dsq[i+1]][0]); /* precalc M(i+1,k+1) * e(M_k+1, x_{i+1}) */
580 mpv = _mm_move_ss(mpv, zerov);
581 mpv = _mm_shuffle_ps(mpv, mpv, _MM_SHUFFLE(0,3,2,1));
582
583 xBv = zerov;
584 for (q = Q-1; q >= 0; q--) /* backwards stride */
585 {
586 ipv = IMO(dpp,q); /* assumes emission odds ratio of 1.0; i+1's IMO(q) now free */
587 IMO(dpc,q) = _mm_add_ps(_mm_mul_ps(ipv, *tp), _mm_mul_ps(mpv, timv)); tp--;
588 DMO(dpc,q) = _mm_mul_ps(mpv, tdmv);
589 mcv = _mm_add_ps(_mm_mul_ps(ipv, *tp), _mm_mul_ps(mpv, tmmv)); tp-= 2;
590
591 mpv = _mm_mul_ps(MMO(dpp,q), *rp); rp--; /* obtain mpv for next q. i+1's MMO(q) is freed */
592 MMO(dpc,q) = mcv;
593
594 tdmv = *tp; tp--;
595 timv = *tp; tp--;
596 tmmv = *tp; tp--;
597
598 xBv = _mm_add_ps(xBv, _mm_mul_ps(mpv, *tp)); tp--;
599 }
600
601 /* phase 2: now that we have accumulated the B->Mk transitions in xBv, we can do the specials */
602 /* this incantation is a horiz sum of xBv elements: (_mm_hadd_ps() would require SSE3) */
603 xBv = _mm_add_ps(xBv, _mm_shuffle_ps(xBv, xBv, _MM_SHUFFLE(0, 3, 2, 1)));
604 xBv = _mm_add_ps(xBv, _mm_shuffle_ps(xBv, xBv, _MM_SHUFFLE(1, 0, 3, 2)));
605 _mm_store_ss(&xB, xBv);
606
607 xC = xC * om->xf[p7O_C][p7O_LOOP];
608 xJ = (xB * om->xf[p7O_J][p7O_MOVE]) + (xJ * om->xf[p7O_J][p7O_LOOP]); /* must come after xB */
609 xN = (xB * om->xf[p7O_N][p7O_MOVE]) + (xN * om->xf[p7O_N][p7O_LOOP]); /* must come after xB */
610 xE = (xC * om->xf[p7O_E][p7O_MOVE]) + (xJ * om->xf[p7O_E][p7O_LOOP]); /* must come after xJ, xC */
611 xEv = _mm_set1_ps(xE); /* splat */
612
613
614 /* phase 3: {MD}->E paths and one step of the D->D paths */
615 tp = om->tfv + 8*Q - 1; /* <*tp> now the [4 8 12 x] TDD quad */
616 dpv = _mm_add_ps(DMO(dpc,0), xEv);
617 dpv = _mm_move_ss(dpv, zerov);
618 dpv = _mm_shuffle_ps(dpv, dpv, _MM_SHUFFLE(0,3,2,1));
619 for (q = Q-1; q >= 0; q--)
620 {
621 dcv = _mm_mul_ps(dpv, *tp); tp--;
622 DMO(dpc,q) = _mm_add_ps(DMO(dpc,q), _mm_add_ps(dcv, xEv));
623 dpv = DMO(dpc,q);
624 MMO(dpc,q) = _mm_add_ps(MMO(dpc,q), xEv);
625 }
626
627 /* phase 4: finish extending the DD paths */
628 /* fully serialized for now */
629 for (j = 1; j < 4; j++) /* three passes: we've already done 1 segment, we need 4 total */
630 {
631 dcv = _mm_move_ss(dcv, zerov);
632 dcv = _mm_shuffle_ps(dcv, dcv, _MM_SHUFFLE(0,3,2,1));
633 tp = om->tfv + 8*Q - 1; /* <*tp> now the [4 8 12 x] TDD quad */
634 for (q = Q-1; q >= 0; q--)
635 {
636 dcv = _mm_mul_ps(dcv, *tp); tp--;
637 DMO(dpc,q) = _mm_add_ps(DMO(dpc,q), dcv);
638 }
639 }
640
641 /* phase 5: add M->D paths */
642 dcv = _mm_move_ss(DMO(dpc,0), zerov);
643 dcv = _mm_shuffle_ps(dcv, dcv, _MM_SHUFFLE(0,3,2,1));
644 tp = om->tfv + 7*Q - 3; /* <*tp> is now the [4 8 12 x] Mk->Dk+1 quad */
645 for (q = Q-1; q >= 0; q--)
646 {
647 MMO(dpc,q) = _mm_add_ps(MMO(dpc,q), _mm_mul_ps(dcv, *tp)); tp -= 7;
648 dcv = DMO(dpc,q);
649 }
650
651 /* Sparse rescaling */
652
653 /* In rare cases [J3/119] scale factors from <fwd> are
654 * insufficient and backwards will overflow. In this case, we
655 * switch on the fly to using our own scale factors, different
656 * from those in <fwd>. This will complicate subsequent
657 * posterior decoding routines.
658 */
659 if (xB > 1.0e16) bck->has_own_scales = TRUE;
660
661 if (bck->has_own_scales) bck->xmx[i*p7X_NXCELLS+p7X_SCALE] = (xB > 1.0e4) ? xB : 1.0;
662 else bck->xmx[i*p7X_NXCELLS+p7X_SCALE] = fwd->xmx[i*p7X_NXCELLS+p7X_SCALE];
663
664 if (bck->xmx[i*p7X_NXCELLS+p7X_SCALE] > 1.0)
665 {
666 xE /= bck->xmx[i*p7X_NXCELLS+p7X_SCALE];
667 xN /= bck->xmx[i*p7X_NXCELLS+p7X_SCALE];
668 xJ /= bck->xmx[i*p7X_NXCELLS+p7X_SCALE];
669 xB /= bck->xmx[i*p7X_NXCELLS+p7X_SCALE];
670 xC /= bck->xmx[i*p7X_NXCELLS+p7X_SCALE];
671 xBv = _mm_set1_ps(1.0 / bck->xmx[i*p7X_NXCELLS+p7X_SCALE]);
672 for (q = 0; q < Q; q++) {
673 MMO(dpc,q) = _mm_mul_ps(MMO(dpc,q), xBv);
674 DMO(dpc,q) = _mm_mul_ps(DMO(dpc,q), xBv);
675 IMO(dpc,q) = _mm_mul_ps(IMO(dpc,q), xBv);
676 }
677 bck->totscale += log(bck->xmx[i*p7X_NXCELLS+p7X_SCALE]);
678 }
679
680 /* Stores are separate only for pedagogical reasons: easy to
681 * turn this into a more memory efficient version just by
682 * deleting the stores.
683 */
684 bck->xmx[i*p7X_NXCELLS+p7X_E] = xE;
685 bck->xmx[i*p7X_NXCELLS+p7X_N] = xN;
686 bck->xmx[i*p7X_NXCELLS+p7X_J] = xJ;
687 bck->xmx[i*p7X_NXCELLS+p7X_B] = xB;
688 bck->xmx[i*p7X_NXCELLS+p7X_C] = xC;
689
690 #if eslDEBUGLEVEL > 0
691 if (bck->debugging) p7_omx_DumpFBRow(bck, TRUE, i, 9, 4, xE, xN, xJ, xB, xC); /* logify=TRUE, <rowi>=i, width=9, precision=4*/
692 #endif
693 } /* thus ends the loop over sequence positions i */
694
695 /* Termination at i=0, where we can only reach N,B states. */
696 dpp = bck->dpf[1 * do_full];
697 tp = om->tfv; /* <*tp> is now the [1 5 9 13] TBMk transition quad */
698 rp = om->rfv[dsq[1]]; /* <*rp> is now the [1 5 9 13] match emission quad */
699 xBv = zerov;
700 for (q = 0; q < Q; q++)
701 {
702 mpv = _mm_mul_ps(MMO(dpp,q), *rp); rp++;
703 mpv = _mm_mul_ps(mpv, *tp); tp += 7;
704 xBv = _mm_add_ps(xBv, mpv);
705 }
706 /* horizontal sum of xBv */
707 xBv = _mm_add_ps(xBv, _mm_shuffle_ps(xBv, xBv, _MM_SHUFFLE(0, 3, 2, 1)));
708 xBv = _mm_add_ps(xBv, _mm_shuffle_ps(xBv, xBv, _MM_SHUFFLE(1, 0, 3, 2)));
709 _mm_store_ss(&xB, xBv);
710
711 xN = (xB * om->xf[p7O_N][p7O_MOVE]) + (xN * om->xf[p7O_N][p7O_LOOP]);
712
713 bck->xmx[p7X_B] = xB;
714 bck->xmx[p7X_C] = 0.0;
715 bck->xmx[p7X_J] = 0.0;
716 bck->xmx[p7X_N] = xN;
717 bck->xmx[p7X_E] = 0.0;
718 bck->xmx[p7X_SCALE] = 1.0;
719
720 #if eslDEBUGLEVEL > 0
721 dpc = bck->dpf[0];
722 for (q = 0; q < Q; q++) /* Not strictly necessary, but if someone's looking at DP matrices, this is nice to do: */
723 MMO(dpc,q) = DMO(dpc,q) = IMO(dpc,q) = zerov;
724 if (bck->debugging) p7_omx_DumpFBRow(bck, TRUE, 0, 9, 4, bck->xmx[p7X_E], bck->xmx[p7X_N], bck->xmx[p7X_J], bck->xmx[p7X_B], bck->xmx[p7X_C]); /* logify=TRUE, <rowi>=0, width=9, precision=4*/
725 #endif
726
727 if (isnan(xN)) ESL_EXCEPTION(eslERANGE, "backward score is NaN");
728 else if (L>0 && xN == 0.0) ESL_EXCEPTION(eslERANGE, "backward score underflow (is 0.0)"); /* if L==0, xN *should* be 0.0 [J5/118]*/
729 else if (isinf(xN) == 1) ESL_EXCEPTION(eslERANGE, "backward score overflow (is infinity)");
730
731 if (opt_sc != NULL) *opt_sc = bck->totscale + log(xN);
732 return eslOK;
733 }
734 /*-------------- end, forward/backward engines -----------------*/
735
736
737
738
739
740 /*****************************************************************
741 * 4. Benchmark driver.
742 *****************************************************************/
743 #ifdef p7FWDBACK_BENCHMARK
744 /* -c, -x options are for debugging and testing: see fwdfilter.c for explanation */
745 /*
746 icc -O3 -static -o fwdback_benchmark -I.. -L.. -I../../easel -L../../easel -Dp7FWDBACK_BENCHMARK fwdback.c -lhmmer -leasel -lm
747
748 ./fwdback_benchmark <hmmfile> runs benchmark on both Forward and Backward parser
749 ./fwdback_benchmark -c -N100 <hmmfile> compare scores of SSE to generic impl
750 ./fwdback_benchmark -x -N100 <hmmfile> test that scores match trusted implementation.
751 */
752 #include <p7_config.h>
753
754 #include "easel.h"
755 #include "esl_alphabet.h"
756 #include "esl_getopts.h"
757 #include "esl_random.h"
758 #include "esl_randomseq.h"
759 #include "esl_stopwatch.h"
760
761 #include "hmmer.h"
762 #include "impl_sse.h"
763
764 static ESL_OPTIONS options[] = {
765 /* name type default env range toggles reqs incomp help docgroup*/
766 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
767 { "-c", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-x", "compare scores to generic implementation (debug)", 0 },
768 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
769 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-c", "equate scores to trusted implementation (debug)", 0 },
770 { "-L", eslARG_INT, "400", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
771 { "-N", eslARG_INT, "50000", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
772 { "-F", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-B", "only benchmark Forward", 0 },
773 { "-B", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-F", "only benchmark Backward", 0 },
774 { "-P", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "benchmark parsing version, not full version", 0 },
775 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
776 };
777 static char usage[] = "[-options] <hmmfile>";
778 static char banner[] = "benchmark driver for Forward, Backward implementations";
779
780 int
781 main(int argc, char **argv)
782 {
783 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
784 char *hmmfile = esl_opt_GetArg(go, 1);
785 ESL_STOPWATCH *w = esl_stopwatch_Create();
786 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
787 ESL_ALPHABET *abc = NULL;
788 P7_HMMFILE *hfp = NULL;
789 P7_HMM *hmm = NULL;
790 P7_BG *bg = NULL;
791 P7_PROFILE *gm = NULL;
792 P7_OPROFILE *om = NULL;
793 P7_GMX *gx = NULL;
794 P7_OMX *fwd = NULL;
795 P7_OMX *bck = NULL;
796 int L = esl_opt_GetInteger(go, "-L");
797 int N = esl_opt_GetInteger(go, "-N");
798 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
799 int i;
800 float fsc, bsc;
801 float fsc2, bsc2;
802 double base_time, bench_time, Mcs;
803
804 p7_FLogsumInit();
805
806 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
807 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
808
809 bg = p7_bg_Create(abc);
810 p7_bg_SetLength(bg, L);
811 gm = p7_profile_Create(hmm->M, abc);
812 p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL);
813 om = p7_oprofile_Create(gm->M, abc);
814 p7_oprofile_Convert(gm, om);
815 p7_oprofile_ReconfigLength(om, L);
816
817 if (esl_opt_GetBoolean(go, "-x") && p7_FLogsumError(-0.4, -0.5) > 0.0001)
818 p7_Fail("-x here requires p7_Logsum() recompiled in slow exact mode");
819
820 if (esl_opt_GetBoolean(go, "-P")) {
821 fwd = p7_omx_Create(gm->M, 0, L);
822 bck = p7_omx_Create(gm->M, 0, L);
823 } else {
824 fwd = p7_omx_Create(gm->M, L, L);
825 bck = p7_omx_Create(gm->M, L, L);
826 }
827 gx = p7_gmx_Create(gm->M, L);
828
829 /* Get a baseline time: how long it takes just to generate the sequences */
830 esl_stopwatch_Start(w);
831 for (i = 0; i < N; i++) esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
832 esl_stopwatch_Stop(w);
833 base_time = w->user;
834
835 esl_stopwatch_Start(w);
836 for (i = 0; i < N; i++)
837 {
838 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
839 if (esl_opt_GetBoolean(go, "-P")) {
840 if (! esl_opt_GetBoolean(go, "-B")) p7_ForwardParser (dsq, L, om, fwd, &fsc);
841 if (! esl_opt_GetBoolean(go, "-F")) p7_BackwardParser(dsq, L, om, fwd, bck, &bsc);
842 } else {
843 if (! esl_opt_GetBoolean(go, "-B")) p7_Forward (dsq, L, om, fwd, &fsc);
844 if (! esl_opt_GetBoolean(go, "-F")) p7_Backward(dsq, L, om, fwd, bck, &bsc);
845 }
846
847 if (esl_opt_GetBoolean(go, "-c") || esl_opt_GetBoolean(go, "-x"))
848 {
849 p7_GForward (dsq, L, gm, gx, &fsc2);
850 p7_GBackward(dsq, L, gm, gx, &bsc2);
851 printf("%.4f %.4f %.4f %.4f\n", fsc, bsc, fsc2, bsc2);
852 }
853 }
854 esl_stopwatch_Stop(w);
855 bench_time = w->user - base_time;
856 Mcs = (double) N * (double) L * (double) gm->M * 1e-6 / (double) bench_time;
857 esl_stopwatch_Display(stdout, w, "# CPU time: ");
858 printf("# M = %d\n", gm->M);
859 printf("# %.1f Mc/s\n", Mcs);
860
861 free(dsq);
862 p7_omx_Destroy(bck);
863 p7_omx_Destroy(fwd);
864 p7_gmx_Destroy(gx);
865 p7_oprofile_Destroy(om);
866 p7_profile_Destroy(gm);
867 p7_bg_Destroy(bg);
868 p7_hmm_Destroy(hmm);
869 p7_hmmfile_Close(hfp);
870 esl_alphabet_Destroy(abc);
871 esl_stopwatch_Destroy(w);
872 esl_randomness_Destroy(r);
873 esl_getopts_Destroy(go);
874 return 0;
875 }
876 #endif /*p7FWDBACK_BENCHMARK*/
877 /*------------------- end, benchmark driver ---------------------*/
878
879
880
881
882
883 /*****************************************************************
884 * 5. Unit tests.
885 *****************************************************************/
886 #ifdef p7FWDBACK_TESTDRIVE
887 #include "esl_random.h"
888 #include "esl_randomseq.h"
889
890 /*
891 * compare to GForward() scores.
892 */
893 static void
894 utest_fwdback(ESL_RANDOMNESS *r, ESL_ALPHABET *abc, P7_BG *bg, int M, int L, int N)
895 {
896 char *msg = "forward/backward unit test failed";
897 P7_HMM *hmm = NULL;
898 P7_PROFILE *gm = NULL;
899 P7_OPROFILE *om = NULL;
900 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
901 P7_OMX *fwd = p7_omx_Create(M, 0, L);
902 P7_OMX *bck = p7_omx_Create(M, 0, L);
903 P7_OMX *oxf = p7_omx_Create(M, L, L);
904 P7_OMX *oxb = p7_omx_Create(M, L, L);
905 P7_GMX *gx = p7_gmx_Create(M, L);
906 float tolerance;
907 float fsc1, fsc2;
908 float bsc1, bsc2;
909 float generic_sc;
910
911 p7_FLogsumInit();
912 if (p7_FLogsumError(-0.4, -0.5) > 0.0001) tolerance = 1.0; /* weaker test against GForward() */
913 else tolerance = 0.0001; /* stronger test: FLogsum() is in slow exact mode. */
914
915 p7_oprofile_Sample(r, abc, bg, M, L, &hmm, &gm, &om);
916 while (N--)
917 {
918 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
919
920 p7_Forward (dsq, L, om, oxf, &fsc1);
921 p7_Backward (dsq, L, om, oxf, oxb, &bsc1);
922 p7_ForwardParser (dsq, L, om, fwd, &fsc2);
923 p7_BackwardParser(dsq, L, om, fwd, bck, &bsc2);
924 p7_GForward (dsq, L, gm, gx, &generic_sc);
925
926 /* Forward and Backward scores should agree with high tolerance */
927 if (fabs(fsc1-bsc1) > 0.0001) esl_fatal(msg);
928 if (fabs(fsc2-bsc2) > 0.0001) esl_fatal(msg);
929 if (fabs(fsc1-fsc2) > 0.0001) esl_fatal(msg);
930
931 /* GForward scores should approximate Forward scores,
932 * with tolerance that depends on how logsum.c was compiled
933 */
934 if (fabs(fsc1-generic_sc) > tolerance) esl_fatal(msg);
935 }
936
937 free(dsq);
938 p7_hmm_Destroy(hmm);
939 p7_omx_Destroy(oxb);
940 p7_omx_Destroy(oxf);
941 p7_omx_Destroy(bck);
942 p7_omx_Destroy(fwd);
943 p7_gmx_Destroy(gx);
944 p7_profile_Destroy(gm);
945 p7_oprofile_Destroy(om);
946 }
947 #endif /*p7FWDBACK_TESTDRIVE*/
948 /*---------------------- end, unit tests ------------------------*/
949
950
951
952
953 /*****************************************************************
954 * 6. Test driver
955 *****************************************************************/
956 #ifdef p7FWDBACK_TESTDRIVE
957 /*
958 gcc -g -Wall -msse2 -std=gnu99 -o fwdback_utest -I.. -L.. -I../../easel -L../../easel -Dp7FWDBACK_TESTDRIVE fwdback.c -lhmmer -leasel -lm
959 ./fwdback_utest
960 */
961 #include <p7_config.h>
962
963 #include "easel.h"
964 #include "esl_alphabet.h"
965 #include "esl_getopts.h"
966 #include "esl_random.h"
967
968 #include "hmmer.h"
969 #include "impl_sse.h"
970
971 static ESL_OPTIONS options[] = {
972 /* name type default env range toggles reqs incomp help docgroup*/
973 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
974 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
975 { "-L", eslARG_INT, "200", NULL, NULL, NULL, NULL, NULL, "size of random sequences to sample", 0 },
976 { "-M", eslARG_INT, "145", NULL, NULL, NULL, NULL, NULL, "size of random models to sample", 0 },
977 { "-N", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "number of random sequences to sample", 0 },
978 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
979 };
980 static char usage[] = "[-options]";
981 static char banner[] = "test driver for SSE Forward, Backward implementations";
982
983 int
984 main(int argc, char **argv)
985 {
986 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
987 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
988 ESL_ALPHABET *abc = NULL;
989 P7_BG *bg = NULL;
990 int M = esl_opt_GetInteger(go, "-M");
991 int L = esl_opt_GetInteger(go, "-L");
992 int N = esl_opt_GetInteger(go, "-N");
993
994 /* First round of tests for DNA alphabets. */
995 if ((abc = esl_alphabet_Create(eslDNA)) == NULL) esl_fatal("failed to create alphabet");
996 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
997
998 utest_fwdback(r, abc, bg, M, L, N); /* normal sized models */
999 utest_fwdback(r, abc, bg, 1, L, 10); /* size 1 models */
1000 utest_fwdback(r, abc, bg, M, 1, 10); /* size 1 sequences */
1001
1002 esl_alphabet_Destroy(abc);
1003 p7_bg_Destroy(bg);
1004
1005 /* Second round of tests for amino alphabets. */
1006 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal("failed to create alphabet");
1007 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
1008
1009 utest_fwdback(r, abc, bg, M, L, N);
1010 utest_fwdback(r, abc, bg, 1, L, 10);
1011 utest_fwdback(r, abc, bg, M, 1, 10);
1012
1013 esl_alphabet_Destroy(abc);
1014 p7_bg_Destroy(bg);
1015
1016 esl_getopts_Destroy(go);
1017 esl_randomness_Destroy(r);
1018 return eslOK;
1019 }
1020 #endif /*p7FWDBACK_TESTDRIVE*/
1021 /*--------------------- end, test driver ------------------------*/
1022
1023
1024
1025 /*****************************************************************
1026 * 7. Example
1027 *****************************************************************/
1028 #ifdef p7FWDBACK_EXAMPLE
1029 /* Useful for debugging on small HMMs and sequences.
1030 *
1031 * Compares to GForward().
1032 *
1033 gcc -g -Wall -msse2 -std=gnu99 -o fwdback_example -I.. -L.. -I../../easel -L../../easel -Dp7FWDBACK_EXAMPLE fwdback.c -lhmmer -leasel -lm
1034 ./fwdback_example <hmmfile> <seqfile>
1035 */
1036 #include <p7_config.h>
1037
1038 #include "easel.h"
1039 #include "esl_alphabet.h"
1040 #include "esl_exponential.h"
1041 #include "esl_getopts.h"
1042 #include "esl_sq.h"
1043 #include "esl_sqio.h"
1044
1045 #include "hmmer.h"
1046 #include "impl_sse.h"
1047
1048 #define STYLES "--fs,--sw,--ls,--s" /* Exclusive choice for alignment mode */
1049
1050 static ESL_OPTIONS options[] = {
1051 /* name type default env range toggles reqs incomp help docgroup*/
1052 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1053 { "-1", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in one line awkable format", 0 },
1054 { "-P", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in profmark format", 0 },
1055 { "--fs", eslARG_NONE,"default",NULL, NULL, STYLES, NULL, NULL, "multihit local alignment", 0 },
1056 { "--sw", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "unihit local alignment", 0 },
1057 { "--ls", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "multihit glocal alignment", 0 },
1058 { "--s", eslARG_NONE, FALSE, NULL, NULL, STYLES, NULL, NULL, "unihit glocal alignment", 0 },
1059 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1060 };
1061 static char usage[] = "[-options] <hmmfile> <seqfile>";
1062 static char banner[] = "example of Forward/Backward (SSE versions)";
1063
1064 int
1065 main(int argc, char **argv)
1066 {
1067 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 2, argc, argv, banner, usage);
1068 char *hmmfile = esl_opt_GetArg(go, 1);
1069 char *seqfile = esl_opt_GetArg(go, 2);
1070 ESL_ALPHABET *abc = NULL;
1071 P7_HMMFILE *hfp = NULL;
1072 P7_HMM *hmm = NULL;
1073 P7_BG *bg = NULL;
1074 P7_PROFILE *gm = NULL;
1075 P7_OPROFILE *om = NULL;
1076 P7_GMX *gx = NULL;
1077 P7_OMX *fwd = NULL;
1078 P7_OMX *bck = NULL;
1079 ESL_SQ *sq = NULL;
1080 ESL_SQFILE *sqfp = NULL;
1081 int format = eslSQFILE_UNKNOWN;
1082 float fraw, braw, nullsc, fsc;
1083 float gfraw, gbraw, gfsc;
1084 double P, gP;
1085 int status;
1086
1087 /* Read in one HMM */
1088 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
1089 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
1090
1091 /* Open sequence file for reading */
1092 sq = esl_sq_CreateDigital(abc);
1093 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
1094 if (status == eslENOTFOUND) p7_Fail("No such file.");
1095 else if (status == eslEFORMAT) p7_Fail("Format unrecognized.");
1096 else if (status == eslEINVAL) p7_Fail("Can't autodetect stdin or .gz.");
1097 else if (status != eslOK) p7_Fail("Open failed, code %d.", status);
1098
1099 /* create default null model, then create and optimize profile */
1100 bg = p7_bg_Create(abc);
1101 p7_bg_SetLength(bg, sq->n);
1102 gm = p7_profile_Create(hmm->M, abc);
1103
1104 /* Now reconfig the models however we were asked to */
1105 if (esl_opt_GetBoolean(go, "--fs")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_LOCAL);
1106 else if (esl_opt_GetBoolean(go, "--sw")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_UNILOCAL);
1107 else if (esl_opt_GetBoolean(go, "--ls")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_GLOCAL);
1108 else if (esl_opt_GetBoolean(go, "--s")) p7_ProfileConfig(hmm, bg, gm, sq->n, p7_UNIGLOCAL);
1109
1110 /* now the optimized profile */
1111 om = p7_oprofile_Create(gm->M, abc);
1112 p7_oprofile_Convert(gm, om);
1113 /* p7_oprofile_Dump(stdout, om); */
1114
1115 /* allocate DP matrices for O(M+L) parsers */
1116 fwd = p7_omx_Create(gm->M, 0, sq->n);
1117 bck = p7_omx_Create(gm->M, 0, sq->n);
1118 gx = p7_gmx_Create(gm->M, sq->n);
1119
1120 /* allocate DP matrices for O(ML) fills */
1121 /* fwd = p7_omx_Create(gm->M, sq->n, sq->n); */
1122 /* bck = p7_omx_Create(gm->M, sq->n, sq->n); */
1123
1124 /* p7_omx_SetDumpMode(stdout, fwd, TRUE); */ /* makes the fast DP algorithms dump their matrices */
1125 /* p7_omx_SetDumpMode(stdout, bck, TRUE); */
1126
1127 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
1128 {
1129 p7_oprofile_ReconfigLength(om, sq->n);
1130 p7_ReconfigLength(gm, sq->n);
1131 p7_bg_SetLength(bg, sq->n);
1132 p7_omx_GrowTo(fwd, om->M, 0, sq->n);
1133 p7_omx_GrowTo(bck, om->M, 0, sq->n);
1134 p7_gmx_GrowTo(gx, gm->M, sq->n);
1135
1136 p7_bg_NullOne (bg, sq->dsq, sq->n, &nullsc);
1137
1138 p7_ForwardParser (sq->dsq, sq->n, om, fwd, &fraw);
1139 p7_BackwardParser(sq->dsq, sq->n, om, fwd, bck, &braw);
1140
1141 /* p7_Forward (sq->dsq, sq->n, om, fwd, &fsc); printf("forward: %.2f nats\n", fsc); */
1142 /* p7_Backward(sq->dsq, sq->n, om, fwd, bck, &bsc); printf("backward: %.2f nats\n", bsc); */
1143
1144 /* Comparison to other F/B implementations */
1145 p7_GForward (sq->dsq, sq->n, gm, gx, &gfraw);
1146 p7_GBackward (sq->dsq, sq->n, gm, gx, &gbraw);
1147
1148 /* p7_gmx_Dump(stdout, gx, p7_DEFAULT); */
1149
1150 fsc = (fraw-nullsc) / eslCONST_LOG2;
1151 gfsc = (gfraw-nullsc) / eslCONST_LOG2;
1152 P = esl_exp_surv(fsc, om->evparam[p7_FTAU], om->evparam[p7_FLAMBDA]);
1153 gP = esl_exp_surv(gfsc, gm->evparam[p7_FTAU], gm->evparam[p7_FLAMBDA]);
1154
1155 if (esl_opt_GetBoolean(go, "-1"))
1156 {
1157 printf("%-30s\t%-20s\t%9.2g\t%6.1f\t%9.2g\t%6.1f\n", sq->name, hmm->name, P, fsc, gP, gfsc);
1158 }
1159 else if (esl_opt_GetBoolean(go, "-P"))
1160 { /* output suitable for direct use in profmark benchmark postprocessors: */
1161 printf("%g\t%.2f\t%s\t%s\n", P, fsc, sq->name, hmm->name);
1162 }
1163 else
1164 {
1165 printf("target sequence: %s\n", sq->name);
1166 printf("fwd filter raw score: %.2f nats\n", fraw);
1167 printf("bck filter raw score: %.2f nats\n", braw);
1168 printf("null score: %.2f nats\n", nullsc);
1169 printf("per-seq score: %.2f bits\n", fsc);
1170 printf("P-value: %g\n", P);
1171 printf("GForward raw score: %.2f nats\n", gfraw);
1172 printf("GBackward raw score: %.2f nats\n", gbraw);
1173 printf("GForward seq score: %.2f bits\n", gfsc);
1174 printf("GForward P-value: %g\n", gP);
1175 }
1176
1177 esl_sq_Reuse(sq);
1178 }
1179
1180 /* cleanup */
1181 esl_sq_Destroy(sq);
1182 esl_sqfile_Close(sqfp);
1183 p7_omx_Destroy(bck);
1184 p7_omx_Destroy(fwd);
1185 p7_gmx_Destroy(gx);
1186 p7_oprofile_Destroy(om);
1187 p7_profile_Destroy(gm);
1188 p7_bg_Destroy(bg);
1189 p7_hmm_Destroy(hmm);
1190 p7_hmmfile_Close(hfp);
1191 esl_alphabet_Destroy(abc);
1192 esl_getopts_Destroy(go);
1193 return 0;
1194 }
1195 #endif /*p7FWDBACK_EXAMPLE*/
1196