Debian Codegraph @

hmmer/src/impl_sse/msvfilter.c

raw symbols SCIP
1 /* The MSV filter implementation; SSE version.
2 *
3 * A "filter" is a one-row, O(M), DP implementation that calculates an
4 * approximated nat score (i.e. in limited precision - here, uchar)
5 * and may have limited numeric range. It will return <eslERANGE> if
6 * its numeric range is exceeded, in which case the caller will have
7 * to obtain the score by another (probably slower) method.
8 *
9 * Contents:
10 * 1. p7_MSVFilter() implementation
11 * 2. Benchmark driver
12 * 3. Unit tests
13 * 4. Test driver
14 * 5. Example
15 *
16 * SRE, Sun Nov 25 11:26:48 2007 [Casa de Gatos]
17 */
18 #include <p7_config.h>
19
20 #include <stdio.h>
21 #include <math.h>
22
23 #include <xmmintrin.h> /* SSE */
24 #include <emmintrin.h> /* SSE2 */
25
26 #include "easel.h"
27 #include "esl_sse.h"
28 #include "esl_gumbel.h"
29
30 #include "hmmer.h"
31 #include "impl_sse.h"
32
33 /*****************************************************************
34 * 1. The p7_MSVFilter() DP implementation.
35 *****************************************************************/
36
37 /* Function: p7_MSVFilter()
38 * Synopsis: Calculates MSV score, vewy vewy fast, in limited precision.
39 * Incept: SRE, Wed Dec 26 15:12:25 2007 [Janelia]
40 *
41 * Purpose: Calculates an approximation of the MSV score for sequence
42 * <dsq> of length <L> residues, using optimized profile <om>,
43 * and a preallocated one-row DP matrix <ox>. Return the
44 * estimated MSV score (in nats) in <ret_sc>.
45 *
46 * Score may overflow (and will, on high-scoring
47 * sequences), but will not underflow.
48 *
49 * The model may be in any mode, because only its match
50 * emission scores will be used. The MSV filter inherently
51 * assumes a multihit local mode, and uses its own special
52 * state transition scores, not the scores in the profile.
53 *
54 * Args: dsq - digital target sequence, 1..L
55 * L - length of dsq in residues
56 * om - optimized profile
57 * ox - DP matrix
58 * ret_sc - RETURN: MSV score (in nats)
59 *
60 * Note: We misuse the matrix <ox> here, using only a third of the
61 * first dp row, accessing it as <dp[0..Q-1]> rather than
62 * in triplets via <{MDI}MX(q)> macros, since we only need
63 * to store M state values. We know that if <ox> was big
64 * enough for normal DP calculations, it must be big enough
65 * to hold the MSVFilter calculation.
66 *
67 * Returns: <eslOK> on success.
68 * <eslERANGE> if the score overflows the limited range; in
69 * this case, this is a high-scoring hit.
70 *
71 * Throws: <eslEINVAL> if <ox> allocation is too small.
72 */
73 int
74 p7_MSVFilter(const ESL_DSQ *dsq, int L, const P7_OPROFILE *om, P7_OMX *ox, float *ret_sc)
75 {
76 register __m128i mpv; /* previous row values */
77 register __m128i xEv; /* E state: keeps max for Mk->E as we go */
78 register __m128i xBv; /* B state: splatted vector of B[i-1] for B->Mk calculations */
79 register __m128i sv; /* temp storage of 1 curr row value in progress */
80 register __m128i biasv; /* emission bias in a vector */
81 uint8_t xJ; /* special states' scores */
82 int i; /* counter over sequence positions 1..L */
83 int q; /* counter over vectors 0..nq-1 */
84 int Q = p7O_NQB(om->M); /* segment length: # of vectors */
85 __m128i *dp = ox->dpb[0]; /* we're going to use dp[0][0..q..Q-1], not {MDI}MX(q) macros*/
86 __m128i *rsc; /* will point at om->rbv[x] for residue x[i] */
87
88 __m128i xJv; /* vector for states score */
89 __m128i tjbmv; /* vector for cost of moving from either J or N through B to an M state */
90 __m128i tecv; /* vector for E->C cost */
91 __m128i basev; /* offset for scores */
92 __m128i ceilingv; /* saturateed simd value used to test for overflow */
93 __m128i tempv; /* work vector */
94
95 int cmp;
96 int status = eslOK;
97
98 /* Check that the DP matrix is ok for us. */
99 if (Q > ox->allocQ16) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small");
100 ox->M = om->M;
101
102 /* Try highly optimized ssv filter first */
103 status = p7_SSVFilter(dsq, L, om, ret_sc);
104 if (status != eslENORESULT) return status;
105
106 /* Initialization. In offset unsigned arithmetic, -infinity is 0, and 0 is om->base.
107 */
108 biasv = _mm_set1_epi8((int8_t) om->bias_b); /* yes, you can set1() an unsigned char vector this way */
109 for (q = 0; q < Q; q++) dp[q] = _mm_setzero_si128();
110 xJ = 0;
111
112 /* saturate simd register for overflow test */
113 ceilingv = _mm_cmpeq_epi8(biasv, biasv);
114 basev = _mm_set1_epi8((int8_t) om->base_b);
115
116 tjbmv = _mm_set1_epi8((int8_t) om->tjb_b + (int8_t) om->tbm_b);
117 tecv = _mm_set1_epi8((int8_t) om->tec_b);
118
119 xJv = _mm_subs_epu8(biasv, biasv);
120 xBv = _mm_subs_epu8(basev, tjbmv);
121
122 #if eslDEBUGLEVEL > 0
123 if (ox->debugging)
124 {
125 uint8_t xB;
126 xB = _mm_extract_epi16(xBv, 0);
127 xJ = _mm_extract_epi16(xJv, 0);
128 p7_omx_DumpMFRow(ox, 0, 0, 0, xJ, xB, xJ);
129 }
130 #endif
131
132 for (i = 1; i <= L; i++)
133 {
134 rsc = om->rbv[dsq[i]];
135 xEv = _mm_setzero_si128();
136
137 /* Right shifts by 1 byte. 4,8,12,x becomes x,4,8,12.
138 * Because ia32 is littlendian, this means a left bit shift.
139 * Zeros shift on automatically, which is our -infinity.
140 */
141 mpv = _mm_slli_si128(dp[Q-1], 1);
142 for (q = 0; q < Q; q++)
143 {
144 /* Calculate new MMXo(i,q); don't store it yet, hold it in sv. */
145 sv = _mm_max_epu8(mpv, xBv);
146 sv = _mm_adds_epu8(sv, biasv);
147 sv = _mm_subs_epu8(sv, *rsc); rsc++;
148 xEv = _mm_max_epu8(xEv, sv);
149
150 mpv = dp[q]; /* Load {MDI}(i-1,q) into mpv */
151 dp[q] = sv; /* Do delayed store of M(i,q) now that memory is usable */
152 }
153
154 /* test for the overflow condition */
155 tempv = _mm_adds_epu8(xEv, biasv);
156 tempv = _mm_cmpeq_epi8(tempv, ceilingv);
157 cmp = _mm_movemask_epi8(tempv);
158
159 /* Now the "special" states, which start from Mk->E (->C, ->J->B)
160 * Use shuffles instead of shifts so when the last max has completed,
161 * the last four elements of the simd register will contain the
162 * max value. Then the last shuffle will broadcast the max value
163 * to all simd elements.
164 */
165 tempv = _mm_shuffle_epi32(xEv, _MM_SHUFFLE(2, 3, 0, 1));
166 xEv = _mm_max_epu8(xEv, tempv);
167 tempv = _mm_shuffle_epi32(xEv, _MM_SHUFFLE(0, 1, 2, 3));
168 xEv = _mm_max_epu8(xEv, tempv);
169 tempv = _mm_shufflelo_epi16(xEv, _MM_SHUFFLE(2, 3, 0, 1));
170 xEv = _mm_max_epu8(xEv, tempv);
171 tempv = _mm_srli_si128(xEv, 1);
172 xEv = _mm_max_epu8(xEv, tempv);
173 xEv = _mm_shuffle_epi32(xEv, _MM_SHUFFLE(0, 0, 0, 0));
174
175 /* immediately detect overflow */
176 if (cmp != 0x0000)
177 {
178 *ret_sc = eslINFINITY;
179 return eslERANGE;
180 }
181
182 xEv = _mm_subs_epu8(xEv, tecv);
183 xJv = _mm_max_epu8(xJv,xEv);
184
185 xBv = _mm_max_epu8(basev, xJv);
186 xBv = _mm_subs_epu8(xBv, tjbmv);
187
188 #if eslDEBUGLEVEL > 0
189 if (ox->debugging)
190 {
191 uint8_t xB, xE;
192 xB = _mm_extract_epi16(xBv, 0);
193 xE = _mm_extract_epi16(xEv, 0);
194 xJ = _mm_extract_epi16(xJv, 0);
195 p7_omx_DumpMFRow(ox, i, xE, 0, xJ, xB, xJ);
196 }
197 #endif
198 } /* end loop over sequence residues 1..L */
199
200 xJ = (uint8_t) _mm_extract_epi16(xJv, 0);
201
202 /* finally C->T, and add our missing precision on the NN,CC,JJ back */
203 *ret_sc = ((float) (xJ - om->tjb_b) - (float) om->base_b);
204 *ret_sc /= om->scale_b;
205 *ret_sc -= 3.0; /* that's ~ L \log \frac{L}{L+3}, for our NN,CC,JJ */
206
207 return eslOK;
208 }
209 /*------------------ end, p7_MSVFilter() ------------------------*/
210
211
212
213 /* Function: p7_SSVFilter_longtarget()
214 * Synopsis: Finds windows with SSV scores above some threshold (vewy vewy fast, in limited precision)
215 *
216 * Purpose: Calculates an approximation of the SSV (single ungapped diagonal)
217 * score for regions of sequence <dsq> of length <L> residues, using
218 * optimized profile <om>, and a preallocated one-row DP matrix <ox>,
219 * and captures the positions at which such regions exceed the score
220 * required to be significant in the eyes of the calling function,
221 * which depends on the <bg> and <p> (usually p=0.02 for nhmmer).
222 * Note that this variant performs only SSV computations, never
223 * passing through the J state - the score required to pass SSV at
224 * the default threshold (or less restrictive) is sufficient to
225 * pass MSV in essentially all DNA models we've tested.
226 *
227 * Above-threshold diagonals are captured into a preallocated list
228 * <windowlist>. Rather than simply capturing positions at which a
229 * score threshold is reached, this function establishes windows
230 * around those high-scoring positions, using scores in <msvdata>.
231 * These windows can be merged by the calling function.
232 *
233 *
234 * Args: dsq - digital target sequence, 1..L
235 * L - length of dsq in residues
236 * om - optimized profile
237 * ox - DP matrix
238 * msvdata - compact representation of substitution scores, for backtracking diagonals
239 * bg - the background model, required for translating a P-value threshold into a score threshold
240 * P - p-value below which a region is captured as being above threshold
241 * windowlist - preallocated container for all hits (resized if necessary)
242 *
243 *
244 * Note: We misuse the matrix <ox> here, using only a third of the
245 * first dp row, accessing it as <dp[0..Q-1]> rather than
246 * in triplets via <{MDI}MX(q)> macros, since we only need
247 * to store M state values. We know that if <ox> was big
248 * enough for normal DP calculations, it must be big enough
249 * to hold the MSVFilter calculation.
250 *
251 * Returns: <eslOK> on success.
252 *
253 * Throws: <eslEINVAL> if <ox> allocation is too small.
254 */
255 int
256 p7_SSVFilter_longtarget(const ESL_DSQ *dsq, int L, P7_OPROFILE *om, P7_OMX *ox, const P7_SCOREDATA *ssvdata,
257 P7_BG *bg, double P, P7_HMM_WINDOWLIST *windowlist)
258 {
259
260 register __m128i mpv; /* previous row values */
261 register __m128i xEv; /* E state: keeps max for Mk->E for a single iteration */
262 register __m128i xBv; /* B state: splatted vector of B[i-1] for B->Mk calculations */
263 register __m128i sv; /* temp storage of 1 curr row value in progress */
264 register __m128i biasv; /* emission bias in a vector */
265 int i; /* counter over sequence positions 1..L */
266 int q; /* counter over vectors 0..nq-1 */
267 int Q = p7O_NQB(om->M); /* segment length: # of vectors */
268 __m128i *dp = ox->dpb[0]; /* we're going to use dp[0][0..q..Q-1], not {MDI}MX(q) macros*/
269 __m128i *rsc; /* will point at om->rbv[x] for residue x[i] */
270 __m128i tjbmv; /* vector for J->B move cost + B->M move costs */
271 __m128i basev; /* offset for scores */
272 __m128i ceilingv; /* saturated simd value used to test for overflow */
273 __m128i tempv; /* work vector */
274 int cmp;
275 int k;
276 int n;
277 int end;
278 int rem_sc;
279 int start;
280 int target_end;
281 int target_start;
282 int max_end;
283 int max_sc;
284 int sc;
285 int pos_since_max;
286 float ret_sc;
287
288 union { __m128i v; uint8_t b[16]; } u;
289
290 /*
291 * Computing the score required to let P meet the F1 prob threshold
292 * In original code, converting from a scaled int MSV
293 * score S (the score getting to state E) to a probability goes like this:
294 * usc = S - om->tec_b - om->tjb_b - om->base_b;
295 * usc /= om->scale_b;
296 * usc -= 3.0;
297 * P = f ( (usc - nullsc) / eslCONST_LOG2 , mu, lambda)
298 * and we're computing the threshold usc, so reverse it:
299 * (usc - nullsc) / eslCONST_LOG2 = inv_f( P, mu, lambda)
300 * usc = nullsc + eslCONST_LOG2 * inv_f( P, mu, lambda)
301 * usc += 3
302 * usc *= om->scale_b
303 * S = usc + om->tec_b + om->tjb_b + om->base_b
304 *
305 * Here, I compute threshold with length model based on max_length. Doesn't
306 * matter much - in any case, both the bg and om models will change with roughly
307 * 1 bit for each doubling of the length model, so they offset.
308 */
309 float nullsc;
310 __m128i sc_threshv;
311 uint8_t sc_thresh;
312 float invP = esl_gumbel_invsurv(P, om->evparam[p7_MMU], om->evparam[p7_MLAMBDA]);
313
314
315 /* Check that the DP matrix is ok for us. */
316 if (Q > ox->allocQ16) ESL_EXCEPTION(eslEINVAL, "DP matrix allocated too small");
317 ox->M = om->M;
318
319
320 p7_bg_SetLength(bg, om->max_length);
321 p7_oprofile_ReconfigMSVLength(om, om->max_length);
322 p7_bg_NullOne (bg, dsq, om->max_length, &nullsc);
323
324 sc_thresh = (int) ceil( ( ( nullsc + (invP * eslCONST_LOG2) + 3.0 ) * om->scale_b ) + om->base_b + om->tec_b + om->tjb_b );
325 sc_threshv = _mm_set1_epi8((int8_t) 255 - sc_thresh);
326
327 /* Initialization. In offset unsigned arithmetic, -infinity is 0, and 0 is om->base.
328 */
329 biasv = _mm_set1_epi8((int8_t) om->bias_b); /* yes, you can set1() an unsigned char vector this way */
330 ceilingv = _mm_cmpeq_epi8(biasv, biasv);
331 for (q = 0; q < Q; q++) dp[q] = _mm_setzero_si128();
332
333 basev = _mm_set1_epi8((int8_t) om->base_b);
334 tjbmv = _mm_set1_epi8((int8_t) om->tjb_b + (int8_t) om->tbm_b);
335
336 xBv = _mm_subs_epu8(basev, tjbmv);
337
338 for (i = 1; i <= L; i++)
339 {
340 rsc = om->rbv[dsq[i]];
341 xEv = _mm_setzero_si128();
342
343 /* Right shifts by 1 byte. 4,8,12,x becomes x,4,8,12.
344 * Because ia32 is littlendian, this means a left bit shift.
345 * Zeros shift on automatically, which is our -infinity.
346 */
347 mpv = _mm_slli_si128(dp[Q-1], 1);
348 for (q = 0; q < Q; q++) {
349 /* Calculate new MMXo(i,q); don't store it yet, hold it in sv. */
350 sv = _mm_max_epu8(mpv, xBv);
351 sv = _mm_adds_epu8(sv, biasv);
352 sv = _mm_subs_epu8(sv, *rsc); rsc++;
353 xEv = _mm_max_epu8(xEv, sv);
354
355 mpv = dp[q]; /* Load {MDI}(i-1,q) into mpv */
356 dp[q] = sv; /* Do delayed store of M(i,q) now that memory is usable */
357 }
358
359 /* test if the pthresh significance threshold has been reached;
360 * note: don't use _mm_cmpgt_epi8, because it's a signed comparison, which won't work on uint8s */
361 tempv = _mm_adds_epu8(xEv, sc_threshv);
362 tempv = _mm_cmpeq_epi8(tempv, ceilingv);
363 cmp = _mm_movemask_epi8(tempv);
364
365 if (cmp != 0) { //hit pthresh, so add position to list and reset values
366 //figure out which model state hit threshold
367 end = -1;
368 rem_sc = -1;
369 for (q = 0; q < Q; q++) { /// Unpack and unstripe, so we can find the state that exceeded pthresh
370 u.v = dp[q];
371 for (k = 0; k < 16; k++) { // unstripe
372 //(q+Q*k+1) is the model position k at which the xE score is found
373 if (u.b[k] >= sc_thresh && u.b[k] > rem_sc && (q+Q*k+1) <= om->M) {
374 end = (q+Q*k+1);
375 rem_sc = u.b[k];
376 }
377 }
378 dp[q] = _mm_set1_epi8(0); // while we're here ... this will cause values to get reset to xB in next dp iteration
379 }
380
381 //recover the diagonal that hit threshold
382 start = end; // model position
383 target_end = target_start = i; // target position
384 sc = rem_sc;
385 while (rem_sc > om->base_b - om->tjb_b - om->tbm_b) {
386 rem_sc -= om->bias_b - ssvdata->ssv_scores[start*om->abc->Kp + dsq[target_start]];
387 --start;
388 --target_start;
389 }
390 start++;
391 target_start++;
392
393
394 //extend diagonal further with single diagonal extension
395 k = end+1;
396 n = target_end+1;
397 max_end = target_end;
398 max_sc = sc;
399 pos_since_max = 0;
400 while (k<om->M && n<=L) {
401 sc += om->bias_b - ssvdata->ssv_scores[k*om->abc->Kp + dsq[n]];
402
403 if (sc >= max_sc) {
404 max_sc = sc;
405 max_end = n;
406 pos_since_max=0;
407 } else {
408 pos_since_max++;
409 if (pos_since_max == 5)
410 break;
411 }
412 k++;
413 n++;
414 }
415
416 end += (max_end - target_end);
417 //k += (max_end - target_end);
418 target_end = max_end;
419
420 ret_sc = ((float) (max_sc - om->tjb_b) - (float) om->base_b);
421 ret_sc /= om->scale_b;
422 ret_sc -= 3.0; // that's ~ L \log \frac{L}{L+3}, for our NN,CC,JJ
423
424 p7_hmmwindow_new( windowlist,
425 0, // sequence_id; used in the FM-based filter, but not here
426 target_start, // position in the target at which the diagonal starts
427 0, // position in the target fm_index at which diagonal starts; not used here, just in FM-based filter
428 end, // position in the model at which the diagonal ends
429 end-start+1 , // length of diagonal
430 ret_sc, // score of diagonal
431 p7_NOCOMPLEMENT, // always p7_NOCOMPLEMENT here; varies in FM-based filter
432 L
433 );
434
435 i = target_end; // skip forward
436 }
437 } /* end loop over sequence residues 1..L */
438 return eslOK;
439 }
440 /*------------------ end, p7_SSVFilter_longtarget() ------------------------*/
441
442
443
444
445 /*****************************************************************
446 * 2. Benchmark driver.
447 *****************************************************************/
448 /* The benchmark driver has some additional non-benchmarking options
449 * to facilitate small-scale (by-eye) comparison of MSV scores against
450 * other implementations, for debugging purposes.
451 *
452 * The -c option compares against p7_GMSV() scores. This allows
453 * measuring the error inherent in the SSE implementation's reduced
454 * precision (p7_MSVFilter() runs in uint8_t; p7_GMSV() uses floats).
455 *
456 * The -x option compares against an emulation that should give
457 * exactly the same scores. The emulation is achieved by jiggering the
458 * fp scores in a generic profile to disallow gaps, have the same
459 * rounding and precision as the uint8_t's MSVFilter() is using, and
460 * to make the same post-hoc corrections for the NN, CC, JJ
461 * contributions to the final nat score; under these contrived
462 * circumstances, p7_GViterbi() gives the same scores as
463 * p7_MSVFilter().
464 *
465 * For using either -c or -x, you probably also want to limit the
466 * number of generated target sequences, using -N10 or -N100 for
467 * example.
468 */
469 #ifdef p7MSVFILTER_BENCHMARK
470 /*
471 gcc -o msvfilter-benchmark -std=gnu99 -g -Wall -msse2 -I.. -L.. -I../../easel -L../../easel -Dp7MSVFILTER_BENCHMARK msvfilter.c -lhmmer -leasel -lm
472 icc -o msvfilter-benchmark -O3 -static -I.. -L.. -I../../easel -L../../easel -Dp7MSVFILTER_BENCHMARK msvfilter.c -lhmmer -leasel -lm
473
474 ./benchmark-msvfilter <hmmfile> runs benchmark
475 ./benchmark-msvfilter -N100 -c <hmmfile> compare scores to generic impl
476 ./benchmark-msvfilter -N100 -x <hmmfile> compare scores to exact emulation
477 */
478 #include <p7_config.h>
479
480 #include "easel.h"
481 #include "esl_alphabet.h"
482 #include "esl_getopts.h"
483 #include "esl_random.h"
484 #include "esl_randomseq.h"
485 #include "esl_stopwatch.h"
486
487 #include "hmmer.h"
488 #include "impl_sse.h"
489
490 static ESL_OPTIONS options[] = {
491 /* name type default env range toggles reqs incomp help docgroup*/
492 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
493 { "-c", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-x", "compare scores to generic implementation (debug)", 0 },
494 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
495 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, "-c", "equate scores to trusted implementation (debug)", 0 },
496 { "-L", eslARG_INT, "400", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
497 { "-N", eslARG_INT, "50000", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
498 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
499 };
500 static char usage[] = "[-options] <hmmfile>";
501 static char banner[] = "benchmark driver for MSVFilter() implementation";
502
503 int
504 main(int argc, char **argv)
505 {
506 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
507 char *hmmfile = esl_opt_GetArg(go, 1);
508 ESL_STOPWATCH *w = esl_stopwatch_Create();
509 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
510 ESL_ALPHABET *abc = NULL;
511 P7_HMMFILE *hfp = NULL;
512 P7_HMM *hmm = NULL;
513 P7_BG *bg = NULL;
514 P7_PROFILE *gm = NULL;
515 P7_OPROFILE *om = NULL;
516 P7_OMX *ox = NULL;
517 P7_GMX *gx = NULL;
518 int L = esl_opt_GetInteger(go, "-L");
519 int N = esl_opt_GetInteger(go, "-N");
520 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
521 int i;
522 float sc1, sc2;
523 double base_time, bench_time, Mcs;
524
525 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
526 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
527
528 bg = p7_bg_Create(abc);
529 p7_bg_SetLength(bg, L);
530 gm = p7_profile_Create(hmm->M, abc);
531 p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL);
532 om = p7_oprofile_Create(gm->M, abc);
533 p7_oprofile_Convert(gm, om);
534 p7_oprofile_ReconfigLength(om, L);
535
536 if (esl_opt_GetBoolean(go, "-x")) p7_profile_SameAsMF(om, gm);
537
538 ox = p7_omx_Create(gm->M, 0, 0);
539 gx = p7_gmx_Create(gm->M, L);
540
541 /* Get a baseline time: how long it takes just to generate the sequences */
542 esl_stopwatch_Start(w);
543 for (i = 0; i < N; i++)
544 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
545 esl_stopwatch_Stop(w);
546 base_time = w->user;
547
548 esl_stopwatch_Start(w);
549 for (i = 0; i < N; i++)
550 {
551 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
552 p7_MSVFilter (dsq, L, om, ox, &sc1);
553
554 /* -c option: compare generic to fast score */
555 if (esl_opt_GetBoolean(go, "-c"))
556 {
557 p7_GMSV (dsq, L, gm, gx, 2.0, &sc2);
558 printf("%.4f %.4f\n", sc1, sc2);
559 }
560
561 /* -x option: compare generic to fast score in a way that should give exactly the same result */
562 if (esl_opt_GetBoolean(go, "-x"))
563 {
564 p7_GViterbi(dsq, L, gm, gx, &sc2);
565 sc2 /= om->scale_b;
566 if (om->mode == p7_UNILOCAL) sc2 -= 2.0; /* that's ~ L \log \frac{L}{L+2}, for our NN,CC,JJ */
567 else if (om->mode == p7_LOCAL) sc2 -= 3.0; /* that's ~ L \log \frac{L}{L+3}, for our NN,CC,JJ */
568 printf("%.4f %.4f\n", sc1, sc2);
569 }
570 }
571 esl_stopwatch_Stop(w);
572 bench_time = w->user - base_time;
573 Mcs = (double) N * (double) L * (double) gm->M * 1e-6 / (double) bench_time;
574 esl_stopwatch_Display(stdout, w, "# CPU time: ");
575 printf("# M = %d\n", gm->M);
576 printf("# %.1f Mc/s\n", Mcs);
577
578 free(dsq);
579 p7_omx_Destroy(ox);
580 p7_gmx_Destroy(gx);
581 p7_oprofile_Destroy(om);
582 p7_profile_Destroy(gm);
583 p7_bg_Destroy(bg);
584 p7_hmm_Destroy(hmm);
585 p7_hmmfile_Close(hfp);
586 esl_alphabet_Destroy(abc);
587 esl_stopwatch_Destroy(w);
588 esl_randomness_Destroy(r);
589 esl_getopts_Destroy(go);
590 return 0;
591 }
592 #endif /*p7MSVFILTER_BENCHMARK*/
593 /*------------------ end, benchmark driver ----------------------*/
594
595
596
597
598 /*****************************************************************
599 * 3. Unit tests
600 *****************************************************************/
601 #ifdef p7MSVFILTER_TESTDRIVE
602 #include "esl_random.h"
603 #include "esl_randomseq.h"
604
605 /*
606 * We can check that scores are identical (within machine error) to
607 * scores of generic DP with scores rounded the same way. Do this for
608 * a random model of length <M>, for <N> test sequences of length <L>.
609 *
610 * We assume that we don't accidentally generate a high-scoring random
611 * sequence that overflows MSVFilter()'s limited range.
612 *
613 */
614 static void
615 utest_msv_filter(ESL_RANDOMNESS *r, ESL_ALPHABET *abc, P7_BG *bg, int M, int L, int N)
616 {
617 P7_HMM *hmm = NULL;
618 P7_PROFILE *gm = NULL;
619 P7_OPROFILE *om = NULL;
620 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
621 P7_OMX *ox = p7_omx_Create(M, 0, 0);
622 P7_GMX *gx = p7_gmx_Create(M, L);
623 float sc1, sc2;
624
625 p7_oprofile_Sample(r, abc, bg, M, L, &hmm, &gm, &om);
626 p7_profile_SameAsMF(om, gm);
627 #if 0
628 p7_oprofile_Dump(stdout, om); /* dumps the optimized profile */
629 p7_omx_SetDumpMode(stdout, ox, TRUE); /* makes the fast DP algorithms dump their matrices */
630 #endif
631
632 while (N--)
633 {
634 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
635 p7_MSVFilter(dsq, L, om, ox, &sc1);
636 p7_GViterbi (dsq, L, gm, gx, &sc2);
637 #if 0
638 p7_gmx_Dump(stdout, gx, p7_DEFAULT); /* dumps a generic DP matrix */
639 #endif
640
641 sc2 = sc2 / om->scale_b - 3.0f;
642 if (fabs(sc1-sc2) > 0.001) esl_fatal("msv filter unit test failed: scores differ (%.2f, %.2f)", sc1, sc2);
643 }
644
645 free(dsq);
646 p7_hmm_Destroy(hmm);
647 p7_omx_Destroy(ox);
648 p7_gmx_Destroy(gx);
649 p7_profile_Destroy(gm);
650 p7_oprofile_Destroy(om);
651 }
652 #endif /*p7MSVFILTER_TESTDRIVE*/
653 /*-------------------- end, unit tests --------------------------*/
654
655
656
657
658 /*****************************************************************
659 * 4. Test driver
660 *****************************************************************/
661 #ifdef p7MSVFILTER_TESTDRIVE
662 /*
663 gcc -g -Wall -msse2 -std=gnu99 -I.. -L.. -I../../easel -L../../easel -o msvfilter_utest -Dp7MSVFILTER_TESTDRIVE msvfilter.c -lhmmer -leasel -lm
664 ./msvfilter_utest
665 */
666 #include <p7_config.h>
667
668 #include "easel.h"
669 #include "esl_alphabet.h"
670 #include "esl_getopts.h"
671
672 #include "hmmer.h"
673 #include "impl_sse.h"
674
675 static ESL_OPTIONS options[] = {
676 /* name type default env range toggles reqs incomp help docgroup*/
677 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
678 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
679 { "-v", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "be verbose", 0 },
680 { "-L", eslARG_INT, "200", NULL, NULL, NULL, NULL, NULL, "size of random sequences to sample", 0 },
681 { "-M", eslARG_INT, "145", NULL, NULL, NULL, NULL, NULL, "size of random models to sample", 0 },
682 { "-N", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "number of random sequences to sample", 0 },
683 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
684 };
685 static char usage[] = "[-options]";
686 static char banner[] = "test driver for the SSE MSVFilter() implementation";
687
688 int
689 main(int argc, char **argv)
690 {
691 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
692 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
693 ESL_ALPHABET *abc = NULL;
694 P7_BG *bg = NULL;
695 int M = esl_opt_GetInteger(go, "-M");
696 int L = esl_opt_GetInteger(go, "-L");
697 int N = esl_opt_GetInteger(go, "-N");
698
699 /* First round of tests for DNA alphabets. */
700 if ((abc = esl_alphabet_Create(eslDNA)) == NULL) esl_fatal("failed to create alphabet");
701 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
702
703 if (esl_opt_GetBoolean(go, "-v")) printf("MSVFilter() tests, DNA\n");
704 utest_msv_filter(r, abc, bg, M, L, N); /* normal sized models */
705 utest_msv_filter(r, abc, bg, 1, L, 10); /* size 1 models */
706 utest_msv_filter(r, abc, bg, M, 1, 10); /* size 1 sequences */
707
708 esl_alphabet_Destroy(abc);
709 p7_bg_Destroy(bg);
710
711 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal("failed to create alphabet");
712 if ((bg = p7_bg_Create(abc)) == NULL) esl_fatal("failed to create null model");
713
714 if (esl_opt_GetBoolean(go, "-v")) printf("MSVFilter() tests, protein\n");
715 utest_msv_filter(r, abc, bg, M, L, N);
716 utest_msv_filter(r, abc, bg, 1, L, 10);
717 utest_msv_filter(r, abc, bg, M, 1, 10);
718
719 esl_alphabet_Destroy(abc);
720 p7_bg_Destroy(bg);
721
722 esl_getopts_Destroy(go);
723 esl_randomness_Destroy(r);
724 return eslOK;
725 }
726 #endif /*VITFILTER_TESTDRIVE*/
727
728
729
730 /*****************************************************************
731 * 5. Example
732 *****************************************************************/
733
734 #ifdef p7MSVFILTER_EXAMPLE
735 /* A minimal example.
736 Also useful for debugging on small HMMs and sequences.
737
738 gcc -g -Wall -msse2 -std=gnu99 -I.. -L.. -I../../easel -L../../easel -o msvfilter_example -Dp7MSVFILTER_EXAMPLE msvfilter.c -lhmmer -leasel -lm
739 ./msvfilter_example <hmmfile> <seqfile>
740 */
741 #include <p7_config.h>
742
743 #include "easel.h"
744 #include "esl_alphabet.h"
745 #include "esl_getopts.h"
746 #include "esl_gumbel.h"
747 #include "esl_sq.h"
748 #include "esl_sqio.h"
749
750 #include "hmmer.h"
751 #include "impl_sse.h"
752
753 static ESL_OPTIONS options[] = {
754 /* name type default env range toggles reqs incomp help docgroup*/
755 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
756 { "-1", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in one line awkable format", 0 },
757 { "-P", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "output in profmark format", 0 },
758 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
759 };
760 static char usage[] = "[-options] <hmmfile> <seqfile>";
761 static char banner[] = "example of MSV filter algorithm";
762
763 int
764 main(int argc, char **argv)
765 {
766 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 2, argc, argv, banner, usage);
767 char *hmmfile = esl_opt_GetArg(go, 1);
768 char *seqfile = esl_opt_GetArg(go, 2);
769 ESL_ALPHABET *abc = NULL;
770 P7_HMMFILE *hfp = NULL;
771 P7_HMM *hmm = NULL;
772 P7_BG *bg = NULL;
773 P7_PROFILE *gm = NULL;
774 P7_OPROFILE *om = NULL;
775 P7_OMX *ox = NULL;
776 P7_GMX *gx = NULL;
777 ESL_SQ *sq = NULL;
778 ESL_SQFILE *sqfp = NULL;
779 int format = eslSQFILE_UNKNOWN;
780 float msvraw, nullsc, msvscore;
781 float graw, gscore;
782 double P, gP;
783 int status;
784
785 /* Read in one HMM */
786 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
787 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
788
789 /* Open sequence file for reading */
790 sq = esl_sq_CreateDigital(abc);
791 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
792 if (status == eslENOTFOUND) p7_Fail("No such file.");
793 else if (status == eslEFORMAT) p7_Fail("Format unrecognized.");
794 else if (status == eslEINVAL) p7_Fail("Can't autodetect stdin or .gz.");
795 else if (status != eslOK) p7_Fail("Open failed, code %d.", status);
796
797 /* create default null model, then create and optimize profile */
798 bg = p7_bg_Create(abc);
799 p7_bg_SetLength(bg, sq->n);
800 gm = p7_profile_Create(hmm->M, abc);
801 p7_ProfileConfig(hmm, bg, gm, sq->n, p7_LOCAL);
802 om = p7_oprofile_Create(gm->M, abc);
803 p7_oprofile_Convert(gm, om);
804
805 /* allocate DP matrices, both a generic and an optimized one */
806 ox = p7_omx_Create(gm->M, 0, 0); /* one row version */
807 gx = p7_gmx_Create(gm->M, sq->n);
808
809 /* Useful to place and compile in for debugging:
810 p7_oprofile_Dump(stdout, om); dumps the optimized profile
811 p7_omx_SetDumpMode(stdout, ox, TRUE); makes the fast DP algorithms dump their matrices
812 p7_gmx_Dump(stdout, gx, p7_DEFAULT); dumps a generic DP matrix
813 p7_oprofile_SameMSV(om, gm);
814 */
815 //p7_oprofile_Dump(stdout, om);
816 //p7_omx_SetDumpMode(stdout, ox, TRUE);
817
818 while ((status = esl_sqio_Read(sqfp, sq)) == eslOK)
819 {
820 p7_oprofile_ReconfigLength(om, sq->n);
821 p7_ReconfigLength(gm, sq->n);
822 p7_bg_SetLength(bg, sq->n);
823 p7_omx_GrowTo(ox, om->M, 0, sq->n);
824 p7_gmx_GrowTo(gx, gm->M, sq->n);
825
826 p7_MSVFilter (sq->dsq, sq->n, om, ox, &msvraw);
827 p7_bg_NullOne (bg, sq->dsq, sq->n, &nullsc);
828 msvscore = (msvraw - nullsc) / eslCONST_LOG2;
829 P = esl_gumbel_surv(msvscore, om->evparam[p7_MMU], om->evparam[p7_MLAMBDA]);
830
831 p7_GMSV(sq->dsq, sq->n, gm, gx, 2.0, &graw);
832 gscore = (graw - nullsc) / eslCONST_LOG2;
833 gP = esl_gumbel_surv(gscore, gm->evparam[p7_MMU], gm->evparam[p7_MLAMBDA]);
834
835 if (esl_opt_GetBoolean(go, "-1"))
836 {
837 printf("%-30s %-20s %9.2g %7.2f %9.2g %7.2f\n", sq->name, hmm->name, P, msvscore, gP, gscore);
838 }
839 else if (esl_opt_GetBoolean(go, "-P"))
840 { /* output suitable for direct use in profmark benchmark postprocessors: */
841 printf("%g %.2f %s %s\n", P, msvscore, sq->name, hmm->name);
842 }
843 else
844 {
845 printf("target sequence: %s\n", sq->name);
846 printf("msv filter raw score: %.2f nats\n", msvraw);
847 printf("null score: %.2f nats\n", nullsc);
848 printf("per-seq score: %.2f bits\n", msvscore);
849 printf("P-value: %g\n", P);
850 printf("GMSV raw score: %.2f nats\n", graw);
851 printf("GSMV per-seq score: %.2f bits\n", gscore);
852 printf("GSMV P-value: %g\n", gP);
853 }
854
855 esl_sq_Reuse(sq);
856 }
857
858 /* cleanup */
859 esl_sq_Destroy(sq);
860 esl_sqfile_Close(sqfp);
861 p7_omx_Destroy(ox);
862 p7_gmx_Destroy(gx);
863 p7_oprofile_Destroy(om);
864 p7_profile_Destroy(gm);
865 p7_bg_Destroy(bg);
866 p7_hmm_Destroy(hmm);
867 p7_hmmfile_Close(hfp);
868 esl_alphabet_Destroy(abc);
869 esl_getopts_Destroy(go);
870 return 0;
871 }
872 #endif /*p7MSVFILTER_EXAMPLE*/
873 /*---------------------- end, example ---------------------------*/
874
875
876
877