Debian Codegraph @

hmmer/src/impl_vmx/vitfilter.c

raw symbols SCIP
1 /* Viterbi filter implementation; VMX version.
2 *
3 * This is a SIMD vectorized, striped, interleaved, one-row, reduced
4 * precision (epi16) implementation of the Viterbi algorithm.
5 *
6 * It calculates a close approximation of the Viterbi score, in
7 * limited precision (signed words: 16 bits) and range. It may overflow on
8 * high scoring sequences, but this indicates that the sequence is a
9 * high-scoring hit worth examining more closely anyway. It will not
10 * underflow, in local alignment mode.
11 *
12 * Contents:
13 * 1. Viterbi filter implementation.
14 * 2. Benchmark driver.
15 * 3. Unit tests.
16 * 4. Test driver.
17 * 5. Example.
18 *
19 * SRE, Thu Jul 31 20:32:25 2008 [Casa de Gatos]
20 */
21 #include <p7_config.h>
22
23 #include <stdio.h>
24 #include <math.h>
25
26 #ifndef __APPLE_ALTIVEC__
27 #include <altivec.h>
28 #endif
29
30 #include "easel.h"
31 #include "esl_vmx.h"
32 #include "esl_gumbel.h"
33
34 #include "hmmer.h"
35 #include "impl_vmx.h"
36
37
38 /*****************************************************************
39 * 1. Viterbi filter implementation.
40 *****************************************************************/
41
42 /* Function: p7_ViterbiFilter()
43 * Synopsis: Calculates Viterbi score, vewy vewy fast, in limited precision.
44 * Incept: SRE, Tue Nov 27 09:15:24 2007 [Janelia]
45 *
46 * Purpose: Calculates an approximation of the Viterbi score for sequence
47 * <dsq> of length <L> residues, using optimized profile <om>,
48 * and a preallocated one-row DP matrix <ox>. Return the
49 * estimated Viterbi score (in nats) in <ret_sc>.
50 *
51 * Score may overflow (and will, on high-scoring
52 * sequences), but will not underflow.
53 *
54 * The model must be in a local alignment mode; other modes
55 * cannot provide the necessary guarantee of no underflow.
56 *
57 * This is a striped SIMD Viterbi implementation using Intel
58 * VMX integer intrinsics \citep{Farrar07}, in reduced
59 * precision (signed words, 16 bits).
60 *
61 * Args: dsq - digital target sequence, 1..L
62 * L - length of dsq in residues
63 * om - optimized profile
64 * ox - DP matrix
65 * ret_sc - RETURN: Viterbi score (in nats)
66 *
67 * Returns: <eslOK> on success;
68 * <eslERANGE> if the score overflows; in this case
69 * <*ret_sc> is <eslINFINITY>, and the sequence can
70 * be treated as a high-scoring hit.
71 *
72 * Throws: <eslEINVAL> if <ox> allocation is too small, or if
73 * profile isn't in a local alignment mode. (Must be in local
74 * alignment mode because that's what helps us guarantee
75 * limited dynamic range.)
76 *
77 * Xref: [Farrar07] for ideas behind striped SIMD DP.
78 * J2/46-47 for layout of HMMER's striped SIMD DP.
79 * J2/50 for single row DP.
80 * J2/60 for reduced precision (epu8)
81 * J2/65 for initial benchmarking
82 * J2/66 for precision maximization
83 * J4/138-140 for reimplementation in 16-bit precision
84 */
85 int
86 p7_ViterbiFilter(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox, float *ret_sc)
87 {
88 vector signed short mpv, dpv, ipv; /* previous row values */
89 vector signed short sv; /* temp storage of 1 curr row value in progress */
90 vector signed short dcv; /* delayed storage of D(i,q+1) */
91 vector signed short xEv; /* E state: keeps max for Mk->E as we go */
92 vector signed short xBv; /* B state: splatted vector of B[i-1] for B->Mk calculations */
93 vector signed short Dmaxv; /* keeps track of maximum D cell on row */
94 int16_t xE, xB, xC, xJ, xN; /* special states' scores */
95 int16_t Dmax; /* maximum D cell score on row */
96 int i; /* counter over sequence positions 1..L */
97 int q; /* counter over vectors 0..nq-1 */
98 int Q; /* segment length: # of vectors */
99 vector signed short *dp; /* using {MDI}MX(q) macro requires initialization of <dp> */
100 vector signed short *rsc; /* will point at om->ru[x] for residue x[i] */
101 vector signed short *tsc; /* will point into (and step thru) om->tu */
102
103 vector signed short negInfv;
104
105 Q = p7O_NQW(om->M);
106 dp = ox->dpw[0];
107
108 /* Check that the DP matrix is ok for us. */
109 if (Q > ox->allocQ8) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small");
110 if (om->mode != p7_LOCAL && om->mode != p7_UNILOCAL) ESL_EXCEPTION(eslEINVAL, "Fast filter only works for local alignment");
111 ox->M = om->M;
112
113 negInfv = esl_vmx_set_s16((signed short)-32768);
114
115 /* Initialization. In unsigned arithmetic, -infinity is -32768
116 */
117 for (q = 0; q < Q; q++)
118 MMXo(q) = IMXo(q) = DMXo(q) = negInfv;
119 xN = om->base_w;
120 xB = xN + om->xw[p7O_N][p7O_MOVE];
121 xJ = -32768;
122 xC = -32768;
123 xE = -32768;
124
125 #if eslDEBUGLEVEL > 0
126 if (ox->debugging) p7_omx_DumpVFRow(ox, 0, xE, 0, xJ, xB, xC); /* first 0 is <rowi>: do header. second 0 is xN: always 0 here. */
127 #endif
128
129 for (i = 1; i <= L; i++)
130 {
131 rsc = om->rwv[dsq[i]];
132 tsc = om->twv;
133 dcv = negInfv; /* "-infinity" */
134 xEv = negInfv;
135 Dmaxv = negInfv;
136 xBv = esl_vmx_set_s16(xB);
137
138 /* Right shifts by 1 value (2 bytes). 4,8,12,x becomes x,4,8,12.
139 * Because ia32 is littlendian, this means a left bit shift.
140 * Zeros shift on automatically; replace it with -32768.
141 */
142 mpv = MMXo(Q-1); mpv = vec_sld(negInfv, mpv, 14);
143 dpv = DMXo(Q-1); dpv = vec_sld(negInfv, dpv, 14);
144 ipv = IMXo(Q-1); ipv = vec_sld(negInfv, ipv, 14);
145
146 for (q = 0; q < Q; q++)
147 {
148 /* Calculate new MMXo(i,q); don't store it yet, hold it in sv. */
149 sv = vec_adds(xBv, *tsc); tsc++;
150 sv = vec_max (sv, vec_adds(mpv, *tsc)); tsc++;
151 sv = vec_max (sv, vec_adds(ipv, *tsc)); tsc++;
152 sv = vec_max (sv, vec_adds(dpv, *tsc)); tsc++;
153 sv = vec_adds(sv, *rsc); rsc++;
154 xEv = vec_max(xEv, sv);
155
156 /* Load {MDI}(i-1,q) into mpv, dpv, ipv;
157 * {MDI}MX(q) is then the current, not the prev row
158 */
159 mpv = MMXo(q);
160 dpv = DMXo(q);
161 ipv = IMXo(q);
162
163 /* Do the delayed stores of {MD}(i,q) now that memory is usable */
164 MMXo(q) = sv;
165 DMXo(q) = dcv;
166
167 /* Calculate the next D(i,q+1) partially: M->D only;
168 * delay storage, holding it in dcv
169 */
170 dcv = vec_adds(sv, *tsc); tsc++;
171 Dmaxv = vec_max(dcv, Dmaxv);
172
173 /* Calculate and store I(i,q) */
174 sv = vec_adds(mpv, *tsc); tsc++;
175 IMXo(q)= vec_max(sv, vec_adds(ipv, *tsc)); tsc++;
176 }
177
178 /* Now the "special" states, which start from Mk->E (->C, ->J->B) */
179 xE = esl_vmx_hmax_s16(xEv);
180 if (xE >= 32767) { *ret_sc = eslINFINITY; return eslERANGE; } /* immediately detect overflow */
181 xN = xN + om->xw[p7O_N][p7O_LOOP];
182 xC = ESL_MAX(xC + om->xw[p7O_C][p7O_LOOP], xE + om->xw[p7O_E][p7O_MOVE]);
183 xJ = ESL_MAX(xJ + om->xw[p7O_J][p7O_LOOP], xE + om->xw[p7O_E][p7O_LOOP]);
184 xB = ESL_MAX(xJ + om->xw[p7O_J][p7O_MOVE], xN + om->xw[p7O_N][p7O_MOVE]);
185 /* and now xB will carry over into next i, and xC carries over after i=L */
186
187 /* Finally the "lazy F" loop (sensu [Farrar07]). We can often
188 * prove that we don't need to evaluate any D->D paths at all.
189 *
190 * The observation is that if we can show that on the next row,
191 * B->M(i+1,k) paths always dominate M->D->...->D->M(i+1,k) paths
192 * for all k, then we don't need any D->D calculations.
193 *
194 * The test condition is:
195 * max_k D(i,k) + max_k ( TDD(k-2) + TDM(k-1) - TBM(k) ) < xB(i)
196 * So:
197 * max_k (TDD(k-2) + TDM(k-1) - TBM(k)) is precalc'ed in om->dd_bound;
198 * max_k D(i,k) is why we tracked Dmaxv;
199 * xB(i) was just calculated above.
200 */
201 Dmax = esl_vmx_hmax_s16(Dmaxv);
202 if (Dmax + om->ddbound_w > xB)
203 {
204 /* Now we're obligated to do at least one complete DD path to be sure. */
205 /* dcv has carried through from end of q loop above */
206 dcv = vec_sld(negInfv, dcv, 14);
207 tsc = om->twv + 7*Q; /* set tsc to start of the DD's */
208 for (q = 0; q < Q; q++)
209 {
210 DMXo(q) = vec_max(dcv, DMXo(q));
211 dcv = vec_adds(DMXo(q), *tsc); tsc++;
212 }
213
214 /* We may have to do up to three more passes; the check
215 * is for whether crossing a segment boundary can improve
216 * our score.
217 */
218 do {
219 dcv = vec_sld(negInfv, dcv, 14);
220 tsc = om->twv + 7*Q; /* set tsc to start of the DD's */
221 for (q = 0; q < Q; q++)
222 {
223 if (! vec_any_gt(dcv, DMXo(q))) break;
224 DMXo(q) = vec_max(dcv, DMXo(q));
225 dcv = vec_adds(DMXo(q), *tsc); tsc++;
226 }
227 } while (q == Q);
228 }
229 else /* not calculating DD? then just store the last M->D vector calc'ed.*/
230 DMXo(0) = vec_sld(negInfv, dcv, 14);
231
232 #if eslDEBUGLEVEL > 0
233 if (ox->debugging) p7_omx_DumpVFRow(ox, i, xE, 0, xJ, xB, xC);
234 #endif
235 } /* end loop over sequence residues 1..L */
236
237 /* finally C->T */
238 if (xC > -32768)
239 {
240 *ret_sc = (float) xC + (float) om->xw[p7O_C][p7O_MOVE] - (float) om->base_w;
241 /* *ret_sc += L * om->ncj_roundoff; see J4/150 for rationale: superceded by -3.0nat approximation*/
242 *ret_sc /= om->scale_w;
243 *ret_sc -= 3.0; /* the NN/CC/JJ=0,-3nat approximation: see J5/36. That's ~ L \log \frac{L}{L+3}, for our NN,CC,JJ contrib */
244 }
245 else *ret_sc = -eslINFINITY;
246 return eslOK;
247 }
248 /*---------------- end, p7_ViterbiFilter() ----------------------*/
249
250
251
252
253 /* Function: p7_ViterbiFilter_longtarget()
254 * Synopsis: Finds windows within potentially long sequence blocks with Viterbi
255 * scores above threshold (vewy vewy fast, in limited precision)
256 *
257 * Purpose: Calculates an approximation of the Viterbi score for regions
258 * of sequence <dsq>, using optimized profile <om>, and a pre-
259 * allocated one-row DP matrix <ox>, and captures the positions
260 * at which such regions exceed the score required to be
261 * significant in the eyes of the calling function (usually
262 * p=0.001).
263 *
264 * The resulting landmarks are converted to subsequence
265 * windows by the calling function
266 *
267 * The model must be in a local alignment mode; other modes
268 * cannot provide the necessary guarantee of no underflow.
269 *
270 * This is a striped SIMD Viterbi implementation using Intel
271 * VMX integer intrinsics \citep{Farrar07}, in reduced
272 * precision (signed words, 16 bits).
273 *
274 * Args: dsq - digital target sequence, 1..L
275 * L - length of dsq in residues
276 * om - optimized profile
277 * ox - DP matrix
278 * filtersc - null or bias correction, required for translating a P-value threshold into a score threshold
279 * P - p-value below which a region is captured as being above threshold
280 * windowlist - RETURN: array of hit windows (start and end of diagonal) for the above-threshold areas
281 *
282 * Returns: <eslOK> on success;
283 *
284 * Throws: <eslEINVAL> if <ox> allocation is too small, or if
285 * profile isn't in a local alignment mode. (Must be in local
286 * alignment mode because that's what helps us guarantee
287 * limited dynamic range.)
288 *
289 * Xref: See p7_ViterbiFilter()
290 */
291 int
292 p7_ViterbiFilter_longtarget(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox,
293 float filtersc, double P, P7_HMM_WINDOWLIST *windowlist)
294 {
295 vector signed short mpv, dpv, ipv; /* previous row values */
296 vector signed short sv; /* temp storage of 1 curr row value in progress */
297 vector signed short dcv; /* delayed storage of D(i,q+1) */
298 vector signed short xEv; /* E state: keeps max for Mk->E as we go */
299 vector signed short xBv; /* B state: splatted vector of B[i-1] for B->Mk calculations */
300 vector signed short Dmaxv; /* keeps track of maximum D cell on row */
301 int16_t xE, xB, xC, xJ, xN; /* special states' scores */
302 int16_t Dmax; /* maximum D cell score on row */
303 int i; /* counter over sequence positions 1..L */
304 int q; /* counter over vectors 0..nq-1 */
305 int Q = p7O_NQW(om->M); /* segment length: # of vectors */
306 vector signed short *dp = ox->dpw[0]; /* using {MDI}MX(q) macro requires initialization of <dp> */
307 vector signed short *rsc; /* will point at om->ru[x] for residue x[i] */
308 vector signed short *tsc; /* will point into (and step thru) om->tu */
309
310 vector signed short negInfv;
311
312 int16_t sc_thresh;
313 float invP;
314
315 int z;
316 union { vector signed short v; int16_t i[8]; } tmp;
317 windowlist->count = 0;
318
319 /*
320 * In p7_ViterbiFilter, converting from a scaled int Viterbi score
321 * S (aka xE the score getting to state E) to a probability
322 * goes like this:
323 * vsc = S + om->xw[p7O_E][p7O_MOVE] + om->xw[p7O_C][p7O_MOVE] - om->base_w
324 * ret_sc /= om->scale_w;
325 * vsc -= 3.0;
326 * P = esl_gumbel_surv((vfsc - filtersc) / eslCONST_LOG2 , om->evparam[p7_VMU], om->evparam[p7_VLAMBDA]);
327 * and we're computing the threshold vsc, so invert it:
328 * (vsc - filtersc) / eslCONST_LOG2 = esl_gumbel_invsurv( P, om->evparam[p7_VMU], om->evparam[p7_VLAMBDA])
329 * vsc = filtersc + eslCONST_LOG2 * esl_gumbel_invsurv( P, om->evparam[p7_VMU], om->evparam[p7_VLAMBDA])
330 * vsc += 3.0
331 * vsc *= om->scale_w
332 * S = vsc - (float)om->xw[p7O_E][p7O_MOVE] - (float)om->xw[p7O_C][p7O_MOVE] + (float)om->base_w
333 */
334 invP = esl_gumbel_invsurv(P, om->evparam[p7_VMU], om->evparam[p7_VLAMBDA]);
335 sc_thresh = (int) ceil ( ( (filtersc + (eslCONST_LOG2 * invP) + 3.0) * om->scale_w )
336 - (float)om->xw[p7O_E][p7O_MOVE] - (float)om->xw[p7O_C][p7O_MOVE] + (float)om->base_w );
337
338
339 /* Check that the DP matrix is ok for us. */
340 if (Q > ox->allocQ8) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small");
341 if (om->mode != p7_LOCAL && om->mode != p7_UNILOCAL) ESL_EXCEPTION(eslEINVAL, "Fast filter only works for local alignment");
342 ox->M = om->M;
343
344 negInfv = esl_vmx_set_s16((signed short)-32768);
345
346 /* Initialization. In unsigned arithmetic, -infinity is -32768
347 */
348 for (q = 0; q < Q; q++)
349 MMXo(q) = IMXo(q) = DMXo(q) = negInfv;
350 xN = om->base_w;
351 xB = xN + om->xw[p7O_N][p7O_MOVE];
352 xJ = -32768;
353 xC = -32768;
354 xE = -32768;
355
356 #if eslDEBUGLEVEL > 0
357 if (ox->debugging) p7_omx_DumpVFRow(ox, 0, xE, 0, xJ, xB, xC); /* first 0 is <rowi>: do header. second 0 is xN: always 0 here. */
358 #endif
359
360 for (i = 1; i <= L; i++)
361 {
362 rsc = om->rwv[dsq[i]];
363 tsc = om->twv;
364 dcv = negInfv; /* "-infinity" */
365 xEv = negInfv;
366 Dmaxv = negInfv;
367 xBv = esl_vmx_set_s16(xB);
368
369 /* Right shifts by 1 value (2 bytes). 4,8,12,x becomes x,4,8,12.
370 * Because ia32 is littlendian, this means a left bit shift.
371 * Zeros shift on automatically; replace it with -32768.
372 */
373 mpv = MMXo(Q-1); mpv = vec_sld(negInfv, mpv, 14);
374 dpv = DMXo(Q-1); dpv = vec_sld(negInfv, dpv, 14);
375 ipv = IMXo(Q-1); ipv = vec_sld(negInfv, ipv, 14);
376
377 for (q = 0; q < Q; q++)
378 {
379 /* Calculate new MMXo(i,q); don't store it yet, hold it in sv. */
380 sv = vec_adds(xBv, *tsc); tsc++;
381 sv = vec_max (sv, vec_adds(mpv, *tsc)); tsc++;
382 sv = vec_max (sv, vec_adds(ipv, *tsc)); tsc++;
383 sv = vec_max (sv, vec_adds(dpv, *tsc)); tsc++;
384 sv = vec_adds(sv, *rsc); rsc++;
385 xEv = vec_max(xEv, sv);
386
387 /* Load {MDI}(i-1,q) into mpv, dpv, ipv;
388 * {MDI}MX(q) is then the current, not the prev row
389 */
390 mpv = MMXo(q);
391 dpv = DMXo(q);
392 ipv = IMXo(q);
393
394 /* Do the delayed stores of {MD}(i,q) now that memory is usable */
395 MMXo(q) = sv;
396 DMXo(q) = dcv;
397
398 /* Calculate the next D(i,q+1) partially: M->D only;
399 * delay storage, holding it in dcv
400 */
401 dcv = vec_adds(sv, *tsc); tsc++;
402 Dmaxv = vec_max(dcv, Dmaxv);
403
404 /* Calculate and store I(i,q) */
405 sv = vec_adds(mpv, *tsc); tsc++;
406 IMXo(q)= vec_max(sv, vec_adds(ipv, *tsc)); tsc++;
407 }
408
409 /* Now the "special" states, which start from Mk->E (->C, ->J->B) */
410 xE = esl_vmx_hmax_s16(xEv);
411
412 if (xE >= sc_thresh) {
413 //hit score threshold. Add a window to the list, then reset scores.
414
415 /* Unpack and unstripe, then find the position responsible for the hit */
416
417 for (q = 0; q < Q; q++) {
418 tmp.v = MMXo(q);
419 for (z = 0; z < 8; z++) { // unstripe
420 if ( tmp.i[z] == xE && (q+Q*z+1) <= om->M) {
421 // (q+Q*z+1) is the model position k at which the xE score is found
422 p7_hmmwindow_new(windowlist, 0, i, i-1, (q+Q*z+1), 1, 0.0, p7_NOCOMPLEMENT, L );
423 }
424 }
425 MMXo(q) = IMXo(q) = DMXo(q) = negInfv; //reset score to start search for next vit window.
426 }
427
428 } else {
429
430 xN = xN + om->xw[p7O_N][p7O_LOOP];
431 xC = ESL_MAX(xC + om->xw[p7O_C][p7O_LOOP], xE + om->xw[p7O_E][p7O_MOVE]);
432 xJ = ESL_MAX(xJ + om->xw[p7O_J][p7O_LOOP], xE + om->xw[p7O_E][p7O_LOOP]);
433 xB = ESL_MAX(xJ + om->xw[p7O_J][p7O_MOVE], xN + om->xw[p7O_N][p7O_MOVE]);
434 /* and now xB will carry over into next i, and xC carries over after i=L */
435
436 /* Finally the "lazy F" loop (sensu [Farrar07]). We can often
437 * prove that we don't need to evaluate any D->D paths at all.
438 *
439 * The observation is that if we can show that on the next row,
440 * B->M(i+1,k) paths always dominate M->D->...->D->M(i+1,k) paths
441 * for all k, then we don't need any D->D calculations.
442 *
443 * The test condition is:
444 * max_k D(i,k) + max_k ( TDD(k-2) + TDM(k-1) - TBM(k) ) < xB(i)
445 * So:
446 * max_k (TDD(k-2) + TDM(k-1) - TBM(k)) is precalc'ed in om->dd_bound;
447 * max_k D(i,k) is why we tracked Dmaxv;
448 * xB(i) was just calculated above.
449 */
450 Dmax = esl_vmx_hmax_s16(Dmaxv);
451 if (Dmax + om->ddbound_w > xB)
452 {
453 /* Now we're obligated to do at least one complete DD path to be sure. */
454 /* dcv has carried through from end of q loop above */
455 dcv = vec_sld(negInfv, dcv, 14);
456 tsc = om->twv + 7*Q; /* set tsc to start of the DD's */
457 for (q = 0; q < Q; q++)
458 {
459 DMXo(q) = vec_max(dcv, DMXo(q));
460 dcv = vec_adds(DMXo(q), *tsc); tsc++;
461 }
462
463 /* We may have to do up to three more passes; the check
464 * is for whether crossing a segment boundary can improve
465 * our score.
466 */
467 do {
468 dcv = vec_sld(negInfv, dcv, 14);
469 tsc = om->twv + 7*Q; /* set tsc to start of the DD's */
470 for (q = 0; q < Q; q++)
471 {
472 if (! vec_any_gt(dcv, DMXo(q))) break;
473 DMXo(q) = vec_max(dcv, DMXo(q));
474 dcv = vec_adds(DMXo(q), *tsc); tsc++;
475 }
476 } while (q == Q);
477 }
478 else /* not calculating DD? then just store the last M->D vector calc'ed.*/
479 DMXo(0) = vec_sld(negInfv, dcv, 14);
480
481 #if eslDEBUGLEVEL > 0
482 if (ox->debugging) p7_omx_DumpVFRow(ox, i, xE, 0, xJ, xB, xC);
483 #endif
484
485 }
486 } /* end loop over sequence residues 1..L */
487
488
489 return eslOK;
490 }
491 /*---------------- end, p7_ViterbiFilter() ----------------------*/
492
493
494
495
496
497 /*****************************************************************
498 * 2. Benchmark driver.
499 *****************************************************************/
500 #ifdef p7VITFILTER_BENCHMARK
501 /* -c, -x are used for debugging, testing; see msvfilter.c for explanation */
502
503 /*
504 gcc -o vitfilter_benchmark -std=gnu99 -g -Wall -maltivec -I.. -L.. -I../../easel -L../../easel -Dp7VITFILTER_BENCHMARK vitfilter.c -lhmmer -leasel -lm
505 icc -o vitfilter_benchmark -O3 -static -I.. -L.. -I../../easel -L../../easel -Dp7VITFILTER_BENCHMARK vitfilter.c -lhmmer -leasel -lm
506
507 ./benchmark-vitfilter <hmmfile> runs benchmark
508 ./benchmark-vitfilter -N100 -c <hmmfile> compare scores to generic impl
509 ./benchmark-vitfilter -N100 -x <hmmfile> compare scores to exact emulation
510 */
511 #include <p7_config.h>
512
513 #include "easel.h"
514 #include "esl_alphabet.h"
515 #include "esl_getopts.h"
516 #include "esl_random.h"
517 #include "esl_randomseq.h"
518 #include "esl_stopwatch.h"
519
520 #include "hmmer.h"
521 #include "impl_vmx.h"
522
523 static ESL_OPTIONS options[] = {
524 /* name type default env range toggles reqs incomp help docgroup*/
525 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
526 { "-c", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-x", "compare scores to generic implementation (debug)", 0 },
527 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
528 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-c", "equate scores to trusted implementation (debug)", 0 },
529 { "-L", eslARG_INT, "400", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
530 { "-N", eslARG_INT, "50000", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
531 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
532 };
533 static char usage[] = "[-options] <hmmfile>";
534 static char banner[] = "benchmark driver for Viterbi filter";
535
536
537 int
538 main(int argc, char **argv)
539 {
540 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
541 char *hmmfile = esl_opt_GetArg(go, 1);
542 ESL_STOPWATCH *w = esl_stopwatch_Create();
543 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
544 ESL_ALPHABET *abc = NULL;
545 P7_HMMFILE *hfp = NULL;
546 P7_HMM *hmm = NULL;
547 P7_BG *bg = NULL;
548 P7_PROFILE *gm = NULL;
549 P7_OPROFILE *om = NULL;
550 P7_OMX *ox = NULL;
551 P7_GMX *gx = NULL;
552 int L = esl_opt_GetInteger(go, "-L");
553 int N = esl_opt_GetInteger(go, "-N");
554 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
555 int i;
556 float sc1, sc2;
557 double base_time, bench_time, Mcs;
558
559 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
560 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
561
562 bg = p7_bg_Create(abc);
563 p7_bg_SetLength(bg, L);
564 gm = p7_profile_Create(hmm->M, abc);
565 p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL);
566 om = p7_oprofile_Create(gm->M, abc);
567 p7_oprofile_Convert(gm, om);
568 p7_oprofile_ReconfigLength(om, L);
569
570 if (esl_opt_GetBoolean(go, "-x")) p7_profile_SameAsVF(om, gm);
571
572 ox = p7_omx_Create(gm->M, 0, 0);
573 gx = p7_gmx_Create(gm->M, L);
574
575 /* Get a baseline time: how long it takes just to generate the sequences */
576 esl_stopwatch_Start(w);
577 for (i = 0; i < N; i++)
578 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
579 esl_stopwatch_Stop(w);
580 base_time = w->user;
581
582 /* Run the benchmark */
583 esl_stopwatch_Start(w);
584 for (i = 0; i < N; i++)
585 {
586 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
587 p7_ViterbiFilter(dsq, L, om, ox, &sc1);
588
589 if (esl_opt_GetBoolean(go, "-c"))
590 {
591 p7_GViterbi(dsq, L, gm, gx, &sc2);
592 printf("%.4f %.4f\n", sc1, sc2);
593 }
594
595 if (esl_opt_GetBoolean(go, "-x"))
596 {
597 p7_GViterbi(dsq, L, gm, gx, &sc2);
598 sc2 /= om->scale_w;
599 if (om->mode == p7_UNILOCAL) sc2 -= 2.0; /* that's ~ L \log \frac{L}{L+2}, for our NN,CC,JJ */
600 else if (om->mode == p7_LOCAL) sc2 -= 3.0; /* that's ~ L \log \frac{L}{L+3}, for our NN,CC,JJ */
601 printf("%.4f %.4f\n", sc1, sc2);
602 }
603 }
604 esl_stopwatch_Stop(w);
605 bench_time = w->user - base_time;
606 Mcs = (double) N * (double) L * (double) gm->M * 1e-6 / (double) bench_time;
607 esl_stopwatch_Display(stdout, w, "# CPU time: ");
608 printf("# M = %d\n", gm->M);
609 printf("# %.1f Mc/s\n", Mcs);
610
611 free(dsq);
612 p7_omx_Destroy(ox);
613 p7_gmx_Destroy(gx);
614 p7_oprofile_Destroy(om);
615 p7_profile_Destroy(gm);
616 p7_bg_Destroy(bg);
617 p7_hmm_Destroy(hmm);
618 p7_hmmfile_Close(hfp);
619 esl_alphabet_Destroy(abc);
620 esl_stopwatch_Destroy(w);
621 esl_randomness_Destroy(r);
622 esl_getopts_Destroy(go);
623 return 0;
624 }
625 #endif /*p7VITFILTER_BENCHMARK*/
626 /*---------------- end, benchmark driver ------------------------*/
627
628
629
630
631 /*****************************************************************
632 * 3. Unit tests.
633 *****************************************************************/
634 #ifdef p7VITFILTER_TESTDRIVE
635 #include "esl_random.h"
636 #include "esl_randomseq.h"
637
638 /* ViterbiFilter() unit test
639 *
640 * We can check that scores are identical (within machine error) to
641 * scores of generic DP with scores rounded the same way. Do this for
642 * a random model of length <M>, for <N> test sequences of length <L>.
643 *
644 * We assume that we don't accidentally generate a high-scoring random
645 * sequence that overflows ViterbiFilter()'s limited range.
646 *
647 */
648 static void
649 utest_viterbi_filter(ESL_RANDOMNESS *r, ESL_ALPHABET *abc, P7_BG *bg, int M, int L, int N)
650 {
651 P7_HMM *hmm = NULL;
652 P7_PROFILE *gm = NULL;
653 P7_OPROFILE *om = NULL;
654 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
655 P7_OMX *ox = p7_omx_Create(M, 0, 0);
656 P7_GMX *gx = p7_gmx_Create(M, L);
657 float sc1, sc2;
658
659 p7_oprofile_Sample(r, abc, bg, M, L, &hmm, &gm, &om);
660 p7_profile_SameAsVF(om, gm); /* round and scale the scores in <gm> the same as in <om> */
661
662 #if 0
663 p7_oprofile_Dump(stdout, om); // dumps the optimized profile
664 p7_omx_SetDumpMode(stdout, ox, TRUE); // makes the fast DP algorithms dump their matrices
665 #endif
666
667 while (N--)
668 {
669 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
670
671 p7_ViterbiFilter(dsq, L, om, ox, &sc1);
672 p7_GViterbi (dsq, L, gm, gx, &sc2);
673
674 #if 0
675 p7_gmx_Dump(stdout, gx, p7_DEFAULT); // dumps a generic DP matrix
676 #endif
677
678 sc2 /= om->scale_w;
679 sc2 -= 3.0;
680
681 if (fabs(sc1-sc2) > 0.001) esl_fatal("viterbi filter unit test failed: scores differ (%.2f, %.2f)", sc1, sc2);
682 }
683
684 free(dsq);
685 p7_hmm_Destroy(hmm);
686 p7_omx_Destroy(ox);
687 p7_gmx_Destroy(gx);
688 p7_profile_Destroy(gm);
689 p7_oprofile_Destroy(om);
690 }
691 #endif /*p7VITFILTER_TESTDRIVE*/
692
693
694 /*****************************************************************
695 * 4. Test driver
696 *****************************************************************/
697 #ifdef p7VITFILTER_TESTDRIVE
698 /*
699 gcc -g -Wall -maltivec -std=gnu99 -I.. -L.. -I../../easel -L../../easel -o vitfilter_utest -Dp7VITFILTER_TESTDRIVE vitfilter.c -lhmmer -leasel -lm
700 ./vitfilter_utest
701 */
702 #include <p7_config.h>
703
704 #include "easel.h"
705 #include "esl_alphabet.h"
706 #include "esl_getopts.h"
707 #include "esl_random.h"
708 #include "esl_randomseq.h"
709
710 #include "hmmer.h"
711 #include "impl_vmx.h"
712
713 static ESL_OPTIONS options[] = {
714 /* name type default env range toggles reqs incomp help docgroup*/
715 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
716 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
717 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose", 0 },
718 { "-L", eslARG_INT, "200", NULL, NULL, NULL, NULL, NULL, "size of random sequences to sample", 0 },
719 { "-M", eslARG_INT, "145", NULL, NULL, NULL, NULL, NULL, "size of random models to sample", 0 },
720 { "-N", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "number of random sequences to sample", 0 },
721 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
722 };
723 static char usage[] = "[-options]";
724 static char banner[] = "test driver for the VMX implementation";
725
726 int
727 main(int argc, char **argv)
728 {
729 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
730 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
731 ESL_ALPHABET *abc = NULL;
732 P7_BG *bg = NULL;
733 int M = esl_opt_GetInteger(go, "-M");
734 int L = esl_opt_GetInteger(go, "-L");
735 int N = esl_opt_GetInteger(go, "-N");
736
737 /* First round of tests for DNA alphabets. */
738 if ((abc = esl_alphabet_Create(eslDNA)) == NULL) esl_fatal("failed to create alphabet");
739 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
740
741 if (esl_opt_GetBoolean(go, "-v")) printf("ViterbiFilter() tests, DNA\n");
742 utest_viterbi_filter(r, abc, bg, M, L, N);
743 utest_viterbi_filter(r, abc, bg, 1, L, 10);
744 utest_viterbi_filter(r, abc, bg, M, 1, 10);
745
746 esl_alphabet_Destroy(abc);
747 p7_bg_Destroy(bg);
748
749 /* Second round of tests for amino alphabets. */
750 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal("failed to create alphabet");
751 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
752
753 if (esl_opt_GetBoolean(go, "-v")) printf("ViterbiFilter() tests, protein\n");
754 utest_viterbi_filter(r, abc, bg, M, L, N);
755 utest_viterbi_filter(r, abc, bg, 1, L, 10);
756 utest_viterbi_filter(r, abc, bg, M, 1, 10);
757
758 esl_alphabet_Destroy(abc);
759 p7_bg_Destroy(bg);
760
761 esl_getopts_Destroy(go);
762 esl_randomness_Destroy(r);
763 return eslOK;
764 }
765 #endif /*VITFILTER_TESTDRIVE*/
766 /*---------------- end, test driver -----------------------------*/
767
768
769
770 /*****************************************************************
771 * 5. Example
772 *****************************************************************/
773 #ifdef p7VITFILTER_EXAMPLE
774 /* A minimal example.
775 Also useful for debugging on small HMMs and sequences.
776
777 gcc -g -Wall -maltivec -std=gnu99 -I.. -L.. -I../../easel -L../../easel -o vitfilter_example -Dp7VITFILTER_EXAMPLE vitfilter.c -lhmmer -leasel -lm
778 ./vitfilter_example <hmmfile> <seqfile>
779 */
780 #include <p7_config.h>
781
782 #include "easel.h"
783 #include "esl_alphabet.h"
784 #include "esl_getopts.h"
785 #include "esl_gumbel.h"
786 #include "esl_sq.h"
787 #include "esl_sqio.h"
788
789 #include "hmmer.h"
790 #include "impl_vmx.h"
791
792 static ESL_OPTIONS options[] = {
793 /* name type default env range toggles reqs incomp help docgroup*/
794 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
795 { "-1", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in one line awkable format", 0 },
796 { "-P", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in profmark format", 0 },
797 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
798 };
799 static char usage[] = "[-options] <hmmfile> <seqfile>";
800 static char banner[] = "example of Viterbi filter algorithm";
801
802 int
803 main(int argc, char **argv)
804 {
805 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 2, argc, argv, banner, usage);
806 char *hmmfile = esl_opt_GetArg(go, 1);
807 char *seqfile = esl_opt_GetArg(go, 2);
808 ESL_ALPHABET *abc = NULL;
809 P7_HMMFILE *hfp = NULL;
810 P7_HMM *hmm = NULL;
811 P7_BG *bg = NULL;
812 P7_PROFILE *gm = NULL;
813 P7_OPROFILE *om = NULL;
814 P7_OMX *ox = NULL;
815 P7_GMX *gx = NULL;
816 ESL_SQ *sq = NULL;
817 ESL_SQFILE *sqfp = NULL;
818 int format = eslSQFILE_UNKNOWN;
819 float vfraw, nullsc, vfscore;
820 float graw, gscore;
821 double P, gP;
822 int status;
823
824 /* Read in one HMM */
825 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
826 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
827
828 /* Read in one sequence */
829 sq = esl_sq_CreateDigital(abc);
830 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
831 if (status == eslENOTFOUND) p7_Fail("No such file.");
832 else if (status == eslEFORMAT) p7_Fail("Format unrecognized.");
833 else if (status == eslEINVAL) p7_Fail("Can't autodetect stdin or .gz.");
834 else if (status != eslOK) p7_Fail("Open failed, code %d.", status);
835
836 /* create default null model, then create and optimize profile */
837 bg = p7_bg_Create(abc);
838 p7_bg_SetLength(bg, sq->n);
839 gm = p7_profile_Create(hmm->M, abc);
840 p7_ProfileConfig(hmm, bg, gm, sq->n, p7_LOCAL);
841 om = p7_oprofile_Create(gm->M, abc);
842 p7_oprofile_Convert(gm, om);
843
844 /* allocate DP matrices, both a generic and an optimized one */
845 ox = p7_omx_Create(gm->M, 0, sq->n);
846 gx = p7_gmx_Create(gm->M, sq->n);
847
848 /* Useful to place and compile in for debugging:
849 p7_oprofile_Dump(stdout, om); dumps the optimized profile
850 p7_omx_SetDumpMode(ox, TRUE); makes the fast DP algorithms dump their matrices
851 p7_gmx_Dump(stdout, gx, p7_DEFAULT); dumps a generic DP matrix
852 */
853
854 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
855 {
856 p7_oprofile_ReconfigLength(om, sq->n);
857 p7_ReconfigLength(gm, sq->n);
858 p7_bg_SetLength(bg, sq->n);
859 p7_omx_GrowTo(ox, om->M, 0, sq->n);
860 p7_gmx_GrowTo(gx, gm->M, sq->n);
861
862 p7_ViterbiFilter (sq->dsq, sq->n, om, ox, &vfraw);
863 p7_bg_NullOne (bg, sq->dsq, sq->n, &nullsc);
864 vfscore = (vfraw - nullsc) / eslCONST_LOG2;
865 P = esl_gumbel_surv(vfscore, om->evparam[p7_VMU], om->evparam[p7_VLAMBDA]);
866
867 p7_GViterbi (sq->dsq, sq->n, gm, gx, &graw);
868 gscore = (graw - nullsc) / eslCONST_LOG2;
869 gP = esl_gumbel_surv(gscore, gm->evparam[p7_VMU], gm->evparam[p7_VLAMBDA]);
870
871 if (esl_opt_GetBoolean(go, "-1"))
872 {
873 printf("%-30s\t%-20s\t%9.2g\t%7.2f\t%9.2g\t%7.2f\n", sq->name, hmm->name, P, vfscore, gP, gscore);
874 }
875 else if (esl_opt_GetBoolean(go, "-P"))
876 { /* output suitable for direct use in profmark benchmark postprocessors: */
877 printf("%g\t%.2f\t%s\t%s\n", P, vfscore, sq->name, hmm->name);
878 }
879 else
880 {
881 printf("target sequence: %s\n", sq->name);
882 printf("vit filter raw score: %.2f nats\n", vfraw);
883 printf("null score: %.2f nats\n", nullsc);
884 printf("per-seq score: %.2f bits\n", vfscore);
885 printf("P-value: %g\n", P);
886 printf("GViterbi raw score: %.2f nats\n", graw);
887 printf("GViterbi seq score: %.2f bits\n", gscore);
888 printf("GViterbi P-value: %g\n", gP);
889 }
890
891 esl_sq_Reuse(sq);
892 }
893
894 /* cleanup */
895 esl_sq_Destroy(sq);
896 esl_sqfile_Close(sqfp);
897 p7_omx_Destroy(ox);
898 p7_gmx_Destroy(gx);
899 p7_oprofile_Destroy(om);
900 p7_profile_Destroy(gm);
901 p7_bg_Destroy(bg);
902 p7_hmm_Destroy(hmm);
903 p7_hmmfile_Close(hfp);
904 esl_alphabet_Destroy(abc);
905 esl_getopts_Destroy(go);
906 return 0;
907 }
908 #endif /*p7VITFILTER_EXAMPLE*/
909 /*-------------------- end, example -----------------------------*/
910
911