Debian Codegraph @

src/cm_qdband.c

raw symbols SCIP
1 /* cm_qdband.c (formerly bandcyk.c)
2 *
3 * SRE, Wed Nov 20 07:46:56 2002 [flight home from Airlie mtg]
4 *
5 * Banded CYK implementation.
6 */
7
8 #include <esl_config.h>
9 #include <p7_config.h>
10 #include "config.h"
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <math.h>
15 #include <float.h>
16
17 #include "easel.h"
18 #include "esl_alphabet.h"
19 #include "esl_random.h"
20 #include "esl_vectorops.h"
21 #include "esl_stack.h"
22 #include "esl_sqio.h"
23
24 #include "hmmer.h"
25
26 #include "infernal.h"
27
28 static char *qdbinfo_setby_to_string(int setby);
29
30 /* Function: CalculateQueryDependentBands()
31 * Incept: EPN, Sat Dec 10 16:23:53 2011
32 *
33 * Purpose: A wrapper for BandCalculationEngine() (see that function
34 * for more information). BCE() requires a guess at a maximum
35 * length Z hat may or may not satisfy our criteria for
36 * truncation error, so if it fails we continue to call it
37 * with larger Z until it passes.
38 *
39 * Returns: eslOK on success.
40 * eslEINVAL if qdbinfo->beta1 is < qdbinfo->beta2 (beta1 should always be higher (tighter bands))
41 * eslEMEM if we're out of memory
42 * eslEINCONCEIVABLE if (Z = cm->clen * 1000) is still not big enough
43 */
44 int
45 CalculateQueryDependentBands(CM_t *cm, char *errbuf, CM_QDBINFO *qdbinfo, double beta_W, int *ret_W,
46 double **ret_gamma0_loc, double **ret_gamma0_glb, int *ret_Z)
47 {
48 int status;
49 int Z;
50
51 if(qdbinfo != NULL && ((qdbinfo->beta2 - qdbinfo->beta1) > 1E-20)) ESL_FAIL(eslEINVAL, errbuf, "Calculating QDBs, qdbinfo->beta1 < qdbinfo->beta2");
52
53 Z = cm->clen * 4;
54 while((status = BandCalculationEngine(cm, Z, qdbinfo, beta_W, ret_W, NULL, ret_gamma0_loc, ret_gamma0_glb)) != eslOK) {
55 if(status == eslEMEM) ESL_FAIL(status, errbuf, "Calculating QDBs, out of memory");
56 if(status != eslERANGE) ESL_FAIL(status, errbuf, "Calculating QDBs, unexpected error");
57 Z *= 2;
58 if(Z > (cm->clen * 1000)) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "Calculating QDBs, Z got insanely large (> 1000*clen)");
59 }
60
61 if(ret_Z != NULL) *ret_Z = Z;
62 return eslOK;
63 }
64
65
66 /* Function: BandCalculationEngine()
67 * Incept: SRE, Sat Oct 11 14:17:40 2003 [St. Louis]
68 *
69 * Purpose: Given a CM and a maximum length Z;
70 * calculate probability densities gamma_v(n), probability
71 * of a parse subtree rooted at state v emitting a sequence
72 * of length n.
73 *
74 * Then use these to return up to two sets of bounds
75 * dmin1[v]..dmax1[v] and dmin2[v]..dmax2[v] which
76 * include a probability mass of >= 1-2(beta1) and
77 * >= 1-2(beta2) respectively. Each truncated tail
78 * (left and right) contains <= beta1 and <= beta2
79 * * probability mass.
80 *
81 * dmin1, dmax2, dmin2, dmax2, beta1, beta2 are all
82 * part of the passed in <qdbinfo> data structure.
83 * If <qdbinfo> is NULL, don't calculate these bands.
84 *
85 * Let L_v(n) be the cumulative probability distribution,
86 * P(length <= n), for state v:
87 * L_v(n) = \sum_{i=0}^{n} \gamma_v(i)
88 *
89 * For each state v, find dmin such that the probability
90 * of missing a hit is <= \beta on the low side:
91 * dmin = max_dmin L_v(dmin-1) <= \beta
92 *
93 * On the high side, let H_v(n) be 1-L_v(n): e.g.
94 * P(length > n) for state v. But it is important not
95 * to calculate this as 1-L_v(n); because of numerical
96 * roundoff issues, it must be done as:
97 * H_v(n) = \sum_{i=n+1}{\infty} \gamma_v(i)
98 *
99 * Then for each state v, find a dmax such that the
100 * probability of missing a hit is <= \beta on the high
101 * side:
102 * dmax = min_dmax H_v(dmax) <= \beta
103 *
104 * Note on truncation error:
105 * Of course we can't calculate the sum to \infty; we have
106 * to truncate somewhere. Truncation error must be negligible,
107 * else our choice of bands will depend on the choice of Z.
108 * See BandTruncationNegligible() for the test.
109 *
110 * Note on model configuration:
111 * We always calculate QDBs with local ends off and local
112 * begins on. This makes the QDBs safe to use for local or
113 * global search: putting local begins on only affects the
114 * ROOT_S state 0, which must be able to transit to any
115 * state for which a legal local begin is possible. A
116 * scanner function (e.g. cm_dpsearch.c:FastCYKScan()) can
117 * restrict dmin[0] and dmax[0] in global mode as a small
118 * optimization.
119 *
120 * However, we don't want to modify the model configuration
121 * since local begins on and local ends off is a strange
122 * combination. So we make copies of <cm->t> and calculate
123 * new versions of <cm->begin> and <cm->trbegin> vectors
124 * just to use to calculate bands. This way we don't have
125 * to reconfigure the model twice: once upon entering the
126 * function and then back to its original state upon exit.
127 * This would be relatively quick, our main motivation is
128 * that we want to limit the possible paths through the
129 * different configuration functions as much as possible
130 * to limit the chance that some of those paths would
131 * screw something up.
132 *
133 * Args: cm - model to build the bands for
134 * Z - maximum subsequence length Z
135 * qdbinfo - data structure with two sets of preallocated
136 * dmin/dmax arrays and two beta values, if
137 * NULL we don't care about d bounds.
138 * beta_W - tail probability mass used to set ret_W,
139 * the maximum size of a hit to be allowed
140 * ret_W - RETURN: dmax[0] set with tail loss prob == beta_W
141 * ret_gamma - RETURN: gamma[v][n], [0..M-1][0..Z], is the prob
142 * density Prob(length=n | parse subtree rooted at v).
143 * If NULL: uses a memory-efficient O(Z lnM)
144 * algorithm instead
145 * ret_gamma0_loc - RETURN: [0..Z] probability of hit lengths (rooted at ROOT_S) in local mode
146 * ret_gamma0_glb - RETURN: [0..Z] probability of hit lengths (rooted at ROOT_S) in global mode
147 *
148 * Returns: eslOK on success.
149 * eslERANGE if Z was too small; caller needs to increase Z and call the engine again.
150 * eslEINVAL if qdbinfo->beta1 is < qdbinfo->beta2 (beta1 should always be higher (tighter bands))
151 * eslEMEM if we're out of memory
152 *
153 * The dependency on a sensible Z a priori is an annoyance;
154 * it may be possible to write an algorithm that calculates
155 * Z on the fly, but I don't see it.
156 *
157 * Xref: STL7 p.127 - rearranged calculations of previous BandBounds()
158 * imp., for better numerical precision
159 * STL7 p.128 - justification of truncation error calculations.
160 * STL7 p.130 - tests/evaluations.
161 */
162 int
163 BandCalculationEngine(CM_t *cm, int Z, CM_QDBINFO *qdbinfo, double beta_W,
164 int *ret_W, double ***ret_gamma, double **ret_gamma0_loc, double **ret_gamma0_glb)
165 {
166 int status; /* return status. */
167 double **gamma; /* P(length = n) for each state v */
168 int v; /* counter over states, 0..M-1 */
169 int y; /* counter over connected states */
170 int n; /* counter over lengths, 0..Z */
171 int dv; /* Delta for state v */
172 int leftn; /* length of left subsequence under a bifurc */
173 double pdf; /* P(<=n) or P(>=n) for this state v */
174 int *touch = NULL; /* touch[y] = # higher states depending on y */
175 ESL_STACK *beamstack = NULL; /* pool of beams we can reuse */
176 double *tmp; /* for freeing beamstack only */
177 int yoffset; /* counter over children */
178 double *gamma0_loc = NULL; /* length distribution of local hits (gamma[0]) */
179 double *gamma0_glb = NULL; /* length distribution of global hits (gamma[0] if we were in global mode) */
180 double max_beta; /* max of beta_W, qdbinfo->beta1 and qdbinfo->beta2 */
181 int dmin2_set = FALSE; /* qdbinfo->dmin2 has been set for this state, used when setting bands */
182 int dmax2_set = FALSE; /* qdbinfo->dmax2 has been set for this state, used when setting bands */
183 int W; /* dmax[0] when using beta_W, returned as *ret_W */
184
185 /* copies of CM parameters */
186 float **t_copy = NULL; /* copy of cm->t[0..v..M-1][0..MAXCONNECT-1], transition probs */
187 float *begin_copy = NULL; /* cm->begin[0..v..M-1], standard local begin probabilities */
188
189 if(qdbinfo != NULL && ((qdbinfo->beta2 - qdbinfo->beta1) > 1E-20)) return eslEINVAL;
190 max_beta = beta_W;
191 if(qdbinfo != NULL) max_beta = ESL_MAX(max_beta, ESL_MAX(qdbinfo->beta1, qdbinfo->beta2));
192
193 /* Make copies of cm->t, cm->begin and cm->trbegin, so we can
194 * modify the copies without changing the originals.
195 */
196 ESL_ALLOC(t_copy, cm->M * sizeof(float *));
197 ESL_ALLOC(t_copy[0], cm->M * MAXCONNECT * sizeof(float));
198 for (v = 0; v < cm->M; v++) {
199 t_copy[v] = t_copy[0] + v * MAXCONNECT;
200 }
201 ESL_ALLOC(begin_copy, sizeof(float) * cm->M);
202 esl_vec_FCopy(cm->t[0], cm->M * MAXCONNECT, t_copy[0]);
203 esl_vec_FCopy(cm->begin, cm->M, begin_copy);
204
205 /* Now modify our copies to reflect a CM with local begins on but local ends off */
206 /* first negate local ends */
207 if(cm->flags & CMH_LOCAL_END) {
208 for (v = 0; v < cm->M; v++) {
209 if(NOTZERO(cm->end[v])) {
210 esl_vec_FNorm(t_copy[v], cm->cnum[v]);
211 }
212 }
213 }
214 cm_CalculateLocalBeginProbs(cm, cm->pbegin, t_copy, begin_copy);
215
216 /* gamma[v][n] is Prob(state v generates subseq of length n)
217 */
218 ESL_ALLOC(gamma, sizeof(double *) * cm->M);
219 for (v = 0; v < cm->M; v++) gamma[v] = NULL;
220
221 /* beamstack is a trick for reusing memory: a pushdown stack of
222 * "beams" (gamma[v] rows) we can reuse.
223 */
224 beamstack = esl_stack_PCreate();
225
226 /* The second component of memory saving is the "touch" array.
227 * touch[y] is the number of states above state [y] that will
228 * depend on y but haven't been calculated yet. When we're done
229 * calculating a new state v, we decrement touch[y] for all
230 * y \in C_v. Any time touch[y] reaches 0, we put that beam
231 * back into the pool for reuse.
232 */
233 ESL_ALLOC(touch, sizeof(int) * cm->M);
234 for (v = 0; v < cm->M; v++) touch[v] = cm->pnum[v];
235
236 /* Allocate and initialize the shared end beam and the special
237 * ROOT_S beam which we need to keep around the entire time.
238 */
239 ESL_ALLOC(gamma[0], (sizeof(double) * (Z+1)));
240 ESL_ALLOC(gamma[cm->M-1], (sizeof(double) * (Z+1)));
241 esl_vec_DSet(gamma[0], Z+1, 0.);
242 esl_vec_DSet(gamma[cm->M-1], Z+1, 0.);
243 gamma[cm->M-1][0] = 1.0;
244
245 for (v = cm->M-1; v >= 0; v--) {
246 if (cm->sttype[v] == E_st) {
247 gamma[v] = gamma[cm->M-1];
248 if(qdbinfo != NULL) {
249 qdbinfo->dmin1[v] = qdbinfo->dmax1[v] = 0;
250 qdbinfo->dmin2[v] = qdbinfo->dmax2[v] = 0;
251 }
252 continue;
253 }
254
255 if(v != 0) {
256 if (esl_stack_PPop(beamstack, (void **) &gamma[v]) == eslEOD) {
257 ESL_ALLOC(gamma[v], sizeof(double) * (Z+1));
258 }
259 esl_vec_DSet(gamma[v], Z+1, 0.);
260 }
261 /* Recursively calculate prob density P(length=n) for this state v.
262 * (The heart of the algorithm is right here.)
263 */
264 if(cm->sttype[v] == B_st) { /* a bifurcation state: */
265 pdf = 0.;
266 for (n = 0; n <= Z; n++) {
267 for (leftn = 0; leftn <= n; leftn++) {
268 gamma[v][n] += gamma[cm->cfirst[v]][leftn]*gamma[cm->cnum[v]][n-leftn];
269 }
270 pdf += gamma[v][n];
271 }
272 }
273 else if (v != 0) {
274 /* not a B_st, not the ROOT_S state (only way out of ROOT_S is via a local begin) */
275 pdf = 0.;
276 dv = StateDelta(cm->sttype[v]);
277 for (n = dv; n <= Z; n++) {
278 for (yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
279 y = cm->cfirst[v] + yoffset;
280 gamma[v][n] += t_copy[v][yoffset] * gamma[y][n-dv];
281 }
282 pdf += gamma[v][n];
283 }
284 }
285 /* update gamma[0] by considering local begins from ROOT_S into v */
286 if(begin_copy[v] > 0.) { /* standard local begin transition into v is possible */
287 for (n = 0; n <= Z; n++) {
288 gamma[0][n] += begin_copy[v] * gamma[v][n];
289 /* Note: we only consider possible standard local
290 * begins, not truncated local begins. This could be
291 * considered 'wrong', but it is consistent with earlier
292 * versions of Infernal that didn't allow truncated
293 * begins. If we did consider truncated local begins we
294 * may have slightly looser bands that were more
295 * relevant for truncated scans. However, standard
296 * scans dominate truncated scans, so this approach
297 * is reasonable.
298 */
299 }
300 }
301
302 /* Make sure we've captured "enough" of the distribution (e.g.,
303 * we have captured the right tail; our truncation error is
304 * negligible).
305 * Of our 3 criteria, we apply two to every state:
306 * 1. we're on the right side of the density (pdf is > 0.5
307 * would be enough, but we use .999)
308 * 2. gamma_v(Z) < p * DBL_EPSILON
309 * Must be true if \sum_{i=Z+1...\infty} g(i) < p*DBL_EPSILON,
310 * which is really what we're trying to prove
311 */
312 if(v == 0) pdf = esl_vec_DSum(gamma[0], Z+1);
313 if (pdf <= 0.999 || gamma[v][Z] > max_beta * DBL_EPSILON)
314 {
315 /* fail; truncation error is unacceptable;
316 * caller is supposed to increase Z and rerun.
317 */
318 status = eslERANGE;
319 goto ERROR;
320 }
321
322 /* Renormalize this beam. (Should we really be doing this?) */
323 if (pdf > 1.0) esl_vec_DNorm(gamma[v], Z+1);
324
325 if(qdbinfo != NULL) {
326 /* Determine our left bounds, dmin1 and dmin2, use knowledge that beta2 < beta1*/
327 pdf = 0.;
328 dmin2_set = FALSE;
329 for (n = 0; n <= Z; n++) {
330 pdf += gamma[v][n];
331 if ((! dmin2_set) && pdf > qdbinfo->beta2) { qdbinfo->dmin2[v] = n; dmin2_set = TRUE; }
332 if (( dmin2_set) && pdf > qdbinfo->beta1) { qdbinfo->dmin1[v] = n; break; }
333 }
334 /* And our right bounds, dmax1 and dmax2 */
335 pdf = 0.;
336 dmax2_set = FALSE;
337 for (n = Z; n >= 0; n--) {
338 pdf += gamma[v][n];
339 if ((! dmax2_set) && pdf > qdbinfo->beta2) { qdbinfo->dmax2[v] = n; dmax2_set = TRUE; }
340 if (( dmax2_set) && pdf > qdbinfo->beta1) { qdbinfo->dmax1[v] = n; break; }
341 }
342 }
343 if(v == 0) { /* calculate right bound, to set as ret_W (will be max size of a hit) */
344 pdf = 0.;
345 for (n = Z; n >= 0; n--) {
346 pdf += gamma[0][n];
347 if (pdf > beta_W) { W = n; break; }
348 }
349 }
350 /* Reuse memory where possible, using the "touch" trick:
351 * look at all children y \in C_v.
352 * decrement touch[y]
353 * if touch[y] reaches 0, no higher state v depends on this
354 * state's numbers; release the memory.
355 * we're reusing the end state for every E, so don't free it
356 * 'til we're done.
357 * But if ret_gamma != NULL, don't do this - the
358 * caller wants the whole gamma matrix back.
359 */
360 if (ret_gamma == NULL) {
361 if (cm->sttype[v] == B_st)
362 { /* connected children of a B st are handled specially, remember */
363 y = cm->cfirst[v];
364 if((status = esl_stack_PPush(beamstack, gamma[y])) != eslOK) goto ERROR;
365 gamma[y] = NULL;
366 y = cm->cnum[v];
367 if((status = esl_stack_PPush(beamstack, gamma[y])) != eslOK) goto ERROR;
368 gamma[y] = NULL;
369 }
370 else
371 {
372 for (y = cm->cfirst[v]; y < cm->cfirst[v]+cm->cnum[v]; y++)
373 {
374 touch[y]--;
375 if (touch[y] == 0 && cm->sttype[y] != E_st) {
376 if((status = esl_stack_PPush(beamstack, gamma[y])) != eslOK) goto ERROR;
377 gamma[y] = NULL;
378 }
379 }
380 }
381 }
382 } /*end loop up through all states v*/
383
384 /* Get length distributions of local hits and global hits */
385 if(ret_gamma0_loc != NULL) {
386 ESL_ALLOC(gamma0_loc, sizeof(double) * (Z+1));
387 /* local mode is easy, gamma[0] already contains the length distribution */
388 esl_vec_DCopy(gamma[0], Z+1, gamma0_loc);
389 esl_vec_DNorm(gamma0_loc, Z+1);
390 }
391 if(ret_gamma0_glb != NULL) {
392 ESL_ALLOC(gamma0_glb, sizeof(double) * (Z+1));
393 /* global: we need to do some more calculations first */
394 /* reset global-mode transition probabilities */
395 if(cm->root_trans != NULL) {
396 for (v = 0; v < cm->cnum[0]; v++) t_copy[0][v] = cm->root_trans[v];
397 } /* else t_copy[0] includes appropriate global transition probs */
398 /* recalculate what gamma[0] would be if local begins were off */
399 esl_vec_DSet(gamma0_glb, Z+1, 0.);
400 for (n = 0; n <= Z; n++) {
401 for (yoffset = 0; yoffset < cm->cnum[0]; yoffset++) {
402 y = cm->cfirst[0] + yoffset;
403 gamma0_glb[n] += t_copy[0][yoffset] * gamma[y][n];
404 }
405 }
406 esl_vec_DNorm(gamma0_glb, Z+1);
407 }
408
409 if ((! BandTruncationNegligible(gamma[0], W, Z, NULL)) ||
410 (qdbinfo != NULL && (! BandTruncationNegligible(gamma[0], qdbinfo->dmax1[0], Z, NULL))) ||
411 (qdbinfo != NULL && (! BandTruncationNegligible(gamma[0], qdbinfo->dmax2[0], Z, NULL))))
412 {
413 status = eslERANGE;
414 goto ERROR;
415 }
416
417 if(qdbinfo != NULL) qdbinfo->setby = CM_QDBINFO_SETBY_BANDCALC;
418
419 /*if(qdbinfo != NULL) DumpCMQDBInfo(stdout, cm, qdbinfo);*/
420
421 if (ret_W != NULL) *ret_W = W;
422 if (ret_gamma != NULL) *ret_gamma = gamma; else FreeBandDensities(cm, gamma);
423 if (ret_gamma0_loc != NULL) *ret_gamma0_loc = gamma0_loc; else if(gamma0_loc != NULL) free(gamma0_loc);
424 if (ret_gamma0_glb != NULL) *ret_gamma0_glb = gamma0_glb; else if(gamma0_glb != NULL) free(gamma0_glb);
425 status = eslOK;
426
427 ERROR:
428 if(status != eslOK) {
429 if (ret_W != NULL) *ret_W = 0;
430 if (ret_gamma != NULL) *ret_gamma = NULL;
431 if (ret_gamma0_loc != NULL) *ret_gamma0_loc = NULL;
432 if (ret_gamma0_glb != NULL) *ret_gamma0_glb = NULL;
433 if (gamma != NULL) FreeBandDensities(cm, gamma);
434 if (gamma0_loc != NULL) free(gamma0_loc);
435 if (gamma0_glb != NULL) free(gamma0_glb);
436 }
437
438 /* Free the reused stack of beams.
439 */
440 if(t_copy != NULL) {
441 if(t_copy[0] != NULL) free(t_copy[0]);
442 free(t_copy);
443 }
444 if(begin_copy != NULL) free(begin_copy);
445
446 free(touch);
447 while (esl_stack_PPop(beamstack, (void **) &tmp) != eslEOD) free(tmp);
448 esl_stack_Destroy(beamstack);
449
450 return status;
451 }
452
453
454 /* Function: BandTruncationNegligible()
455 * Incept: SRE, Sun Oct 19 10:43:21 2003 [St. Louis]
456 *
457 * Purpose: Verifies that for this choice of Z, the truncation error,
458 * D = \sum_{n=Z+1}{\infty} \gamma_v(n),
459 * will not affect our calculation of the right bound, b (dmax),
460 * based on the probability mass we can observe,
461 * C = \sum_{n=b+1}{Z} \gamma_v(n).
462 *
463 * Specifically, we want D such that C + D = C; that is,
464 * D < C * DBL_EPSILON.
465 *
466 * We assume that the tail of \gamma is decreasing
467 * geometrically. This lets us predict the tail is
468 * \gamma_v(n) = \gamma_v(Z+1) \beta^{n-Z-1}
469 *
470 * and from the sum of an infinite geometric series, combined
471 * with \gamma_v(Z+1) = \beta \gamma_v(Z), we obtain:
472 * \gamma_v(Z) \beta
473 * D' = -----------------
474 * 1 - \beta
475 *
476 * How well D' approximates the true truncated tail mass D
477 * depends on how valid the assumption of geometrically
478 * decreasing tails is. For a single insert state, one
479 * obtains a geometrically decreasing tail. For a mixture
480 * of geometric distributions, if one fits the low side,
481 * one overestimates the rate of convergence to 0, and so
482 * underestimates D; D' <= D. But if anything, we want D' >= D;
483 * an upper bound on D lets us prove D < C * epsilon.
484 * Puzzlingly, this does not seem to be a problem. For
485 * a variety of models and states, D' is indeed an
486 * overestimate of D; empirically, the tail density converges to zero
487 * supergeometrically, which I can't explain.
488 *
489 * Using ret_beta to verify:
490 *
491 * D' = (beta / (1.-beta)) * density[Z];
492 * D = \sum_{n=b+1}{\infty} density[Z];
493 * D' >= D.
494 *
495 * test for an even stronger criterion:
496 * let estimated density g(n) = gamma[Z] * \beta^(n-Z);
497 * g(n) >= gamma[n] for all n > Z.
498 *
499 * In the testsuite, "check_bandtruncation" empirically verifies
500 * D' > D.
501 *
502 * Args: density - one density \gamma_v() calculated by BandCalculationEngine();
503 * usually the root (if Z is big enough for the root, it's
504 * big enough for every state).
505 * b - the left bound dmax[v]
506 * Z - the maximum length; gamma_v[] runs [0..Z]
507 * ret_beta - RETURN (optional): the geometric decay constant \beta,
508 * obtained by simple linear fit to log gamma().
509 *
510 *
511 * Returns: 1 if truncation error is negligible (D' < C * DBL_EPSILON)
512 * 0 if truncation error is not negigible, and caller will
513 * have to worry about increasing Z.
514 *
515 * Xref: STL7 p.128.
516 */
517 int
518 BandTruncationNegligible(double *density, int b, int Z, double *ret_beta)
519 {
520 double logbeta;
521 double beta; /* geometric decay parameter */
522 double C; /* area under density from b+1..Z inclusive */
523 double D; /* area under unseen density from Z+1..\infty */
524 int i;
525
526 /* Sum up how much probability mass we do see,
527 * in the truncated tail from b+1..Z.
528 */
529 C = 0.;
530 for (i = b+1; i <= Z; i++) C += density[i];
531
532 /* If density is falling off as a geometric, log(beta) is
533 * the slope of log(p). Estimate slope quickly and crudely, by a
534 * simple 2-point fit at our boundaries b+1 and Z.
535 */
536 logbeta = (log(density[Z]) - log(density[b+1])) / (Z - b - 1);
537 beta = exp(logbeta);
538
539 /* We can now guess at the missing probability mass from Z+1...\infty,
540 * because a finite geometric series converges to 1/(1+\beta).
541 */
542 D = (beta / (1.-beta)) * density[Z];
543
544 if (ret_beta != NULL) *ret_beta = beta;
545
546 if (D < C * DBL_EPSILON) return 1;
547 else return 0;
548 }
549
550 /* Function: BandMonteCarlo()
551 * Incept: SRE, Fri Oct 17 08:01:42 2003 [St. Louis]
552 *
553 * Purpose: Calculate the gamma_v densities by Monte Carlo simulation,
554 * by sampling parsetrees from the CM. gamma[v][i] is the
555 * observed number of subsequences of length i rooted at v
556 * in the sample. These counts are left unnormalized; different
557 * states are reached with different probabilities, and the
558 * caller may want to test the Monte Carlo observed counts
559 * against predicted counts (see bandcyk-montecarlo-test in
560 * the testsuite).
561 *
562 * Args: cm - the model to sample from
563 * nsample - number of Monte Carlo sampled parsetrees
564 * Z - maximum subsequence length in densities
565 * ret_gamma - RETURN: gamma[v][n], [0..M-1][0..Z] as
566 * unnormalized observed counts.
567 *
568 * Returns: 1 on success.
569 * 0 on failure: one or more samples had a length too great to be
570 * captured by Z.
571 *
572 * Caller frees the returned gamma with FreeBandDensities().
573 *
574 * Note: Dies (cm_Fail()) from memory allocation error, without
575 * cleanup.
576 */
577 int
578 BandMonteCarlo(CM_t *cm, int nsample, int Z, double ***ret_gamma)
579 {
580 Parsetree_t *tr; /* sampled parsetree */
581 double **gamma; /* RETURN: the densities */
582 int i; /* counter over samples */
583 int seqlen; /* length of sampled sequence */
584 int tidx; /* index on parsetree */
585 int v; /* state used at a parsetree node */
586 int n; /* subseq length at a parsetree node */
587 int status; /* return status. */
588 char *name; /* name for the seq we've emitted */
589 ESL_RANDOMNESS *r = NULL; /* source of randomness */
590 int namelen; /* max int size for name */
591 char errbuf[eslERRBUFSIZE];
592
593 /* Create and seed RNG */
594 if ((r = esl_randomness_CreateTimeseeded()) == NULL)
595 cm_Fail("Failed to create random number generator: probably out of memory");
596
597 /* Allocate gamma, completely; and initialize to zeros.
598 * For consistency w/ BandCalculationEngine(), allocate a single
599 * shared end deck at M-1, and point other ends at it - even
600 * though P(n=0) = 1.0 by definition at the E's and we don't
601 * really need to calculate it. Then we can use FreeBandDensities()
602 * for gamma matrices alloc'ed in either function.
603 */
604 ESL_ALLOC(gamma, (sizeof(double *) * cm->M));
605 ESL_ALLOC(gamma[cm->M-1], (sizeof(double) * (Z+1)));
606 esl_vec_DSet(gamma[cm->M-1], Z+1, 0.0);
607 for (v = 0; v < cm->M-1; v++)
608 {
609 if (cm->sttype[v] != E_st)
610 {
611 ESL_ALLOC(gamma[v], sizeof(double) * (Z+1));
612 esl_vec_DSet(gamma[v], Z+1, 0.0);
613 }
614 else
615 gamma[v] = gamma[cm->M-1];
616 }
617
618 namelen = 3 + IntMaxDigits() + 1; /* IntMaxDigits() returns number of digits in INT_MAX */
619
620 /* Count Monte Carlo samples of subsequence lengths for
621 * all nodes of sampled parsetrees.
622 */
623 status = 1;
624 for (i = 0; i < nsample; i++) {
625 ESL_ALLOC(name, sizeof(char) * namelen);
626 snprintf(name, namelen, "seq%d", i+1);
627 if(EmitParsetree(cm, errbuf, r, name, FALSE, &tr, NULL, &seqlen) != eslOK) cm_Fail(errbuf);
628 free(name);
629 if (seqlen > Z) {
630 FreeParsetree(tr);
631 status = 0; /* set status to FAILED */
632 continue;
633 }
634
635 /* The parsetree, though it's a tree, is stored as an
636 * array - so traversing it in preorder is trivial. It's
637 * already arranged in preorder.
638 */
639 for (tidx = 0; tidx < tr->n; tidx++)
640 {
641 v = tr->state[tidx];
642 n = (cm->sttype[v] == E_st) ? 0 : tr->emitr[tidx] - tr->emitl[tidx] + 1;
643 gamma[v][n] += 1.;
644 }
645 FreeParsetree(tr);
646 }
647
648 /* Return gamma, the observed counts (unnormalized densities).
649 */
650 *ret_gamma = gamma;
651 esl_randomness_Destroy(r);
652 ESL_DPRINTF1(("#DEBUG: Returning %d from BandMonteCarlo() (1 is passed, 0 failed)\n", status));
653 return status;
654
655 ERROR:
656 cm_Fail("Memory allocation error.\n");
657 return eslFAIL; /* never reached */
658 }
659
660
661 /* Function: FreeBandDensities()
662 * Incept: SRE, Thu Oct 16 08:30:47 2003 [St. Louis]
663 *
664 * Purpose: Free a gamma[] array that was returned by BandCalculationEngine().
665 * Best to handle this with a special function because of the reuse
666 * of the END rows - only cm->M-1 is actually allocated, and other
667 * ENDs just point at that one. Too easy to double free() if we
668 * leave this tricky business to the caller.
669 *
670 * Args: cm - the model we build the band densities, gamma[], for.
671 * gamma - the band densities. Doesn't matter if this is a full
672 * or partial (ret_gamma in BandCalculationEngine() was
673 * non-NULL or NULL.)
674 *
675 * Returns: (void)
676 *
677 * Xref: STL7 p130.
678 */
679 void
680 FreeBandDensities(CM_t *cm, double **gamma)
681 {
682 int v;
683 for (v = 0; v < cm->M; v++)
684 if (cm->sttype[v] != E_st && gamma[v] != NULL)
685 { free(gamma[v]); gamma[v] = NULL; }
686 free(gamma[cm->M-1]); /* free the end state */
687 free(gamma);
688 }
689
690
691 /* A couple of quick hacks. ...
692 * Print an XMGRACE xy file for a specified v, showing the
693 * cumulative distribution. Needed this for the R01 renewal.
694 * SRE, Wed Feb 19 08:35:32 2003
695 */
696 void
697 PrintBandGraph(FILE *fp, double **gamma, int *min, int *max, int v, int Z)
698 {
699 int n;
700
701 for (n = 0; n <= Z; n++)
702 fprintf(fp, "%d %.6f\n", n, gamma[v][n]);
703 fprintf(fp, "&\n");
704 fprintf(fp, "%d 0\n", min[v]);
705 fprintf(fp, "%d 1.0\n", min[v]);
706 fprintf(fp, "&\n");
707 fprintf(fp, "%d 0\n", max[v]);
708 fprintf(fp, "%d 1.0\n", max[v]);
709 fprintf(fp, "&\n");
710 }
711 /* ... and, estimate the total savings in DP cells filled.
712 */
713 void
714 PrintDPCellsSaved(CM_t *cm, int *min, int *max, int W)
715 {
716 int v;
717 int after, before;
718
719 before = after = 0;
720 for (v = 0; v < cm->M; v++)
721 {
722 if (cm->sttype[v] != E_st) {
723 after += max[v] - min[v] + 1;
724 before += W;
725 }
726 }
727 printf("Before: something like %d\n", before);
728 printf("After: something like %d\n", after);
729 printf("Speedup: maybe %.2f fold\n", (float) before / (float) after);
730 }
731
732
733 /* EPN 07.22.05
734 * ExpandBands()
735 * Function: ExpandBands
736 *
737 * Purpose: Called when the sequence we are about to align
738 * using bands is either shorter in length than
739 * the dmin on the root state, or longer in length
740 * than the dmax on the root state.
741 *
742 * This function expands the bands on ALL states
743 * v=1..cm->M-1 in the following manner :
744 *
745 * case 1 : target len < dmin[0]
746 * subtract (dmin[0]-target len) from
747 * dmin of all states, and ensure
748 * dmin[v]>=0 for all v.
749 * Further :
750 * if cm->sttype[v] == MP_st ensure dmin[v]>=2;
751 * if cm->sttype[v] == IL_st || ML_st ensure dmin[v]>=1;
752 * if cm->sttype[v] == IR_st || MR_st ensure dmin[v]>=1;
753 *
754 * case 2 : target len > dmax[0]
755 * add (target len-dmax[0] to dmax
756 * of all states.
757 *
758 * Prior to handling such situtations with this
759 * hack, the program would choke and die. This
760 * hacky approach is used as a simple, inefficient
761 * not well thought out, but effective way to
762 * solve this problem.
763 *
764 * Args: cm - the CM
765 * tlen - length of target sequence about to be aligned
766 * dmin - minimum d bound for each state v; [0..v..M-1]
767 * may be modified in this function
768 * dmax - maximum d bound for each state v; [0..v..M-1]
769 * may be modified in this function
770 *
771 * Returns: (void)
772 */
773
774 void
775 ExpandBands(CM_t *cm, int tlen, int *dmin, int *dmax)
776 {
777 int v;
778 int diff;
779 int root_min;
780 int root_max;
781 int M = cm->M;
782 root_min = dmin[0];
783 root_max = dmax[0];
784
785 if(tlen < root_min)
786 {
787 diff = root_min - tlen;
788 for(v=0; v<M; v++)
789 {
790 dmin[v] -= diff;
791 if((cm->sttype[v] == MP_st) && (dmin[v] < 2))
792 dmin[v] = 2;
793 else if(((cm->sttype[v] == IL_st) || (cm->sttype[v] == ML_st))
794 && (dmin[v] < 1))
795 dmin[v] = 1;
796 else if(((cm->sttype[v] == IR_st) || (cm->sttype[v] == MR_st))
797 && (dmin[v] < 1))
798 dmin[v] = 1;
799 else if(dmin[v] < 0)
800 dmin[v] = 0;
801 }
802 }
803 else if(tlen > root_max)
804 {
805 diff = tlen - root_min;
806 for(v=0; v<M; v++)
807 {
808 dmax[v] += diff;
809 }
810 }
811 }
812
813 /* EPN 08.15.05
814 * qdb_trace_info_dump()
815 * Function: qdb_trace_info_dump
816 *
817 * Purpose: Called when the user has enabled the --banddump
818 * options. This function determines how close the
819 * trace was to the bands at each state in the trace,
820 * and prints out that information in differing levels
821 * of verbosity depending on an input parameter
822 * (bdump_level).
823 *
824 * Args: tr - the parsetree (trace)
825 * dmin - minimum d bound for each state v; [0..v..M-1]
826 * may be modified in this function
827 * dmax - maximum d bound for each state v; [0..v..M-1]
828 * may be modified in this function
829 * bdump_level - level of verbosity
830 * Returns: (void)
831 */
832
833 void
834 qdb_trace_info_dump(CM_t *cm, Parsetree_t *tr, int *dmin, int *dmax, int bdump_level)
835 {
836 int status;
837 char **sttypes;
838 char **nodetypes;
839 int v, i, j, d, tpos;
840 int mindiff; /* d - dmin[v] */
841 int maxdiff; /* dmax[v] - d */
842
843 ESL_ALLOC(sttypes, sizeof(char *) * 10);
844 sttypes[0] = "D";
845 sttypes[1] = "MP";
846 sttypes[2] = "ML";
847 sttypes[3] = "MR";
848 sttypes[4] = "IL";
849 sttypes[5] = "IR";
850 sttypes[6] = "S";
851 sttypes[7] = "E";
852 sttypes[8] = "B";
853 sttypes[9] = "EL";
854
855 ESL_ALLOC(nodetypes, sizeof(char *) * 8);
856 nodetypes[0] = "BIF";
857 nodetypes[1] = "MATP";
858 nodetypes[2] = "MATL";
859 nodetypes[3] = "MATR";
860 nodetypes[4] = "BEGL";
861 nodetypes[5] = "BEGR";
862 nodetypes[6] = "ROOT";
863 nodetypes[7] = "END";
864
865 for (tpos = 0; tpos < tr->n; tpos++)
866 {
867 v = tr->state[tpos];
868 i = tr->emitl[tpos];
869 j = tr->emitr[tpos];
870 d = j-i+1;
871
872 if(cm->sttype[v] != EL_st)
873 {
874 mindiff = d-dmin[v];
875 maxdiff = dmax[v]-d;
876 if(bdump_level > 1 || ((mindiff < 0) || (maxdiff < 0)))
877 printf("%-4s %-3s v: %4d | d: %4d | dmin: %4d | dmax: %4d | %3d | %3d |\n", nodetypes[(int) cm->ndtype[(int) cm->ndidx[v]]], sttypes[(int) cm->sttype[v]], v, d, dmin[v], dmax[v], mindiff, maxdiff);
878 }
879 else
880 {
881 if(bdump_level > 1)
882 printf("%-8s v: %4d | d: %4d |\n", sttypes[(int) cm->sttype[v]], v, d);
883 }
884 }
885 free(sttypes);
886 free(nodetypes);
887 return;
888
889 ERROR:
890 cm_Fail("Memory allocation error.");
891 }
892
893 /* Function: CreateCMQDBInfo()
894 * Date: EPN, Sat Dec 10 06:24:53 2011
895 *
896 * Purpose: Allocate and initialize a CM_QDBINFO object
897 * given <M> the number of states in the CM
898 * we'll use the QDBs for.
899 *
900 * Returns: Newly allocated CM_QDBINFO object. NULL if out
901 * of memory.
902 */
903 CM_QDBINFO *
904 CreateCMQDBInfo(int M, int clen)
905 {
906 int status;
907 CM_QDBINFO *qdbinfo = NULL;
908 ESL_ALLOC(qdbinfo, sizeof(CM_QDBINFO));
909
910 qdbinfo->M = M;
911
912 qdbinfo->beta1 = DEFAULT_BETA_QDB1;
913 ESL_ALLOC(qdbinfo->dmin1, sizeof(int) * M);
914 ESL_ALLOC(qdbinfo->dmax1, sizeof(int) * M);
915 esl_vec_ISet(qdbinfo->dmin1, M, 0);
916 esl_vec_ISet(qdbinfo->dmax1, M, clen*2);
917
918 qdbinfo->beta2 = DEFAULT_BETA_QDB2;
919 ESL_ALLOC(qdbinfo->dmin2, sizeof(int) * M);
920 ESL_ALLOC(qdbinfo->dmax2, sizeof(int) * M);
921 esl_vec_ISet(qdbinfo->dmin2, M, 0);
922 esl_vec_ISet(qdbinfo->dmax2, M, clen*2);
923
924 qdbinfo->setby = CM_QDBINFO_SETBY_INIT;
925
926 return qdbinfo;
927
928 ERROR:
929 if(qdbinfo != NULL) FreeCMQDBInfo(qdbinfo);
930 return NULL;
931 }
932
933
934 /* Function: SizeofCMQDBInfo()
935 * Date: EPN, Wed Jan 18 05:01:42 2012
936 *
937 * Purpose: Determine and return the size of
938 * a CM_QDBINFO object in Mb.
939 *
940 * Returns: Size of the CM_QDBINFO object in Mb.
941 */
942 float
943 SizeofCMQDBInfo(CM_QDBINFO *qdbinfo)
944 {
945 float bytes;
946
947 if(qdbinfo == NULL) return 0.;
948
949 bytes = sizeof(CM_QDBINFO);
950 bytes += sizeof(int) * qdbinfo->M; /* dmin1 */
951 bytes += sizeof(int) * qdbinfo->M; /* dmax1 */
952 bytes += sizeof(int) * qdbinfo->M; /* dmin2 */
953 bytes += sizeof(int) * qdbinfo->M; /* dmax2 */
954
955 bytes *= 0.000001; /* convert to Mb */
956
957 return bytes;
958 }
959
960 /* Function: FreeCMQDBInfo()
961 * Date: EPN, Sat Dec 10 06:31:12 2011
962 *
963 * Purpose: Free a CM_QDBINFO object.
964 *
965 * Returns: void
966 */
967 void
968 FreeCMQDBInfo(CM_QDBINFO *qdbinfo)
969 {
970 if(qdbinfo == NULL) return;
971
972 if(qdbinfo->dmin1 != NULL) free(qdbinfo->dmin1);
973 if(qdbinfo->dmax1 != NULL) free(qdbinfo->dmax1);
974 if(qdbinfo->dmin2 != NULL) free(qdbinfo->dmin2);
975 if(qdbinfo->dmax2 != NULL) free(qdbinfo->dmax2);
976
977 free(qdbinfo);
978 return;
979 }
980
981 /* Function: CopyCMQDBInfo()
982 * Synopsis: Copy a CM_QDBINFO object.
983 * Date: EPN, Sat Dec 10 06:55:17 2011
984 *
985 * Purpose: Copies qdbinfo <src> to qdbinfo <dst>, where <dst>
986 * has already been allocated to be of sufficient size.
987 *
988 * Returns: <eslOK> on success.
989 * Throws: <eslEINVAL> if <dst> is too small
990 * to fit <src>, errbuf is filled.
991 */
992 int
993 CopyCMQDBInfo(const CM_QDBINFO *src, CM_QDBINFO *dst, char *errbuf)
994 {
995 if (src->M != dst->M) ESL_FAIL(eslEINVAL, errbuf, "destination qdbinfo not equal to size of source qdbinfo");
996
997 dst->beta1 = src->beta1;
998 esl_vec_ICopy(src->dmin1, src->M, dst->dmin1);
999 esl_vec_ICopy(src->dmax1, src->M, dst->dmax1);
1000
1001 dst->beta2 = src->beta2;
1002 esl_vec_ICopy(src->dmin2, src->M, dst->dmin2);
1003 esl_vec_ICopy(src->dmax2, src->M, dst->dmax2);
1004
1005 dst->setby = src->setby;
1006
1007 return eslOK;
1008 }
1009
1010
1011 /* Function: qdbinfo_setby_to_string()
1012 * Date: EPN, Tue Dec 13 09:55:42 2011
1013 */
1014 char *
1015 qdbinfo_setby_to_string(int setby)
1016 {
1017 switch (setby) {
1018 case CM_QDBINFO_SETBY_INIT: return "CM_QDBINFO_SETBY_INIT";
1019 case CM_QDBINFO_SETBY_CMFILE: return "CM_QDBINFO_SETBY_CMFILE";
1020 case CM_QDBINFO_SETBY_BANDCALC: return "CM_QDBINFO_SETBY_BANDCALC";
1021 case CM_QDBINFO_SETBY_SUBINIT: return "CM_QDBINFO_SETBY_SUBINIT";
1022 default: cm_Fail("bogus CM_QDBINFO_SETBY type: %d\n", setby);
1023 }
1024 return ""; /* NEVERREACHED */
1025 }
1026
1027 /* Function: DumpCMQDBInfo()
1028 * Synopsis: Print contents of a CM_QDBINFO object to <fp>.
1029 * Date: EPN, Tue Dec 13 09:52:05 2011
1030 *
1031 * Returns: void.
1032 */
1033 void
1034 DumpCMQDBInfo(FILE *fp, CM_t *cm, CM_QDBINFO *qdbinfo)
1035 {
1036 int v;
1037
1038 fprintf(fp, "CM_QDBINFO dump\n");
1039 fprintf(fp, "------------------\n");
1040 fprintf(fp, "# M: %d\n", qdbinfo->M);
1041 fprintf(fp, "# setby: %s\n", qdbinfo_setby_to_string(qdbinfo->setby));
1042 fprintf(fp, "# beta1: %g\n", qdbinfo->beta1);
1043 fprintf(fp, "# beta2: %g\n", qdbinfo->beta2);
1044 fprintf(fp, "# %8s %8s %6s %6s %5s %5s %5s %5s %5s %5s\n", "stidx(v)", "ndidx", "ndtype", "sttype", "dmin2","dmin1", "dmax1", "dmax2", "bwd1", "bwd2");
1045 fprintf(fp, "# %8s %8s %6s %6s %5s %5s %5s %5s %5s %5s\n", "--------", "--------", "------", "------", "-----", "----", "-----", "-----", "------","-----");
1046 for(v = 0; v < cm->M; v++) {
1047 fprintf(fp, " %8d %8d %-6s %-6s %5d %5d %5d %5d %5d %5d\n", v, cm->ndidx[v], Nodetype(cm->ndtype[cm->ndidx[v]]), Statetype(cm->sttype[v]),
1048 qdbinfo->dmin2[v], qdbinfo->dmin1[v], qdbinfo->dmax1[v], qdbinfo->dmax2[v],
1049 qdbinfo->dmax1[v] - qdbinfo->dmin1[v] + 1, qdbinfo->dmax2[v] - qdbinfo->dmin2[v] + 1);
1050 }
1051 fprintf(fp, "//\n");
1052 return;
1053 }
1054
1055 /* Function: CheckCMQDBInfo()
1056 * Synopsis: Check if QDBs in CM_QDBINFO need to be recalculated.
1057 * Date: EPN, Tue Dec 13 13:39:06 2011
1058 *
1059 * Purpose: Check if beta values in a CM_QDBINFO object are equal to
1060 * passed in beta values. If <do_check1>, we check if
1061 * cm->qdbinfo->beta1 == <beta1> and if <do_check2>, we
1062 * check if cm->qdbinfo->beta2 == <beta2>. We return eslOK
1063 * if neither check fails and eslFAIL if one or both
1064 * does. As a special case if cm->qdbinfo->setby ==
1065 * CM_QDBINFO_SETBY_INIT then we always return eslFAIL
1066 * because it means the QDBs in cm->qdbinfo are in their
1067 * initialized state and haven't yet been calculated.
1068 *
1069 * Returns: eslOK if we don't need to recalculate the QDBs in cm->qdbinfo
1070 * eslFAIL if we do need to recalculate the QDBs in cm->qdbinfo
1071 */
1072 int
1073 CheckCMQDBInfo(CM_QDBINFO *qdbinfo, double beta1, int do_check1, double beta2, int do_check2)
1074 {
1075 if(qdbinfo->setby == CM_QDBINFO_SETBY_INIT) return eslFAIL;
1076 if(qdbinfo->setby == CM_QDBINFO_SETBY_SUBINIT) return eslFAIL;
1077
1078 if(do_check1) {
1079 if(fabs(qdbinfo->beta1 - beta1) > 1E-20) return eslFAIL;
1080 }
1081 if(do_check2) {
1082 if(fabs(qdbinfo->beta2 - beta2) > 1E-20) return eslFAIL;
1083 }
1084
1085 return eslOK;
1086 }