Debian Codegraph @

hmmer/src/generic_null2.c

raw symbols SCIP
1 /* "null2" model: biased composition correction
2 *
3 * Contents:
4 * 1. Null2 estimation algorithms.
5 * 2. Benchmark driver.
6 * 3. Unit tests.
7 * 4. Test driver.
8 * 5. Example.
9 *
10 * See p7_domaindef.c -- null2 correction of per-seq and per-domain
11 * scores is embedded within p7_domaindef's logic; we split it out
12 * to a separate file because it's so important.
13 *
14 * SRE, Thu Feb 28 09:51:27 2008 [Janelia]
15 */
16 #include <p7_config.h>
17
18 #include "easel.h"
19 #include "esl_vectorops.h"
20
21 #include "hmmer.h"
22
23 #define MMX(i,k) (dp[(i)][(k) * p7G_NSCELLS + p7G_M])
24 #define IMX(i,k) (dp[(i)][(k) * p7G_NSCELLS + p7G_I])
25 #define DMX(i,k) (dp[(i)][(k) * p7G_NSCELLS + p7G_D])
26 #define XMX(i,s) (xmx[(i) * p7G_NXCELLS + (s)])
27
28
29 /*****************************************************************
30 * 1. Null2 estimation algorithms.
31 *****************************************************************/
32
33 /* Function: p7_GNull2_ByExpectation()
34 * Synopsis: Calculate null2 model from posterior probabilities.
35 * Incept: SRE, Thu Feb 28 09:52:28 2008 [Janelia]
36 *
37 * Purpose: Calculate the "null2" model for the envelope encompassed
38 * by a posterior probability calculation <pp> for model
39 * <gm>. Return the null2 odds emission probabilities
40 * $\frac{f'{x}}{f{x}}$ in <null2>, which caller
41 * provides as space for at least <alphabet->Kp> residues.
42 *
43 * The expectation method is applied to envelopes in
44 * simple, well resolved regions (regions containing just a
45 * single envelope, where no stochastic traceback
46 * clustering was required).
47 *
48 * Make sure that the posterior probability matrix <pp> has
49 * been calculated by the caller for only the envelope; thus
50 * its rows are numbered <1..Ld>, for envelope <ienv..jenv>
51 * of length <Ld=jenv-ienv+1>.
52 *
53 * Args: gm - profile, in any mode, target length model set to <L>
54 * pp - posterior prob matrix, for <gm> against domain envelope <dsq+i-1> (offset)
55 * null2 - RETURN: null2 odds ratios per residue; <0..Kp-1>; caller allocated space
56 *
57 * Returns: <eslOK> on success; <null2> contains the null2 scores. The 0
58 * row of <pp> has been used as temp space, and happens to contain
59 * the expected frequency that each M,I,N,C,J state is used in this
60 * <pp> matrix to generate residues.
61 *
62 * Throws: (no abnormal error conditions)
63 */
64 int
65 p7_GNull2_ByExpectation(const P7_PROFILE *gm, P7_GMX *pp, float *null2)
66 {
67 int M = gm->M;
68 int Ld = pp->L;
69 float **dp = pp->dp;
70 float *xmx = pp->xmx;
71 float xfactor;
72 int x; /* over symbols 0..K-1 */
73 int i; /* over offset envelope dsq positions 1..Ld */
74 int k; /* over model M states 1..M, I states 1..M-1 */
75
76 /* Calculate expected # of times that each emitting state was used
77 * in generating the Ld residues in this domain.
78 * The 0 row in <wrk> is used to hold these numbers.
79 */
80 esl_vec_FCopy(pp->dp[1], (M+1)*p7G_NSCELLS, pp->dp[0]);
81 esl_vec_FCopy(pp->xmx+p7G_NXCELLS, p7G_NXCELLS, pp->xmx);
82 for (i = 2; i <= Ld; i++)
83 {
84 esl_vec_FAdd(pp->dp[0], pp->dp[i], (M+1)*p7G_NSCELLS);
85 esl_vec_FAdd(pp->xmx, pp->xmx+i*p7G_NXCELLS, p7G_NXCELLS);
86 }
87
88 /* Convert those expected #'s to log frequencies; these we'll use as
89 * the log posterior weights.
90 */
91 esl_vec_FLog(pp->dp[0], (M+1)*p7G_NSCELLS);
92 esl_vec_FLog(pp->xmx, p7G_NXCELLS);
93
94 esl_vec_FIncrement(pp->dp[0], (M+1)*p7G_NSCELLS, -log((float)Ld));
95 esl_vec_FIncrement(pp->xmx, p7G_NXCELLS, -log((float)Ld));
96
97 /* Calculate null2's log odds emission probabilities, by taking
98 * posterior weighted sum over all emission vectors used in paths
99 * explaining the domain.
100 * This is dog-slow; a point for future optimization.
101 */
102 xfactor = XMX(0,p7G_N);
103 xfactor = p7_FLogsum(xfactor, XMX(0,p7G_C));
104 xfactor = p7_FLogsum(xfactor, XMX(0,p7G_J));
105 esl_vec_FSet(null2, gm->abc->K, -eslINFINITY);
106 for (x = 0; x < gm->abc->K; x++)
107 {
108 for (k = 1; k < M; k++)
109 {
110 null2[x] = p7_FLogsum(null2[x], MMX(0,k) + p7P_MSC(gm, k, x));
111 null2[x] = p7_FLogsum(null2[x], IMX(0,k) + p7P_ISC(gm, k, x));
112 }
113 null2[x] = p7_FLogsum(null2[x], MMX(0,M) + p7P_MSC(gm, k, x));
114 null2[x] = p7_FLogsum(null2[x], xfactor);
115 }
116
117 esl_vec_FExp (null2, gm->abc->K);
118 /* now null2[x] = \frac{f_d(x)}{f_0(x)} for all x in alphabet,
119 * 0..K-1, where f_d(x) are the ad hoc "null2" residue frequencies
120 * for this envelope.
121 */
122
123 /* make valid scores for all degeneracies, by averaging the odds ratios. */
124 esl_abc_FAvgScVec(gm->abc, null2); /* does not set gap, nonres, missing */
125 null2[gm->abc->K] = 1.0; /* gap character */
126 null2[gm->abc->Kp-2] = 1.0; /* nonresidue "*" */
127 null2[gm->abc->Kp-1] = 1.0; /* missing data "~" */
128
129 return eslOK;
130 }
131
132
133 /* Function: p7_GNull2_ByTrace()
134 * Synopsis: Assign null2 scores to an envelope by the sampling method.
135 * Incept: SRE, Thu May 1 10:00:43 2008 [Janelia]
136 *
137 * Purpose: Given a traceback <tr> for an alignment of model <gm> to
138 * some target sequence; calculate null2 odds ratios $\frac{f'{x}}{f{x}}$
139 * as the state-usage-weighted emission probabilities,
140 * with state usages calculated by counting emissions used
141 * at positions <zstart..zend> in the trace.
142 *
143 * Because we only need to collect state usages from the
144 * trace <tr>, the target sequence is irrelevant. Because
145 * we are only averaging emission odds ratios from model
146 * <gm>, the configuration of <gm> is irrelevant (uni
147 * vs. multihit, or length config).
148 *
149 * Args: gm - model, in any configuration; only emission odds are used
150 * tr - traceback for any region (or all) of a target sequence
151 * zstart - first elem in <tr> to collect from; use 0 for complete
152 * zend - last elem in <tr> to collect from; use tr->N-1 for complete
153 * wrk - DP matrix w/ at least one row, for workspace
154 * null2 - RESULT: odds ratios f'(x)/f(x) for all Kp residues
155 *
156 * Returns: <eslOK> on success, and the <ddef->n2sc> scores are set
157 * for region <i..j>.
158 *
159 * Throws: <eslEMEM> on allocation error.
160 */
161 int
162 p7_GNull2_ByTrace(const P7_PROFILE *gm, const P7_TRACE *tr, int zstart, int zend, P7_GMX *wrk, float *null2)
163 {
164 float **dp = wrk->dp; /* so that {MDI}MX() macros work */
165 float *xmx = wrk->xmx; /* so that XMX() macro works */
166 int Ld = 0;
167 int M = gm->M;
168 int k; /* index over model position */
169 int x; /* index over residues */
170 int z; /* index over trace position */
171 float xfactor;
172
173 /* We'll use the i=0 row in wrk for working space: dp[0][] and xmx[0..4]. */
174 esl_vec_FSet(wrk->dp[0], (M+1)*p7G_NSCELLS, 0.0);
175 esl_vec_FSet(wrk->xmx, p7G_NXCELLS, 0.0);
176
177 /* Calculate emitting state usage in this particular trace segment: */
178 for (z = zstart; z <= zend; z++)
179 {
180 switch (tr->st[z]) {
181 case p7T_M: Ld++; MMX(0,tr->k[z]) += 1.0; break;
182 case p7T_I: Ld++; IMX(0,tr->k[z]) += 1.0; break;
183 case p7T_N: if (tr->st[z-1] == p7T_N) { Ld++; XMX(0,p7G_N) += 1.0; } break;
184 case p7T_C: if (tr->st[z-1] == p7T_C) { Ld++; XMX(0,p7G_C) += 1.0; } break;
185 case p7T_J: if (tr->st[z-1] == p7T_J) { Ld++; XMX(0,p7G_J) += 1.0; } break;
186 }
187 }
188 esl_vec_FScale(wrk->dp[0], (M+1)*p7G_NSCELLS, (1.0 / (float) Ld));
189 esl_vec_FScale(wrk->xmx, p7G_NXCELLS, (1.0 / (float) Ld));
190
191 /* Calculate null2's odds ratio emission probabilities, by taking
192 * posterior weighted sum over all emission vectors used in paths
193 * explaining the domain.
194 */
195 esl_vec_FSet(null2, gm->abc->K, 0.0);
196 xfactor = XMX(0,p7G_N) + XMX(0,p7G_C) + XMX(0,p7G_J);
197 for (x = 0; x < gm->abc->K; x++)
198 {
199 for (k = 1; k < M; k++)
200 {
201 null2[x] += MMX(0,k) * expf(p7P_MSC(gm, k, x));
202 null2[x] += IMX(0,k) * expf(p7P_ISC(gm, k, x));
203 }
204 null2[x] += MMX(0,M) * expf(p7P_MSC(gm, M, x));
205 null2[x] += xfactor;
206 }
207 /* now null2[x] = \frac{f_d(x)}{f_0(x)} odds ratios for all x in alphabet,
208 * 0..K-1, where f_d(x) are the ad hoc "null2" residue frequencies
209 * for this envelope.
210 */
211
212 /* make valid scores for all degeneracies, by averaging the odds ratios. */
213 esl_abc_FAvgScVec(gm->abc, null2);
214 null2[gm->abc->K] = 1.0; /* gap character */
215 null2[gm->abc->Kp-2] = 1.0; /* nonresidue "*" */
216 null2[gm->abc->Kp-1] = 1.0; /* missing data "~" */
217
218 return eslOK;
219 }
220
221
222
223
224 /*****************************************************************
225 * 2. Benchmark driver
226 *****************************************************************/
227 #ifdef p7GENERIC_NULL2_BENCHMARK
228 /*
229 icc -O3 -static -o generic_null2_benchmark -I. -L. -I../easel -L../easel -Dp7GENERIC_NULL2_BENCHMARK generic_null2.c -lhmmer -leasel -lm
230 ./benchmark-generic-null2 <hmmfile>
231 RRM_1 (M=72) Caudal_act (M=136) SMC_N (M=1151)
232 ----------------- ------------------ -------------------
233 21 Aug 2008 7.77u (185 Mc/s) 14.13u (192 Mc/s) 139.03u (165.6 Mc/s)
234 */
235 #include <p7_config.h>
236
237 #include "easel.h"
238 #include "esl_alphabet.h"
239 #include "esl_getopts.h"
240 #include "esl_random.h"
241 #include "esl_randomseq.h"
242 #include "esl_stopwatch.h"
243
244 #include "hmmer.h"
245
246 static ESL_OPTIONS options[] = {
247 /* name type default env range toggles reqs incomp help docgroup*/
248 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
249 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
250 { "-L", eslARG_INT, "400", NULL, "n>0", NULL, NULL, NULL, "length of random target seqs", 0 },
251 { "-N", eslARG_INT, "50000", NULL, "n>0", NULL, NULL, NULL, "number of random target seqs", 0 },
252 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
253 };
254 static char usage[] = "[-options] <hmmfile>";
255 static char banner[] = "benchmark driver for posterior residue null2, generic version";
256
257 int
258 main(int argc, char **argv)
259 {
260 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
261 char *hmmfile = esl_opt_GetArg(go, 1);
262 ESL_STOPWATCH *w = esl_stopwatch_Create();
263 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
264 ESL_ALPHABET *abc = NULL;
265 P7_HMMFILE *hfp = NULL;
266 P7_HMM *hmm = NULL;
267 P7_BG *bg = NULL;
268 P7_PROFILE *gm = NULL;
269 P7_GMX *gx1 = NULL;
270 P7_GMX *gx2 = NULL;
271 int L = esl_opt_GetInteger(go, "-L");
272 int N = esl_opt_GetInteger(go, "-N");
273 ESL_DSQ *dsq = malloc(sizeof(ESL_DSQ) * (L+2));
274 float null2[p7_MAXCODE];
275 int i;
276 float fsc, bsc;
277 double Mcs;
278
279 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
280 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
281
282 bg = p7_bg_Create(abc); p7_bg_SetLength(bg, L);
283 gm = p7_profile_Create(hmm->M, abc); p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL);
284 gx1 = p7_gmx_Create(gm->M, L);
285 gx2 = p7_gmx_Create(gm->M, L);
286
287 esl_rsq_xfIID(r, bg->f, abc->K, L, dsq);
288 p7_GForward (dsq, L, gm, gx1, &fsc);
289 p7_GBackward(dsq, L, gm, gx2, &bsc);
290 p7_GDecoding(gm, gx1, gx2, gx2);
291
292 esl_stopwatch_Start(w);
293 for (i = 0; i < N; i++)
294 p7_GNull2_ByExpectation(gm, gx2, null2);
295 esl_stopwatch_Stop(w);
296
297 Mcs = (double) N * (double) L * (double) gm->M * 1e-6 / w->user;
298 esl_stopwatch_Display(stdout, w, "# CPU time: ");
299 printf("# M = %d\n", gm->M);
300 printf("# %.1f Mc/s\n", Mcs);
301
302 free(dsq);
303 p7_gmx_Destroy(gx1);
304 p7_gmx_Destroy(gx2);
305 p7_profile_Destroy(gm);
306 p7_bg_Destroy(bg);
307 p7_hmm_Destroy(hmm);
308 p7_hmmfile_Close(hfp);
309 esl_alphabet_Destroy(abc);
310 esl_stopwatch_Destroy(w);
311 esl_randomness_Destroy(r);
312 esl_getopts_Destroy(go);
313 return 0;
314 }
315 #endif /*p7GENERIC_NULL2_BENCHMARK*/
316 /*------------------ end, benchmark driver ----------------------*/
317
318
319
320
321 /*****************************************************************
322 * 3. Unit tests
323 *****************************************************************/
324 #ifdef p7GENERIC_NULL2_TESTDRIVE
325
326 static void
327 utest_correct_normalization(ESL_RANDOMNESS *r, P7_PROFILE *gm, P7_BG *bg, ESL_DSQ *dsq, int L, P7_GMX *fwd, P7_GMX *bck)
328 {
329 char *msg = "normalization unit test failed";
330 float null2[p7_MAXABET];
331 float sum;
332 int x;
333
334 esl_rsq_xfIID(r, bg->f, gm->abc->K, L, dsq); /* sample a random digital seq of length L */
335
336 p7_GForward (dsq, L, gm, fwd, NULL);
337 p7_GBackward(dsq, L, gm, bck, NULL);
338 p7_PosteriorNull2(L, gm, fwd, bck, bck); /* <bck> now contains posterior probs */
339 p7_Null2Corrections(gm, dsq, L, 0, bck, fwd, null2, NULL, NULL); /* use <fwd> as workspace */
340
341 /* Convert null2 from lod score to frequencies f_d */
342 for (x = 0; x < gm->abc->K; x++)
343 null2[x] = exp(null2[x]) * bg->f[x];
344
345 sum = esl_vec_FSum(null2, gm->abc->K);
346 if (sum < 0.99 || sum > 1.01) esl_fatal(msg);
347 }
348
349
350 #endif /*p7GENERIC_NULL2_TESTDRIVE*/
351 /*--------------------- end, unit tests -------------------------*/
352
353
354
355
356 /*****************************************************************
357 * 4. Test driver
358 *****************************************************************/
359 #ifdef p7GENERIC_NULL2_TESTDRIVE
360 /* gcc -o null2_utest -g -Wall -I../easel -L../easel -I. -L. -Dp7NULL2_TESTDRIVE null2.c -lhmmer -leasel -lm
361 * ./null2_utest
362 */
363 #include <p7_config.h>
364
365 #include <stdio.h>
366 #include <stdlib.h>
367
368 #include "easel.h"
369 #include "esl_getopts.h"
370 #include "esl_random.h"
371 #include "esl_alphabet.h"
372 #include "hmmer.h"
373
374 static ESL_OPTIONS options[] = {
375 /* name type default env range toggles reqs incomp help docgroup*/
376 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
377 { "-L", eslARG_INT, "200", NULL, NULL, NULL, NULL, NULL, "length of sampled sequences", 0 },
378 { "-M", eslARG_INT, "100", NULL, NULL, NULL, NULL, NULL, "length of sampled HMM", 0 },
379 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
380 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
381 };
382
383 static char usage[] = "[-options]";
384 static char banner[] = "unit test driver for the null2 correction calculation";
385
386 int
387 main(int argc, char **argv)
388 {
389 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
390 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
391 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
392 P7_HMM *hmm = NULL;
393 P7_BG *bg = NULL;
394 P7_PROFILE *gm = NULL;
395 P7_GMX *fwd = NULL;
396 P7_GMX *bck = NULL;
397 ESL_DSQ *dsq = NULL;
398 int M = esl_opt_GetInteger(go, "-M");
399 int L = esl_opt_GetInteger(go, "-L");
400
401 /* Sample a random HMM */
402 p7_hmm_Sample(r, M, abc, &hmm);
403
404 /* Configure a profile from the sampled HMM */
405 bg = p7_bg_Create(abc);
406 p7_bg_SetLength(bg, L);
407 gm = p7_profile_Create(hmm->M, abc);
408 p7_ProfileConfig(hmm, bg, gm, L, p7_LOCAL);
409
410 /* Other initial allocations */
411 dsq = malloc(sizeof(ESL_DSQ) * (L+2));
412 fwd = p7_gmx_Create(gm->M, L);
413 bck = p7_gmx_Create(gm->M, L);
414 p7_FLogsumInit();
415
416 utest_correct_normalization(r, gm, bg, dsq, L, fwd, bck);
417
418 free(dsq);
419 p7_gmx_Destroy(fwd);
420 p7_gmx_Destroy(bck);
421 p7_profile_Destroy(gm);
422 p7_bg_Destroy(bg);
423 p7_hmm_Destroy(hmm);
424 esl_alphabet_Destroy(abc);
425 esl_randomness_Destroy(r);
426 esl_getopts_Destroy(go);
427 return 0;
428 }
429 #endif /*p7GENERIC_NULL2_TESTDRIVE*/
430 /*-------------------- end, test driver -------------------------*/
431
432
433
434
435
436
437
438