Debian Codegraph @

hmmer/src/impl_neon/vitfilter.c

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