Debian Codegraph @

hmmer/src/p7_domaindef.c

raw symbols SCIP
1 /* Definition of multidomain structure of a target sequence, and
2 * rescoring as a sum of individual domains, with null2 correction.
3 *
4 * Contents:
5 * 1. The P7_DOMAINDEF object: allocation, reuse, destruction
6 * 2. Routines inferring domain structure of a target sequence
7 * 3. Internal routines
8 *
9 * Exegesis:
10 *
11 * The key function here is <p7_domaindef_ByPosteriorHeuristics()>.
12 * Everything else is support structure.
13 *
14 * When you call <p7_domaindef_ByPosteriorHeuristics()>, you have a
15 * per-sequence hit that's judged significant, and you've calculated
16 * Forward/Backward score matrices for the complete sequence. Thus,
17 * the input data are the model <gm>, the sequence <sq>, and filled-in
18 * forward and backward matrices <fwd>, <bck>.
19 *
20 * The function then chews over this data, using posterior
21 * probabilities and heuristics to define, score, and obtain
22 * display-ready alignments for individual domains. When it's done,
23 * your <fwd> and <bck> matrices have been effectively destroyed (they
24 * get reused for individual domain alignment calculations), and
25 * <ddef> contains all the per-domain results you need. It returns to
26 * you the number of domains it's defined (in <ret_ndom>), and the
27 * total per-sequence score derived by a sum of individual domain
28 * scores (in <ret_sc>).
29 *
30 * The <P7_DOMAINDEF> structure is a reusable container that manages
31 * all the necessary working memory and heuristic thresholds.
32 *
33 * SRE, Thu Jan 24 09:28:01 2008 [Janelia]
34 */
35 #include <p7_config.h>
36
37 #include <math.h>
38 #include <string.h>
39
40 #include "easel.h"
41 #include "esl_random.h"
42 #include "esl_sq.h"
43 #include "esl_vectorops.h"
44
45 #include "hmmer.h"
46
47 static int is_multidomain_region (P7_DOMAINDEF *ddef, int i, int j);
48 static int region_trace_ensemble (P7_DOMAINDEF *ddef, const P7_OPROFILE *om, const ESL_DSQ *dsq, int ireg, int jreg, const P7_OMX *fwd, P7_OMX *wrk, int *ret_nc);
49 static int rescore_isolated_domain(P7_DOMAINDEF *ddef, P7_OPROFILE *om, const ESL_SQ *sq, const ESL_SQ *ntsq, P7_OMX *ox1, P7_OMX *ox2,
50 int i, int j, int null2_is_done, P7_BG *bg, int long_target, P7_BG *bg_tmp, float *scores_arr, float *fwd_emissions_arr);
51
52
53 /*****************************************************************
54 * 1. The P7_DOMAINDEF object: allocation, reuse, destruction
55 *****************************************************************/
56
57 /* Function: p7_domaindef_Create()
58 * Synopsis: Creates a new <P7_DOMAINDEF> object.
59 * Incept: SRE, Fri Jan 25 13:21:31 2008 [Janelia]
60 *
61 * Purpose: Creates a new <P7_DOMAINDEF> object, with <r> registered
62 * as its random number generator, using default settings
63 * for all thresholds.
64 *
65 * Returns: a pointer to the new <P7_DOMAINDEF> object.
66 *
67 * Throws: <NULL> on allocation failure.
68 */
69 P7_DOMAINDEF *
70 p7_domaindef_Create(ESL_RANDOMNESS *r)
71 {
72 P7_DOMAINDEF *ddef = NULL;
73 int Lalloc = 512; /* this initial alloc doesn't matter much; space is realloced as needed */
74 int nalloc = 32;
75 int status;
76
77 /* level 1 alloc */
78 ESL_ALLOC(ddef, sizeof(P7_DOMAINDEF));
79 ddef->mocc = ddef->btot = ddef->etot = NULL;
80 ddef->n2sc = NULL;
81 ddef->sp = NULL;
82 ddef->tr = NULL;
83 ddef->dcl = NULL;
84
85 /* level 2 alloc: posterior prob arrays */
86 ESL_ALLOC(ddef->mocc, sizeof(float) * (Lalloc+1));
87 ESL_ALLOC(ddef->btot, sizeof(float) * (Lalloc+1));
88 ESL_ALLOC(ddef->etot, sizeof(float) * (Lalloc+1));
89 ESL_ALLOC(ddef->n2sc, sizeof(float) * (Lalloc+1));
90 ddef->mocc[0] = ddef->etot[0] = ddef->btot[0] = 0.;
91 ddef->n2sc[0] = 0.;
92 ddef->Lalloc = Lalloc;
93 ddef->L = 0;
94
95 /* level 2 alloc: results storage */
96 ESL_ALLOC(ddef->dcl, sizeof(P7_DOMAIN) * nalloc);
97 ddef->nalloc = nalloc;
98 ddef->ndom = 0;
99
100 ddef->nexpected = 0.0;
101 ddef->nregions = 0;
102 ddef->nclustered = 0;
103 ddef->noverlaps = 0;
104 ddef->nenvelopes = 0;
105
106 /* default thresholds */
107 ddef->rt1 = 0.25;
108 ddef->rt2 = 0.10;
109 ddef->rt3 = 0.20;
110 ddef->nsamples = 200;
111 ddef->min_overlap = 0.8;
112 ddef->of_smaller = TRUE;
113 ddef->max_diagdiff = 4;
114 ddef->min_posterior = 0.25;
115 ddef->min_endpointp = 0.02;
116
117 /* allocate reusable, growable objects that domain def reuses for each seq */
118 ddef->sp = p7_spensemble_Create(1024, 64, 32); /* init allocs = # sampled pairs; max endpoint range; # of domains */
119 ddef->tr = p7_trace_CreateWithPP();
120 ddef->gtr = p7_trace_Create();
121
122 /* keep a copy of ptr to the RNG */
123 ddef->r = r;
124 ddef->do_reseeding = TRUE;
125 return ddef;
126
127 ERROR:
128 p7_domaindef_Destroy(ddef);
129 return NULL;
130 }
131
132
133 /* p7_domaindef_GrowTo()
134 * Synopsis: Reallocates a <P7_DOMAINDEF> for new seq length <L>
135 * Incept: SRE, Fri Jan 25 13:27:24 2008 [Janelia]
136 *
137 * Purpose: Reallocates a <P7_DOMAINDEF> object <ddef> so that
138 * it can hold a sequence of up to <L> residues.
139 *
140 * (This might be a no-op, if <ddef> is already large
141 * enough.)
142 *
143 * Returns: <eslOK> on success.
144 *
145 * Throws: <eslEMEM> on allocation failure. In this case, the
146 * data in <ddef> are unaffected.
147 */
148 int
149 p7_domaindef_GrowTo(P7_DOMAINDEF *ddef, int L)
150 {
151 void *p;
152 int status;
153
154 if (L <= ddef->Lalloc) return eslOK;
155
156 ESL_RALLOC(ddef->mocc, p, sizeof(float) * (L+1));
157 ESL_RALLOC(ddef->btot, p, sizeof(float) * (L+1));
158 ESL_RALLOC(ddef->etot, p, sizeof(float) * (L+1));
159 ESL_RALLOC(ddef->n2sc, p, sizeof(float) * (L+1));
160 ddef->Lalloc = L;
161 return eslOK;
162
163 ERROR:
164 return status;
165 }
166
167
168 /* Function: p7_domaindef_Reuse()
169 * Synopsis: Prepare to reuse a <P7_DOMAINDEF> on a new sequence.
170 * Incept: SRE, Fri Jan 25 13:48:36 2008 [Janelia]
171 *
172 * Purpose: Prepare a <P7_DOMAINDEF> object <ddef> to be reused on
173 * a new sequence, reusing as much memory as possible.
174 *
175 * Note: Because of the way we handle alidisplays, handing them off to
176 * the caller, we don't reuse their memory; any unused
177 * alidisplays are destroyed. It's not really possible to
178 * reuse alidisplay memory. We need alidisplays to persist
179 * until all sequences have been processed and we're
180 * writing our final output to the user.
181 *
182 * Returns: <eslOK> on success.
183 */
184 int
185 p7_domaindef_Reuse(P7_DOMAINDEF *ddef)
186 {
187 int status;
188 int d;
189
190 /* If ddef->dcl is NULL, we turned the domain list over to a P7_HIT
191 * for permanent storage, and we need to allocate a new one;
192 * else, reuse the one we've got.
193 */
194 if (ddef->dcl == NULL)
195 ESL_ALLOC(ddef->dcl, sizeof(P7_DOMAIN) * ddef->nalloc);
196 else
197 {
198 for (d = 0; d < ddef->ndom; d++) {
199 p7_alidisplay_Destroy(ddef->dcl[d].ad); ddef->dcl[d].ad = NULL;
200 free(ddef->dcl[d].scores_per_pos); ddef->dcl[d].scores_per_pos = NULL;
201 }
202
203 }
204 ddef->ndom = 0;
205 ddef->L = 0;
206
207 ddef->nexpected = 0.0;
208 ddef->nregions = 0;
209 ddef->nclustered = 0;
210 ddef->noverlaps = 0;
211 ddef->nenvelopes = 0;
212
213 p7_spensemble_Reuse(ddef->sp);
214 p7_trace_Reuse(ddef->tr); /* probable overkill; should already have been called */
215 p7_trace_Reuse(ddef->gtr); /* likewise */
216 return eslOK;
217
218 ERROR:
219 return status;
220 }
221
222
223 /* Function: p7_domaindef_DumpPosteriors()
224 * Synopsis: Output posteriors that define domain structure to a stream.
225 * Incept: SRE, Fri Feb 29 08:32:14 2008 [Janelia]
226 *
227 * Purpose: Output the vectors from <ddef> that are used to
228 * define domain structure to a stream <ofp>, in xmgrace format.
229 *
230 * There are four vectors. The first set is
231 * <mocc[1..i..L]>, the probability that residue <i> is
232 * emitted by the core model (is in a domain). The second
233 * set is <btot[1..i..L]>, the cumulative expected number
234 * of times that a domain uses a B state (starts) at or
235 * before position <i>. The third set is <etot[1..i..L]>,
236 * the cumulative expected number of times that a domain
237 * uses an E state (ends) at or before position <i>. The
238 * fourth set is <n2sc[1..i..L]>, the score of residue i
239 * under the ad hoc null2 model; this is a measure of local
240 * biased composition.
241 *
242 * These three fields will only be available after a call
243 * to domain definition by
244 * <p7_domaindef_ByPosteriorHeuristics()>.
245 *
246 * Returns: <eslOK> on success
247 *
248 * Xref: J2/126
249 */
250 int
251 p7_domaindef_DumpPosteriors(FILE *ofp, P7_DOMAINDEF *ddef)
252 {
253 int i;
254
255 for (i = 1; i <= ddef->L; i++)
256 fprintf(ofp, "%d %f\n", i, ddef->mocc[i]);
257 fprintf(ofp, "&\n");
258
259 for (i = 1; i <= ddef->L; i++)
260 fprintf(ofp, "%d %f\n", i, ddef->btot[i]);
261 fprintf(ofp, "&\n");
262
263 for (i = 1; i <= ddef->L; i++)
264 fprintf(ofp, "%d %f\n", i, ddef->etot[i]);
265 fprintf(ofp, "&\n");
266
267 for (i = 1; i <= ddef->L; i++)
268 fprintf(ofp, "%d %f\n", i, ddef->n2sc[i]);
269 fprintf(ofp, "&\n");
270
271 return eslOK;
272 }
273
274
275
276 /* Function: p7_domaindef_Destroy()
277 * Synopsis: Destroys a <P7_DOMAINDEF>.
278 * Incept: SRE, Fri Jan 25 13:52:46 2008 [Janelia]
279 *
280 * Purpose: Destroys a <P7_DOMAINDEF>.
281 */
282 void
283 p7_domaindef_Destroy(P7_DOMAINDEF *ddef)
284 {
285 int d;
286 if (ddef == NULL) return;
287
288 if (ddef->mocc != NULL) free(ddef->mocc);
289 if (ddef->btot != NULL) free(ddef->btot);
290 if (ddef->etot != NULL) free(ddef->etot);
291 if (ddef->n2sc != NULL) free(ddef->n2sc);
292
293 if (ddef->dcl != NULL) {
294 for (d = 0; d < ddef->ndom; d++) {
295 if (ddef->dcl[d].scores_per_pos) free(ddef->dcl[d].scores_per_pos);
296 p7_alidisplay_Destroy(ddef->dcl[d].ad);
297 }
298 free(ddef->dcl);
299 }
300
301 p7_spensemble_Destroy(ddef->sp);
302 p7_trace_Destroy(ddef->tr);
303 p7_trace_Destroy(ddef->gtr);
304 free(ddef);
305 return;
306 }
307
308 /*****************************************************************
309 * 2. Routines inferring domain structure of a target sequence
310 *****************************************************************/
311
312 #if 0
313 /* Function: p7_domaindef_ByViterbi()
314 * Synopsis: Define domains in a sequence by maximum likelihood.
315 * Incept: SRE, Fri Jan 25 15:10:21 2008 [Janelia]
316 *
317 * Purpose: Use a Viterbi (maximum likelihood) parse to determine
318 * the domain structure of sequence <sq> aligned to
319 * model <gm>. Caller provides a filled Viterbi matrix
320 * in <gx1>, and a second matrix of at least the same
321 * size for scratch space in <gx2>.
322 *
323 * Upon return, <ddef> contains definitions of all the
324 * domains, bounds defined by Viterbi parse, individually
325 * scored by null2-corrected Forward, and aligned by
326 * optimal posterior accuracy.
327 *
328 * Returns: <eslOK> on success.
329 */
330 int
331 p7_domaindef_ByViterbi(P7_PROFILE *gm, const ESL_SQ *sq, const ESL_SQ *ntsq, P7_GMX *gx1, P7_GMX *gx2, P7_DOMAINDEF *ddef)
332 {
333 int d;
334 int saveL = gm->L; /* need to be able to restore original <gm> config */
335 int save_mode = gm->mode;
336
337 p7_domaindef_GrowTo(ddef, sq->n);
338 p7_GTrace (sq->dsq, sq->n, gm, gx1, ddef->gtr);
339 p7_trace_Index(ddef->gtr);
340
341 p7_ReconfigUnihit(gm, 0); /* process each domain in unihit L=0 mode */
342
343 for (d = 0; d < ddef->gtr->ndom; d++)
344 rescore_isolated_domain(ddef, gm, sq, ntsq, gx1, gx2, ddef->gtr->sqfrom[d], ddef->gtr->sqto[d], FALSE, NULL, FALSE, NULL, NULL, NULL);
345
346 /* Restore original model configuration, including length */
347 if (p7_IsMulti(save_mode)) p7_ReconfigMultihit(gm, saveL);
348 else p7_ReconfigUnihit( gm, saveL);
349 return eslOK;
350 }
351 #endif
352
353
354 /* Function: p7_domaindef_ByPosteriorHeuristics()
355 * Synopsis: Define domains in a sequence using posterior probs.
356 * Incept: SRE, Sat Feb 23 08:17:44 2008 [Janelia]
357 *
358 * Purpose: Given a sequence <sq> and model <om> for which we have
359 * already calculated a Forward and Backward parsing
360 * matrices <oxf> and <oxb>; use posterior probability
361 * heuristics to determine an annotated domain structure;
362 * and for each domain found, score it (with null2
363 * calculations) and obtain an optimal accuracy alignment,
364 * using <fwd> and <bck> matrices as workspace for the
365 * necessary full-matrix DP calculations. Caller provides a
366 * new or reused <ddef> object to hold these results.
367 * A <bg> is provided for (possible) use in biased-composition
368 * score correction (used in nhmmer), and a boolean
369 * <long_target> argument is provided to allow nhmmer-
370 * specific modifications to the behavior of this function
371 * (TRUE -> from nhmmer).
372 *
373 * Upon return, <ddef> contains the definitions of all the
374 * domains: their bounds, their null-corrected Forward
375 * scores, and their optimal posterior accuracy alignments.
376 *
377 * Returns: <eslOK> on success.
378 *
379 * <eslERANGE> on numeric overflow in posterior
380 * decoding. This should not be possible for multihit
381 * models.
382 */
383 int
384 p7_domaindef_ByPosteriorHeuristics(const ESL_SQ *sq, const ESL_SQ *ntsq, P7_OPROFILE *om,
385 P7_OMX *oxf, P7_OMX *oxb, P7_OMX *fwd, P7_OMX *bck,
386 P7_DOMAINDEF *ddef, P7_BG *bg, int long_target,
387 P7_BG *bg_tmp, float *scores_arr, float *fwd_emissions_arr)
388 {
389 int i, j;
390 int triggered;
391 int d;
392 int i2,j2;
393 int last_j2;
394 int nc;
395 int saveL = om->L; /* Save the length config of <om>; will restore upon return */
396 int save_mode = om->mode; /* Likewise for the mode. */
397 int status;
398
399 if ((status = p7_domaindef_GrowTo(ddef, sq->n)) != eslOK) return status; /* ddef's btot,etot,mocc now ready for seq of length n */
400 if ((status = p7_DomainDecoding(om, oxf, oxb, ddef)) != eslOK) return status; /* ddef->{btot,etot,mocc} now made. */
401
402 esl_vec_FSet(ddef->n2sc, sq->n+1, 0.0); /* ddef->n2sc null2 scores are initialized */
403 ddef->nexpected = ddef->btot[sq->n]; /* posterior expectation for # of domains (same as etot[sq->n]) */
404
405 p7_oprofile_ReconfigUnihit(om, saveL); /* process each domain in unihit mode, regardless of om->mode */
406 i = -1;
407 triggered = FALSE;
408
409 for (j = 1; j <= sq->n; j++)
410 {
411
412 if (! triggered)
413 { /* xref J2/101 for what the logic below is: */
414 if (ddef->mocc[j] - (ddef->btot[j] - ddef->btot[j-1]) < ddef->rt2) i = j;
415 else if (i == -1) i = j;
416 if (ddef->mocc[j] >= ddef->rt1) triggered = TRUE;
417 }
418 else if (ddef->mocc[j] - (ddef->etot[j] - ddef->etot[j-1]) < ddef->rt2)
419 {
420 /* We have a region i..j to evaluate. */
421 p7_omx_GrowTo(fwd, om->M, j-i+1, j-i+1);
422 p7_omx_GrowTo(bck, om->M, j-i+1, j-i+1);
423 ddef->nregions++;
424 if (is_multidomain_region(ddef, i, j))
425 {
426 /* This region appears to contain more than one domain, so we have to
427 * resolve it by cluster analysis of posterior trace samples, to define
428 * one or more domain envelopes.
429 */
430 ddef->nclustered++;
431
432 /* Resolve the region into domains by stochastic trace
433 * clustering; assign position-specific null2 model by
434 * stochastic trace clustering; there is redundancy
435 * here; we will consolidate later if null2 strategy
436 * works
437 */
438 p7_oprofile_ReconfigMultihit(om, saveL);
439 p7_Forward(sq->dsq+i-1, j-i+1, om, fwd, NULL);
440
441 region_trace_ensemble(ddef, om, sq->dsq, i, j, fwd, bck, &nc);
442 p7_oprofile_ReconfigUnihit(om, saveL);
443 /* ddef->n2sc is now set on i..j by the traceback-dependent method */
444
445 last_j2 = 0;
446 for (d = 0; d < nc; d++) {
447 p7_spensemble_GetClusterCoords(ddef->sp, d, &i2, &j2, NULL, NULL, NULL);
448 if (i2 <= last_j2) ddef->noverlaps++;
449
450 /* Note that k..m coords on model are available, but
451 * we're currently ignoring them. This leads to a
452 * rare clustering bug that we eventually need to fix
453 * properly [xref J3/32]: two different regions in one
454 * profile HMM might have hit same seq domain, and
455 * when we now go to calculate an OA trace, nothing
456 * constrains us to find the two different alignments
457 * to the HMM; in fact, because OA is optimal, we'll
458 * find one and the *same* alignment, leading to an
459 * apparent duplicate alignment in the output.
460 *
461 * Registered as #h74, Dec 2009, after EBI finds and
462 * reports it. #h74 is worked around in p7_tophits.c
463 * by hiding all but one envelope with an identical
464 * alignment, in the rare event that this
465 * happens. [xref J5/130].
466 */
467 ddef->nenvelopes++;
468
469 /*the !long_target argument will cause the function to recompute null2
470 * scores if this is part of a long_target (nhmmer) pipeline */
471 if (rescore_isolated_domain(ddef, om, sq, ntsq, fwd, bck, i2, j2, TRUE, bg, long_target, bg_tmp, scores_arr, fwd_emissions_arr) == eslOK)
472 last_j2 = j2;
473 }
474 p7_spensemble_Reuse(ddef->sp);
475 p7_trace_Reuse(ddef->tr);
476 }
477 else
478 {
479 /* The region looks simple, single domain; convert the region to an envelope. */
480 ddef->nenvelopes++;
481 rescore_isolated_domain(ddef, om, sq, ntsq, fwd, bck, i, j, FALSE, bg, long_target, bg_tmp, scores_arr, fwd_emissions_arr);
482 }
483 i = -1;
484 triggered = FALSE;
485 }
486 }
487
488
489 /* Restore model to uni/multihit mode, and to its original length model */
490 if (p7_IsMulti(save_mode)) p7_oprofile_ReconfigMultihit(om, saveL);
491 else p7_oprofile_ReconfigUnihit (om, saveL);
492 return eslOK;
493 }
494
495
496
497 /*****************************************************************
498 * 3. Internal routines
499 *****************************************************************/
500
501
502 /* is_multidomain_region()
503 * SRE, Fri Feb 8 11:35:04 2008 [Janelia]
504 *
505 * This defines the trigger for when we need to hand a "region" off to
506 * a deeper analysis (using stochastic tracebacks and clustering)
507 * because there's reason to suspect it may encompass two or more
508 * domains.
509 *
510 * The criterion is to find the split point z at which the expected
511 * number of E occurrences preceding B occurrences is maximized, and
512 * if that number is greater than the heuristic threshold <ddef->rt3>,
513 * then return TRUE. In other words, we're checking to see if there's
514 * any point in the region at which it looks like an E was followed by
515 * a B, as expected for a multidomain interpretation of the region.
516 *
517 * More precisely: return TRUE if \max_z [ \min (B(z), E(z)) ] >= rt3
518 * where
519 * E(z) = expected number of E states occurring in region before z is emitted
520 * = \sum_{y=i}^{z} eocc[i] = etot[z] - etot[i-1]
521 * B(z) = expected number of B states occurring in region after z is emitted
522 * = \sum_{y=z}^{j} bocc[i] = btot[j] - btot[z-1]
523 *
524 *
525 * Because this relies on the <ddef->etot> and <ddef->btot> arrays,
526 * <calculate_domain_posteriors()> needs to have been called first.
527 *
528 * Xref: J2/101.
529 */
530 static int
531 is_multidomain_region(P7_DOMAINDEF *ddef, int i, int j)
532 {
533 int z;
534 float max;
535 float expected_n;
536
537 max = -1.0;
538 for (z = i; z <= j; z++)
539 {
540 expected_n = ESL_MIN( (ddef->etot[z] - ddef->etot[i-1]), (ddef->btot[j] - ddef->btot[z-1]));
541 max = ESL_MAX(max, expected_n);
542 }
543
544 return ( (max >= ddef->rt3) ? TRUE : FALSE);
545 }
546
547
548 /* region_trace_ensemble()
549 * SRE, Fri Feb 8 11:49:44 2008 [Janelia]
550 *
551 * Here, we've decided that region <ireg>..<jreg> in sequence <dsq> might be
552 * composed of more than one domain, and we're going to use clustering
553 * of a posterior ensemble of stochastic tracebacks to sort it out.
554 *
555 * Caller provides a filled Forward matrix in <fwd> for the sequence
556 * region <dsq+ireg-1>, length <jreg-ireg+1>, for the model <om>
557 * configured in multihit mode with its target length distribution
558 * set to the total length of <dsq>: i.e., the same model
559 * configuration used to score the complete sequence (if it weren't
560 * multihit, we wouldn't be worried about multiple domains).
561 *
562 * Caller also provides a DP matrix in <wrk> containing at least one
563 * row, for use as temporary workspace. (This will typically be the
564 * caller's Backwards matrix, which we haven't yet used at this point
565 * in the processing pipeline.)
566 *
567 * Caller provides <ddef>, which defines heuristic parameters that
568 * control the clustering, and provides working space for the
569 * calculation and the answers. The <ddef->sp> object must have been
570 * reused (i.e., it needs to be fresh; we're going to use it here);
571 * the caller needs to Reuse() it specifically, because it can't just
572 * Reuse() the whole <ddef>, when it's in the process of analyzing
573 * regions.
574 *
575 * Upon return, <*ret_nc> contains the number of clusters that were
576 * defined.
577 *
578 * The caller can retrieve info on each cluster by calling
579 * <p7_spensemble_GetClusterCoords(ddef->sp...)> on the
580 * <P7_SPENSEMBLE> object in <ddef>.
581 *
582 * Other information on what's happened in working memory:
583 *
584 * <ddef->n2sc[ireg..jreg]> now contains log f'(x_i) / f(x_i) null2 scores
585 * for each residue.
586 *
587 * <ddef->sp> gets filled in, and upon return, it's holding the answers
588 * (the cluster definitions). When the caller is done retrieving those
589 * answers, it needs to <esl_spensemble_Reuse()> it before calling
590 * <region_trace_ensemble()> again.
591 *
592 * <ddef->tr> is used as working memory for sampled traces.
593 *
594 * <wrk> has had its zero row clobbered as working space for a null2 calculation.
595 */
596 static int
597 region_trace_ensemble(P7_DOMAINDEF *ddef, const P7_OPROFILE *om, const ESL_DSQ *dsq, int ireg, int jreg,
598 const P7_OMX *fwd, P7_OMX *wrk, int *ret_nc)
599 {
600 int Lr = jreg-ireg+1;
601 int t, d, d2;
602 int nov, n;
603 int nc;
604 int pos;
605 float null2[p7_MAXCODE];
606
607 esl_vec_FSet(ddef->n2sc+ireg, Lr, 0.0); /* zero the null2 scores in region */
608
609 /* By default, we make results reproducible by forcing a reset of
610 * the RNG to its originally seeded state.
611 */
612 if (ddef->do_reseeding)
613 esl_randomness_Init(ddef->r, esl_randomness_GetSeed(ddef->r));
614
615 /* Collect an ensemble of sampled traces; calculate null2 odds ratios from these */
616 for (t = 0; t < ddef->nsamples; t++)
617 {
618 p7_StochasticTrace(ddef->r, dsq+ireg-1, Lr, om, fwd, ddef->tr);
619 p7_trace_Index(ddef->tr);
620
621 pos = 1;
622 for (d = 0; d < ddef->tr->ndom; d++)
623 {
624 p7_spensemble_Add(ddef->sp, t, ddef->tr->sqfrom[d]+ireg-1, ddef->tr->sqto[d]+ireg-1, ddef->tr->hmmfrom[d], ddef->tr->hmmto[d]);
625
626 p7_Null2_ByTrace(om, ddef->tr, ddef->tr->tfrom[d], ddef->tr->tto[d], wrk, null2);
627
628 /* residues outside domains get bumped +1: because f'(x) = f(x), so f'(x)/f(x) = 1 in these segments */
629 for (; pos <= ddef->tr->sqfrom[d]; pos++) ddef->n2sc[ireg+pos-1] += 1.0;
630
631 /* Residues inside domains get bumped by their null2 ratio */
632 for (; pos <= ddef->tr->sqto[d]; pos++) ddef->n2sc[ireg+pos-1] += null2[dsq[ireg+pos-1]];
633 }
634 /* the remaining residues in the region outside any domains get +1 */
635 for (; pos <= Lr; pos++) ddef->n2sc[ireg+pos-1] += 1.0;
636
637 p7_trace_Reuse(ddef->tr);
638 }
639
640 /* Convert the accumulated n2sc[] ratios in this region to log odds null2 scores on each residue. */
641 for (pos = ireg; pos <= jreg; pos++)
642 ddef->n2sc[pos] = logf(ddef->n2sc[pos] / (float) ddef->nsamples);
643
644 /* Cluster the ensemble of traces to break region into envelopes. */
645 p7_spensemble_Cluster(ddef->sp, ddef->min_overlap, ddef->of_smaller, ddef->max_diagdiff, ddef->min_posterior, ddef->min_endpointp, &nc);
646
647 /* A little hacky now. Remove "dominated" domains relative to seq coords. */
648 for (d = 0; d < nc; d++)
649 ddef->sp->assignment[d] = 0; /* overload <assignment> to flag that a domain is dominated */
650
651 /* who dominates who? (by post prob) */
652 for (d = 0; d < nc; d++)
653 {
654 for (d2 = d+1; d2 < nc; d2++)
655 {
656 nov = ESL_MIN(ddef->sp->sigc[d].j, ddef->sp->sigc[d2].j) - ESL_MAX(ddef->sp->sigc[d].i, ddef->sp->sigc[d2].i) + 1;
657 if (nov == 0) break;
658 n = ESL_MIN(ddef->sp->sigc[d].j - ddef->sp->sigc[d].i + 1, ddef->sp->sigc[d2].j - ddef->sp->sigc[d2].i + 1);
659 if ((float) nov / (float) n >= 0.8) /* overlap */
660 {
661 if (ddef->sp->sigc[d].prob > ddef->sp->sigc[d2].prob) ddef->sp->assignment[d2] = 1;
662 else ddef->sp->assignment[d] = 1;
663 }
664 }
665 }
666
667 /* shrink the sigc list, removing dominated domains */
668 d = 0;
669 for (d2 = 0; d2 < nc; d2++)
670 {
671 if (ddef->sp->assignment[d2]) continue; /* skip domain d2, it's dominated. */
672 if (d != d2) memcpy(ddef->sp->sigc + d, ddef->sp->sigc + d2, sizeof(struct p7_spcoord_s));
673 d++;
674 }
675 ddef->sp->nc = d;
676 *ret_nc = d;
677 return eslOK;
678 }
679
680
681
682
683 /* Function: reparameterize_model()
684 *
685 * Synopsis: Establish new background priors based on a sequence window,
686 * and change match state emission log-odds scores accordingly.
687 *
688 * Purpose: Compute new background priors based on a sequence window,
689 * and set match search model's match state emission log-odds
690 * scores accordingly. Used narrowly within the post-fwd
691 * portion of the longtarget pipeline
692 *
693 * If sq != NULL: Given a sequence <sq> and <start> and length
694 * <L>, compute the residue frequency, and modify <bg> in place
695 * to store a mixture of that frequency with the default (passed
696 * in <bg>). Then update the match emission scores in place in
697 * <om> to account for new <bg> values. Prior bg values are
698 * stored for return in <bgf_arr>. This is called by
699 * rescore_isolated_domain(), which is required to call it again
700 * once complete to return <bg> and <om> to original state.
701 *
702 *
703 * If sq == NULL: return <bg> and <om> to original state.
704 *
705 * Only used in the longtarget (nhmmer) case. In-place
706 * modification is done to avoid rampant memory allocation.
707 * Doing this requires that (a) each thread has its own
708 * independent copy of <bg> and <om>, and (b) those are
709 * returned to their original state before being used
710 * outside the function using the modified structures.
711 *
712 * The pre-allocated array <sc_tmp> must be passed, for use
713 * in p7_oprofile_UpdateFwdEmissionScores().
714 *
715 */
716 static int
717 reparameterize_model (P7_BG *bg, P7_OPROFILE *om, const ESL_SQ *sq, int start, int L, float *fwd_emissions, float *bgf_arr, float *sc_arr) {
718 int K = om->abc->K;
719 int i;
720 float tmp;
721 int status;
722
723 /* Fraction of new bg frequencies that comes from a prior determined by the sequence block.
724 * This is 25% for long sequences, more for shorter sequences (e.g. 50% for sequences of length 50)
725 */
726 float bg_smooth = 1.; // will be modified immediately below, if it's used
727
728 if (sq != NULL) {
729 /* compute new bg->f, capturing original values into a preallocated array */
730 bg_smooth = 25.0 / (ESL_MIN(100,ESL_MAX(50,sq->n)));
731
732 esl_vec_FSet (bgf_arr, om->abc->K, 0);
733 status = esl_sq_CountResidues(sq, start, L, bgf_arr);
734 if (status != eslOK) p7_Fail("Invalid sequence range in reparameterize_model()\n");
735 esl_vec_FNorm(bgf_arr, om->abc->K);
736
737 for (i=0; i<K; i++) {
738 tmp = bg->f[i];
739 bg->f[i] = (bg_smooth*bg->f[i]) + ( (1.0-bg_smooth) * bgf_arr[i]) ;
740 bgf_arr[i] = tmp;
741 }
742 } else {
743 /* revert bg->f to the passed in orig_bgf */
744 esl_vec_FCopy(bgf_arr, K, bg->f);
745 }
746
747 p7_oprofile_UpdateFwdEmissionScores(om, bg, fwd_emissions, sc_arr);
748
749 return eslOK;
750 }
751
752
753 /* rescore_isolated_domain()
754 * SRE, Fri Feb 8 09:18:33 2008 [Janelia]
755 *
756 * We have isolated a single domain's envelope from <i>..<j> in
757 * sequence <sq>, and now we want to score it in isolation and obtain
758 * an alignment display for it.
759 *
760 * (Later, we can add up all the individual domain scores from this
761 * seq into a new per-seq score, to compare to the original per-seq
762 * score).
763 *
764 * The caller provides model <om> configured in unilocal mode; by
765 * using unilocal (as opposed to multilocal), we're going to force the
766 * identification of a single domain in this envelope now.
767 *
768 * The alignment is an optimal accuracy alignment (sensu IH Holmes),
769 * also obtained in unilocal mode.
770 *
771 * The caller provides DP matrices <ox1> and <ox2> with sufficient
772 * space to hold Forward and Backward calculations for this domain
773 * against the model. (The caller will typically already have matrices
774 * sufficient for the complete sequence lying around, and can just use
775 * those.) The caller also provides a <P7_DOMAINDEF> object (ddef)
776 * which is (efficiently, we trust) managing any necessary temporary
777 * working space and heuristic thresholds.
778 *
779 * If <long_target> is TRUE, the calling function optionally
780 * passes in three allocated arrays (bg_tmp, scores_arr,
781 * fwd_emissions_arr) used for temporary storage in
782 * reparameterize_model(). If scores_arr is NULL, reparameterization
783 * is not done, and the domcorrection, used to determine null2, is not
784 * computed).
785 *
786 * Returns <eslOK> if a domain was successfully identified, scored,
787 * and aligned in the envelope; if so, the per-domain information is
788 * registered in <ddef>, in <ddef->dcl>.
789 *
790 * And here's what's happened to our working memory:
791 *
792 * <ddef>: <ddef->tr> has been used, and possibly reallocated, for
793 * the OA trace of the domain. Before exit, we called
794 * <Reuse()> on it.
795 *
796 * <ox1> : happens to be holding OA score matrix for the domain
797 * upon return, but that's not part of the spec; officially
798 * its contents are "undefined".
799 *
800 * <ox2> : happens to be holding a posterior probability matrix
801 * for the domain upon return, but we're not making that
802 * part of the spec, so caller shouldn't rely on this;
803 * spec just makes its contents "undefined".
804 *
805 *
806 * Returns <eslFAIL> if domain is not successfully identified. This
807 * is rare; one way it can happen is if posterior decoding calculation
808 * overflows, which can occur on highly repetitive sequence
809 * {J3/119-121}. Beware: as a result, it is possible to have
810 * <ddef->ndom = 0>, for nonzero region(s)/envelope(s). See {iss131}.
811 *
812 */
813 static int
814 rescore_isolated_domain(P7_DOMAINDEF *ddef, P7_OPROFILE *om, const ESL_SQ *sq, const ESL_SQ *ntsq,
815 P7_OMX *ox1, P7_OMX *ox2, int i, int j, int null2_is_done, P7_BG *bg, int long_target,
816 P7_BG *bg_tmp, float *scores_arr, float *fwd_emissions_arr)
817 {
818 P7_DOMAIN *dom = NULL;
819 int Ld = j-i+1;
820 float domcorrection = 0.0;
821 float envsc, oasc;
822 int z;
823 int pos;
824 float null2[p7_MAXCODE];
825 int status;
826 int max_env_extra = 20;
827 int orig_L;
828
829
830 if (long_target) {
831 //temporarily change model length to env_len. The nhmmer pipeline will tack
832 //on the appropriate cost to account for the longer actual window
833 orig_L = om->L;
834 p7_oprofile_ReconfigRestLength(om, j-i+1);
835 }
836
837 if (long_target && scores_arr!=NULL) {
838 // Modify bg and om in-place to avoid having to clone (allocate) a massive
839 // number of times when there are many hits
840 reparameterize_model (bg, om, sq, i, j-i+1, fwd_emissions_arr, bg_tmp->f, scores_arr);
841 }
842
843 p7_Forward (sq->dsq + i-1, Ld, om, ox1, &envsc);
844 p7_Backward(sq->dsq + i-1, Ld, om, ox1, ox2, NULL);
845
846 status = p7_Decoding(om, ox1, ox2, ox2); /* <ox2> is now overwritten with post probabilities */
847 if (status == eslERANGE) { /* rare: numeric overflow; domain is assumed to be repetitive garbage [J3/119-121] */
848 if (long_target && scores_arr)
849 reparameterize_model(bg, om, NULL, 0, 0, fwd_emissions_arr, bg_tmp->f, scores_arr); /* revert to original bg model */
850 status = eslFAIL;
851 goto ERROR;
852 }
853
854 /* Find an optimal accuracy alignment */
855 p7_OptimalAccuracy(om, ox2, ox1, &oasc); /* <ox1> is now overwritten with OA scores */
856 p7_OATrace (om, ox2, ox1, ddef->tr); /* <tr>'s seq coords are offset by i-1, rel to orig dsq */
857
858 /* hack the trace's sq coords to be correct w.r.t. original dsq */
859 for (z = 0; z < ddef->tr->N; z++)
860 if (ddef->tr->i[z] > 0) ddef->tr->i[z] += i-1;
861
862 /* get ptr to next empty domain structure in domaindef's results */
863 if (ddef->ndom == ddef->nalloc) {
864 ESL_REALLOC(ddef->dcl, sizeof(P7_DOMAIN) * (ddef->nalloc*2));
865 ddef->nalloc *= 2;
866 }
867 dom = &(ddef->dcl[ddef->ndom]);
868 dom->ad = p7_alidisplay_Create(ddef->tr, 0, om, sq, ntsq);
869 dom->scores_per_pos = NULL;
870
871
872 /* For long target DNA, it's common to see a huge envelope (>1Kb longer than alignment), usually
873 * involving simple repeat part of model that attracted similar segments of the repeatedly, to
874 * acquire a large total score. Now that we have alignment boundaries, re-run Fwd/Bkwd to trim away
875 * such a long envelope and estimate the true score of the hit region
876 */
877 if (long_target) {
878
879 if ( i < dom->ad->sqfrom-max_env_extra //trim the left side of the envelope
880 || j > dom->ad->sqto+max_env_extra //trim the right side of the envelope
881 ) {
882
883 //trim in the envelope, and do it again
884 i = ESL_MAX(i,dom->ad->sqfrom-max_env_extra);
885 j = ESL_MIN(j,dom->ad->sqto+max_env_extra);
886 Ld = j - i + 1;
887
888 //temporarily change model length to env_len. The nhmmer pipeline will tack
889 //on the appropriate cost to account for the longer actual window
890 p7_oprofile_ReconfigRestLength(om, j-i+1);
891
892 if (scores_arr!=NULL) {
893 //revert bg and om back to original, then forward to new values
894 reparameterize_model (bg, om, NULL, 0, 0, fwd_emissions_arr, bg_tmp->f, scores_arr);
895 reparameterize_model (bg, om, sq, i, Ld, fwd_emissions_arr, bg_tmp->f, scores_arr);
896 }
897
898 p7_Forward (sq->dsq + i-1, Ld, om, ox1, &envsc);
899 p7_Backward(sq->dsq + i-1, Ld, om, ox1, ox2, NULL);
900
901 status = p7_Decoding(om, ox1, ox2, ox2); /* <ox2> is now overwritten with post probabilities */
902 if (status == eslERANGE) { /* rare: numeric overflow; domain is assumed to be repetitive garbage [J3/119-121] */
903 reparameterize_model(bg, om, NULL, 0, 0, fwd_emissions_arr, bg_tmp->f, scores_arr); /* revert to original bg model */
904 status = eslFAIL;
905 goto ERROR;
906 }
907
908 /* Find an optimal accuracy alignment */
909 p7_OptimalAccuracy(om, ox2, ox1, &oasc); /* <ox1> is now overwritten with OA scores */
910 p7_trace_Reuse(ddef->tr);
911 p7_OATrace (om, ox2, ox1, ddef->tr); /* <tr>'s seq coords are offset by i-1, rel to orig dsq */
912
913 /* re-hack the trace's sq coords to be correct w.r.t. original dsq */
914 for (z = 0; z < ddef->tr->N; z++)
915 if (ddef->tr->i[z] > 0) ddef->tr->i[z] += i-1;
916
917 /* store the results in it, first destroying the old alidisplay object */
918 p7_alidisplay_Destroy(dom->ad);
919 dom->ad = p7_alidisplay_Create(ddef->tr, 0, om, sq, NULL);
920 }
921
922 /* Estimate bias correction, by computing what the score would've been without
923 * reparameterization
924 */
925 domcorrection = envsc;
926 if (scores_arr!=NULL) { //revert bg and om back to original,
927 //and while I'm at it, capture what the default parameterized score would have been, for "null2"
928 reparameterize_model (bg, om, NULL, 0, 0, fwd_emissions_arr, bg_tmp->f, scores_arr);
929 p7_Forward (sq->dsq + i-1, Ld, om, ox1, &domcorrection);
930 }
931
932 p7_oprofile_ReconfigRestLength(om, orig_L);
933
934 if (domcorrection < envsc) //negative bias correction shouldn't happen. Stick with the original score.
935 envsc = domcorrection;
936
937 dom->domcorrection = domcorrection - envsc;
938
939 } else {
940
941 /* Compute bias correction (for non-longtarget case)
942 *
943 * Is null2 set already for this i..j? (It is, if we're in a domain that
944 * was defined by stochastic traceback clustering in a multidomain region;
945 * it isn't yet, if we're in a simple one-domain region). If it isn't,
946 * do it now, by the expectation (posterior decoding) method.
947 */
948 if (!null2_is_done) {
949 p7_Null2_ByExpectation(om, ox2, null2);
950 for (pos = i; pos <= j; pos++)
951 ddef->n2sc[pos] = logf(null2[sq->dsq[pos]]);
952 }
953 for (pos = i; pos <= j; pos++)
954 domcorrection += ddef->n2sc[pos]; /* domcorrection is in units of NATS */
955
956 dom->domcorrection = domcorrection; /* in units of NATS */
957
958 }
959
960
961 dom->iali = dom->ad->sqfrom;
962 dom->jali = dom->ad->sqto;
963 dom->ienv = i;
964 dom->jenv = j;
965 dom->envsc = envsc; /* in units of NATS */
966 dom->oasc = oasc; /* in units of expected # of correctly aligned residues */
967 dom->dombias = 0.0; /* gets set later, using bg->omega and dombias */
968 dom->bitscore = 0.0; /* gets set later by caller, using envsc, null score, and dombias */
969 dom->lnP = 0.0; /* gets set later by caller, using bitscore */
970 dom->is_reported = FALSE; /* gets set later by caller */
971 dom->is_included = FALSE; /* gets set later by caller */
972
973
974 ddef->ndom++;
975
976 p7_trace_Reuse(ddef->tr);
977 return eslOK;
978
979 ERROR:
980 p7_trace_Reuse(ddef->tr);
981 return status;
982 }
983
984
985 /*****************************************************************
986 * Example driver.
987 *****************************************************************/
988
989 #ifdef p7DOMAINDEF_EXAMPLE
990
991 /* gcc -o domaindef_example -g -Wall -I../easel -L../easel -I. -L. -Dp7DOMAINDEF_EXAMPLE p7_domaindef.c -lhmmer -leasel -lm
992 * ./domaindef_example <hmmfile> <seqfile>
993 */
994
995
996 #include <p7_config.h>
997
998 #include <stdio.h>
999 #include <stdlib.h>
1000
1001 #include "easel.h"
1002 #include "esl_getopts.h"
1003 #include "esl_random.h"
1004 #include "esl_alphabet.h"
1005 #include "esl_sq.h"
1006 #include "esl_sqio.h"
1007 #include "hmmer.h"
1008
1009 static ESL_OPTIONS options[] = {
1010 /* name type default env range toggles reqs incomp help docgroup*/
1011 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1012 { "-V", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "find domains by Viterbi parsing", 0 },
1013 { "--occp", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output posterior occupancies for xmgrace to <f>", 0 },
1014 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1015 };
1016
1017 static char usage[] = "[-options] <hmmfile> <seqfile>";
1018 static char banner[] = "example of domain definition by posterior sampling";
1019
1020 int
1021 main(int argc, char **argv)
1022 {
1023 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 2, argc, argv, banner, usage);
1024 ESL_RANDOMNESS *r = esl_randomness_CreateFast(42);
1025 char *hmmfile = esl_opt_GetArg(go, 1);
1026 P7_HMMFILE *hfp = NULL;
1027 P7_HMM *hmm = NULL;
1028 char *seqfile = esl_opt_GetArg(go, 2);
1029 int format = eslSQFILE_UNKNOWN;
1030 ESL_SQFILE *sqfp = NULL;
1031 ESL_SQ *sq = NULL;
1032 ESL_ALPHABET *abc = NULL;
1033 P7_BG *bg = NULL;
1034 P7_PROFILE *gm = NULL;
1035 P7_OPROFILE *om = NULL;
1036 P7_OMX *oxf = NULL; /* parsing matrix, passed to PosteriorHeuristics */
1037 P7_OMX *oxb = NULL;
1038 P7_OMX *fwd = NULL; /* full LxL matrix workspace passed to PosteriorHeuristics */
1039 P7_OMX *bck = NULL;
1040 P7_DOMAINDEF *ddef = NULL;
1041 char *ofile = NULL;
1042 FILE *ofp = NULL;
1043 float overall_sc, sc;
1044 int d;
1045 int status;
1046
1047 /* Read in one HMM */
1048 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
1049 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
1050 p7_hmmfile_Close(hfp);
1051
1052 /* Read in one sequence */
1053 sq = esl_sq_CreateDigital(abc);
1054 status = esl_sqfile_Open(seqfile, format, NULL, &sqfp);
1055 if (status == eslENOTFOUND) p7_Fail("No such file.");
1056 else if (status == eslEFORMAT) p7_Fail("Format unrecognized.");
1057 else if (status == eslEINVAL) p7_Fail("Can't autodetect stdin or .gz.");
1058 else if (status != eslOK) p7_Fail("Open failed, code %d.", status);
1059 if (esl_sqio_Read(sqfp, sq) != eslOK) p7_Fail("Failed to read sequence");
1060 esl_sqfile_Close(sqfp);
1061
1062 /* Configure a profile from the HMM */
1063 p7_FLogsumInit();
1064
1065 bg = p7_bg_Create(abc);
1066 p7_bg_SetLength(bg, sq->n);
1067 gm = p7_profile_Create(hmm->M, abc);
1068 om = p7_oprofile_Create(hmm->M, abc);
1069 p7_ProfileConfig(hmm, bg, gm, sq->n, p7_LOCAL);
1070 p7_oprofile_Convert(gm, om);
1071 p7_oprofile_ReconfigLength(om, sq->n);
1072
1073 /* allocate the domain definition object */
1074 ddef = p7_domaindef_Create(r);
1075
1076 /* allocate DP matrices for forward and backward */
1077 fwd = p7_omx_Create(gm->M, sq->n, sq->n);
1078 bck = p7_omx_Create(gm->M, sq->n, sq->n);
1079
1080 oxf = p7_omx_Create(om->M, 0, sq->n);
1081 oxb = p7_omx_Create(om->M, 0, sq->n);
1082
1083 /* define domain structure */
1084
1085
1086 p7_Forward (sq->dsq, sq->n, om, fwd, &overall_sc);
1087 p7_Backward(sq->dsq, sq->n, om, fwd, bck, &sc);
1088 p7_domaindef_ByPosteriorHeuristics(sq, NULL, om, oxf, oxb, fwd, bck, ddef, NULL, FALSE, NULL, NULL, NULL);
1089
1090
1091 printf("Overall raw likelihood score: %.2f nats\n", overall_sc);
1092
1093 /* retrieve and display results */
1094 for (d = 0; d < ddef->ndom; d++)
1095 {
1096 printf("domain %-4d : %4" PRId64 " %4" PRId64 " %6.2f %6.2f\n",
1097 d+1,
1098 ddef->dcl[d].ienv,
1099 ddef->dcl[d].jenv,
1100 ddef->dcl[d].envsc,
1101 ddef->dcl[d].domcorrection);
1102
1103 p7_alidisplay_Print(stdout, ddef->dcl[d].ad, 50, 120, FALSE);
1104 }
1105
1106 if ((ofile = esl_opt_GetString(go, "--occp")) != NULL)
1107 {
1108 if ((ofp = fopen(ofile, "w")) == NULL) p7_Fail("Failed to open output file %s\n", ofile);
1109 p7_domaindef_DumpPosteriors(ofp, ddef);
1110 fclose(ofp);
1111 }
1112
1113 p7_domaindef_Destroy(ddef);
1114 p7_omx_Destroy(oxf);
1115 p7_omx_Destroy(oxb);
1116 p7_omx_Destroy(fwd);
1117 p7_omx_Destroy(bck);
1118 p7_profile_Destroy(gm);
1119 p7_oprofile_Destroy(om);
1120 p7_bg_Destroy(bg);
1121 p7_hmm_Destroy(hmm);
1122 esl_sq_Destroy(sq);
1123 esl_alphabet_Destroy(abc);
1124 esl_randomness_Destroy(r);
1125 esl_getopts_Destroy(go);
1126 return 0;
1127 }
1128 #endif /*p7DOMAINDEF_EXAMPLE*/
1129
1130
1131 #ifdef p7DOMAINDEF_EXAMPLE2
1132 /* gcc -o domaindef_example2 -g -Wall -I../easel -L../easel -I. -L. -Dp7DOMAINDEF_EXAMPLE2 p7_domaindef.c -lhmmer -leasel -lm
1133 * ./domaindef_example2 <hmmfile>
1134 */
1135 #include <p7_config.h>
1136
1137 #include <stdio.h>
1138 #include <stdlib.h>
1139
1140 #include "easel.h"
1141 #include "esl_getopts.h"
1142 #include "esl_random.h"
1143 #include "esl_alphabet.h"
1144 #include "esl_stopwatch.h"
1145 #include "hmmer.h"
1146
1147 static ESL_OPTIONS options[] = {
1148 /* name type default env range toggles reqs incomp help docgroup*/
1149 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1150 { "-N", eslARG_INT, "1000", NULL, NULL, NULL, NULL, NULL, "number of sampled sequences", 0 },
1151 { "-L", eslARG_INT, "400", NULL, NULL, NULL, NULL, NULL, "length config for the profile", 0 },
1152 { "-V", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "find domains by Viterbi parsing", 0 },
1153 { "-b", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "baseline timing - no domain processing", 0 },
1154 { "-v", eslARG_NONE, NULL, NULL, NULL, NULL, NULL, NULL, "be more verbose (show per sequence results)", 0 },
1155 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1156 };
1157
1158 static char usage[] = "[-options] <hmmfile>";
1159 static char banner[] = "example of domain definition by posterior sampling";
1160
1161 int
1162 main(int argc, char **argv)
1163 {
1164 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 1, argc, argv, banner, usage);
1165 ESL_RANDOMNESS *r = esl_randomness_CreateFast(42);
1166 ESL_STOPWATCH *w = esl_stopwatch_Create();
1167 char *hmmfile = esl_opt_GetArg(go, 1);
1168 P7_HMMFILE *hfp = NULL;
1169 P7_HMM *hmm = NULL;
1170 ESL_SQ *sq = NULL;
1171 ESL_ALPHABET *abc = NULL;
1172 P7_BG *bg = NULL;
1173 P7_PROFILE *gm = NULL;
1174 P7_TRACE *tr = NULL;
1175 P7_GMX *fwd = NULL;
1176 P7_GMX *bck = NULL;
1177 P7_OMX *gxf = NULL; /* parsing matrix, passed to PosteriorHeuristics */
1178 P7_OMX *gxb = NULL;
1179
1180 P7_DOMAINDEF *ddef = NULL;
1181 int N = esl_opt_GetInteger(go, "-N");
1182 int L0 = esl_opt_GetInteger(go, "-L");
1183 int do_vit = esl_opt_GetBoolean(go, "-V");
1184 int do_baseline = esl_opt_GetBoolean(go, "-b");
1185 int be_verbose = esl_opt_GetBoolean(go, "-v");
1186 float overall_sc, sc;
1187 int idx;
1188 int tot_true, tot_found;
1189
1190 /* Read in one HMM */
1191 if (p7_hmmfile_Open(hmmfile, NULL, &hfp, NULL) != eslOK) p7_Fail("Failed to open HMM file %s", hmmfile);
1192 if (p7_hmmfile_Read(hfp, &abc, &hmm) != eslOK) p7_Fail("Failed to read HMM");
1193 p7_hmmfile_Close(hfp);
1194
1195 /* Configure a profile from the HMM */
1196 bg = p7_bg_Create(abc);
1197 p7_bg_SetLength(bg, L0);
1198 gm = p7_profile_Create(hmm->M, abc);
1199 p7_ProfileConfig(hmm, bg, gm, L0, p7_LOCAL);
1200
1201 /* Other initial allocations */
1202 sq = esl_sq_CreateDigital(abc);
1203 ddef = p7_domaindef_Create(r);
1204 fwd = p7_gmx_Create(gm->M, L0);
1205 bck = p7_gmx_Create(gm->M, L0);
1206 gxf = p7_gmx_Create(gm->M, L0);
1207 gxb = p7_gmx_Create(gm->M, L0);
1208 tr = p7_trace_Create();
1209 p7_FLogsumInit();
1210
1211 tot_true = tot_found = 0;
1212 esl_stopwatch_Start(w);
1213 for (idx = 0; idx < N; idx++)
1214 {
1215 p7_ReconfigLength(gm, L0);
1216 p7_bg_SetLength(bg, L0);
1217 p7_ProfileEmit(r, hmm, gm, bg, sq, tr); /* sample a sequence from the profile */
1218 p7_trace_Index(tr); /* tr->ndom is the "true" domain number emitted */
1219 tot_true += tr->ndom;
1220
1221 p7_ReconfigLength(gm, sq->n);
1222 p7_bg_SetLength(bg, sq->n);
1223 p7_gmx_GrowTo(fwd, gm->M, sq->n);
1224 p7_gmx_GrowTo(bck, gm->M, sq->n);
1225
1226 if (do_vit)
1227 {
1228 p7_GViterbi (sq->dsq, sq->n, gm, fwd, &overall_sc);
1229 if (! do_baseline)
1230 p7_domaindef_ByViterbi(gm, sq, fwd, bck, ddef);
1231 }
1232 else
1233 {
1234 p7_GForward (sq->dsq, sq->n, gm, fwd, &overall_sc);
1235 if (! do_baseline) {
1236 p7_GBackward(sq->dsq, sq->n, gm, bck, &sc);
1237 p7_domaindef_ByPosteriorHeuristics(sq, gm, fwd, bck, gxf, gxb, ddef, NULL, FALSE, NULL, NULL, NULL);
1238 //Is this even being compiled by any tests? Looks like there's a fair amount of bit rot here
1239 }
1240 }
1241
1242 tot_found += ddef->ndom;
1243 if (be_verbose)
1244 printf("true: %d found: %d\n", tr->ndom, ddef->ndom);
1245
1246 p7_trace_Reuse(tr);
1247 p7_domaindef_Reuse(ddef);
1248 }
1249 esl_stopwatch_Stop(w);
1250
1251 printf("Total domains: %d\n", tot_true);
1252 printf("Total found: %d\n", tot_found);
1253 printf("Accuracy: %.2f%%\n", 100. * (double) tot_found / (double) tot_true);
1254 esl_stopwatch_Display(stdout, w, "CPU time: ");
1255
1256 p7_domaindef_Destroy(ddef);
1257 p7_gmx_Destroy(fwd);
1258 p7_gmx_Destroy(bck);
1259 p7_profile_Destroy(gm);
1260 p7_trace_Destroy(tr);
1261 p7_bg_Destroy(bg);
1262 p7_hmm_Destroy(hmm);
1263 esl_sq_Destroy(sq);
1264 esl_stopwatch_Destroy(w);
1265 esl_randomness_Destroy(r);
1266 esl_alphabet_Destroy(abc);
1267 esl_getopts_Destroy(go);
1268 return 0;
1269 }
1270 #endif /*p7DOMAINDEF_EXAMPLE2*/
1271