Debian Codegraph @

hmmer/src/p7_trace.c

raw symbols SCIP
1 /* P7_TRACE, the traceback structure.
2 *
3 * Contents:
4 * 1. The P7_TRACE structure
5 * 2. Access routines
6 * 3. Debugging tools
7 * 4. Creating traces by DP traceback
8 * 5. Creating faux traces from existing MSAs
9 * 6. Counting traces into new HMMs
10 * 7. Unit tests
11 * 8. Test driver
12 *
13 * Stylistic note: elements in a trace path are usually indexed by z.
14 */
15
16 #include <p7_config.h>
17
18 #include <stdlib.h>
19 #include <stdio.h>
20
21 #include "easel.h"
22 #include "hmmer.h"
23
24
25 /*****************************************************************
26 * 1. The P7_TRACE structure.
27 *****************************************************************/
28
29 static P7_TRACE *trace_create_engine(int initial_nalloc, int initial_ndomalloc, int with_posteriors);
30
31 /* Function: p7_trace_Create()
32 * Synopsis: Allocates a (growable, reusable) traceback.
33 *
34 * Purpose: Allocates a traceback.
35 *
36 * Tracebacks are growable. A reasonable initial internal
37 * allocation is made here, and routines that generate
38 * tracebacks will dynamically grow the trace as needed.
39 *
40 * Tracebacks are reusable. Usually a routine only
41 * allocates one, and reuses its memory over and over as
42 * new target sequences are aligned.
43 *
44 * Returns: a pointer to the new <P7_TRACE> structure on success.
45 *
46 * Throws: <NULL> on allocation error.
47 */
48 P7_TRACE *
49 p7_trace_Create(void)
50 {
51 int initial_nalloc = 256;
52 int initial_ndomalloc = 16;
53 int with_posteriors = FALSE;
54 return trace_create_engine(initial_nalloc, initial_ndomalloc, with_posteriors);
55 }
56
57 /* Function: p7_trace_CreateWithPP()
58 * Synopsis: Allocates a traceback that includes posterior probs.
59 * Incept: SRE, Tue Aug 19 13:08:12 2008 [Janelia]
60 *
61 * Purpose: Allocates a traceback that includes <tr->pp[z]> fields
62 * for posterior probabilities of emitted residues;
63 * otherwise identical to <p7_trace_Create()>.
64 */
65 P7_TRACE *
66 p7_trace_CreateWithPP(void)
67 {
68 int initial_nalloc = 256;
69 int initial_ndomalloc = 16;
70 int with_posteriors = TRUE;
71 return trace_create_engine(initial_nalloc, initial_ndomalloc, with_posteriors);
72 }
73
74 static P7_TRACE *
75 trace_create_engine(int initial_nalloc, int initial_ndomalloc, int with_posteriors)
76 {
77 P7_TRACE *tr = NULL;
78 int status;
79
80 ESL_ALLOC(tr, sizeof(P7_TRACE));
81 tr->st = NULL;
82 tr->k = NULL;
83 tr->i = NULL;
84 tr->pp = NULL;
85 tr->M = 0;
86 tr->L = 0;
87 tr->tfrom = tr->tto = NULL;
88 tr->sqfrom = tr->sqto = NULL;
89 tr->hmmfrom = tr->hmmto = NULL;
90
91 /* The trace data itself */
92 ESL_ALLOC(tr->st, sizeof(char) * initial_nalloc);
93 ESL_ALLOC(tr->k, sizeof(int) * initial_nalloc);
94 ESL_ALLOC(tr->i, sizeof(int) * initial_nalloc);
95 if (with_posteriors)
96 ESL_ALLOC(tr->pp, sizeof(float) * initial_nalloc);
97 tr->N = 0;
98 tr->nalloc = initial_nalloc;
99
100 /* The trace's index: table of domain start/stop coords */
101 ESL_ALLOC(tr->tfrom, sizeof(int) * initial_ndomalloc);
102 ESL_ALLOC(tr->tto, sizeof(int) * initial_ndomalloc);
103 ESL_ALLOC(tr->sqfrom, sizeof(int) * initial_ndomalloc);
104 ESL_ALLOC(tr->sqto, sizeof(int) * initial_ndomalloc);
105 ESL_ALLOC(tr->hmmfrom, sizeof(int) * initial_ndomalloc);
106 ESL_ALLOC(tr->hmmto, sizeof(int) * initial_ndomalloc);
107 tr->ndom = 0;
108 tr->ndomalloc = initial_ndomalloc;
109 return tr;
110
111 ERROR:
112 if (tr != NULL) p7_trace_Destroy(tr);
113 return NULL;
114 }
115
116
117 /* Function: p7_trace_Reuse()
118 * Synopsis: Prepare a trace for reuse.
119 * Incept: SRE, Tue Jan 9 13:02:34 2007 [Janelia]
120 *
121 * Purpose: Reinitializes an existing trace object, reusing its
122 * memory.
123 *
124 * Returns: <eslOK> on success.
125 *
126 * Throws: (no abnormal error conditions)
127 *
128 * Xref: STL11/124
129 */
130 int
131 p7_trace_Reuse(P7_TRACE *tr)
132 {
133 tr->N = 0;
134 tr->M = 0;
135 tr->L = 0;
136 tr->ndom = 0;
137 return eslOK;
138 }
139
140 /* Function: p7_trace_Grow()
141 * Synopsis: Grow the allocation for trace data.
142 *
143 * Purpose: If <tr> can't fit another state, double its allocation for
144 * traceback data.
145 *
146 * This doesn't reallocate the domain index; see
147 * <p7_trace_GrowIndex()> or <p7_trace_GrowIndexTo()> for
148 * that.
149 *
150 * Returns: <eslOK> on success.
151 *
152 * Throws: <eslEMEM> on allocation failure; in this case, the data in
153 * <tr> are unaffected.
154 */
155 int
156 p7_trace_Grow(P7_TRACE *tr)
157 {
158 void *tmp;
159 int status;
160
161 if (tr->N < tr->nalloc) return eslOK;
162
163 ESL_RALLOC(tr->st, tmp, sizeof(char) *2*tr->nalloc);
164 ESL_RALLOC(tr->k, tmp, sizeof(int) *2*tr->nalloc);
165 ESL_RALLOC(tr->i, tmp, sizeof(int) *2*tr->nalloc);
166 if (tr->pp != NULL) ESL_RALLOC(tr->pp, tmp, sizeof(float) *2*tr->nalloc);
167 tr->nalloc *= 2;
168 return eslOK;
169
170 ERROR:
171 return status;
172 }
173
174 /* Function: p7_trace_GrowIndex()
175 * Synopsis: Grows the allocation of the trace's domain index.
176 * Incept: SRE, Fri Jan 4 10:40:02 2008 [Janelia]
177 *
178 * Purpose: If <tr> can't fit another domain in its index,
179 * double the allocation of the index in <tr>.
180 *
181 * Returns: <eslOK> on success.
182 *
183 * Throws: <eslEMEM> on allocation failure; in this case, the
184 * data in <tr> are unaffected.
185 */
186 int
187 p7_trace_GrowIndex(P7_TRACE *tr)
188 {
189 void *p;
190 int status;
191
192 if (tr->ndom < tr->ndomalloc) return eslOK;
193
194 ESL_RALLOC(tr->tfrom, p, sizeof(int)*2*tr->ndomalloc);
195 ESL_RALLOC(tr->tto, p, sizeof(int)*2*tr->ndomalloc);
196 ESL_RALLOC(tr->sqfrom, p, sizeof(int)*2*tr->ndomalloc);
197 ESL_RALLOC(tr->sqto, p, sizeof(int)*2*tr->ndomalloc);
198 ESL_RALLOC(tr->hmmfrom, p, sizeof(int)*2*tr->ndomalloc);
199 ESL_RALLOC(tr->hmmto, p, sizeof(int)*2*tr->ndomalloc);
200 tr->ndomalloc *= 2;
201 return eslOK;
202
203 ERROR:
204 return status;
205 }
206
207
208 /* Function: p7_trace_GrowTo()
209 * Synopsis: Reallocates trace to a given minimum size.
210 *
211 * Purpose: Reallocates a trace structure <tr> to hold a trace
212 * of at least length <N> states.
213 *
214 * Returns: <eslOK> on success.
215 *
216 * Throws: <eslEMEM> on allocation failure; the data in <tr>
217 * are unaffected by failure.
218 */
219 int
220 p7_trace_GrowTo(P7_TRACE *tr, int N)
221 {
222 int status;
223 void *tmp;
224
225 if (N < tr->nalloc) return eslOK; /* no-op */
226
227 ESL_RALLOC(tr->st, tmp, sizeof(char) *N);
228 ESL_RALLOC(tr->k, tmp, sizeof(int) *N);
229 ESL_RALLOC(tr->i, tmp, sizeof(int) *N);
230 if (tr->pp != NULL) ESL_RALLOC(tr->pp, tmp, sizeof(float) *N);
231 tr->nalloc = N;
232 return eslOK;
233
234 ERROR:
235 return status;
236 }
237
238
239 /* Function: p7_trace_GrowIndexTo()
240 * Synopsis: Reallocates domain index for a given minimum number.
241 * Incept: SRE, Fri Jan 4 10:47:43 2008 [Janelia]
242 *
243 * Purpose: Reallocates the domain index in <tr> to index
244 * at least <ndom> domains.
245 *
246 * Returns: <eslOK> on success.
247 *
248 * Throws: <eslEMEM> on allocation failure, in which case
249 * the data in <tr> are unaffected.
250 */
251 int
252 p7_trace_GrowIndexTo(P7_TRACE *tr, int ndom)
253 {
254 void *p;
255 int status;
256
257 if (ndom < tr->ndomalloc) return eslOK;
258
259 ESL_RALLOC(tr->tfrom, p, sizeof(int)*ndom);
260 ESL_RALLOC(tr->tto, p, sizeof(int)*ndom);
261 ESL_RALLOC(tr->sqfrom, p, sizeof(int)*ndom);
262 ESL_RALLOC(tr->sqto, p, sizeof(int)*ndom);
263 ESL_RALLOC(tr->hmmfrom, p, sizeof(int)*ndom);
264 ESL_RALLOC(tr->hmmto, p, sizeof(int)*ndom);
265 tr->ndomalloc = ndom;
266 return eslOK;
267
268 ERROR:
269 return status;
270 }
271
272
273 /* Function: p7_trace_Destroy()
274 * Synopsis: Frees a trace.
275 *
276 * Purpose: Frees a trace structure <tr>.
277 *
278 * Returns: (void)
279 */
280 void
281 p7_trace_Destroy(P7_TRACE *tr)
282 {
283 if (tr == NULL) return;
284 if (tr->st != NULL) free(tr->st);
285 if (tr->k != NULL) free(tr->k);
286 if (tr->i != NULL) free(tr->i);
287 if (tr->pp != NULL) free(tr->pp);
288 if (tr->tfrom != NULL) free(tr->tfrom);
289 if (tr->tto != NULL) free(tr->tto);
290 if (tr->sqfrom != NULL) free(tr->sqfrom);
291 if (tr->sqto != NULL) free(tr->sqto);
292 if (tr->hmmfrom != NULL) free(tr->hmmfrom);
293 if (tr->hmmto != NULL) free(tr->hmmto);
294 free(tr);
295 return;
296 }
297
298 /* Function: p7_trace_DestroyArray()
299 *
300 * Purpose: Frees an array of <N> trace structures, <tr[0..N-1]>.
301 *
302 * Returns: (void)
303 */
304 void
305 p7_trace_DestroyArray(P7_TRACE **tr, int N)
306 {
307 int idx;
308
309 if (tr == NULL) return;
310 for (idx = 0; idx < N; idx++)
311 {
312 if (tr[idx] == NULL) continue;
313 p7_trace_Destroy(tr[idx]);
314 }
315 free(tr);
316 return;
317 }
318
319 /*---------------------- end, P7_TRACE --------------------------*/
320
321
322
323
324 /*****************************************************************
325 * 2. Access routines
326 *****************************************************************/
327
328 /* Function: p7_trace_GetDomainCount()
329 * Incept: SRE, Tue Feb 27 13:11:43 2007 [Janelia]
330 *
331 * Purpose: Determine the number of hits in the trace <tr> -- that is,
332 * the number of times the trace traverses the model from
333 * B...E. Return that number in <ret_ndom>.
334 *
335 * Done simply by counting the number of B states used in
336 * the trace.
337 *
338 * Only sensible on profile traces. Core traces have 1
339 * domain by definition.
340 *
341 * Returns: <eslOK> on success.
342 *
343 * Throws: (no abnormal error conditions)
344 */
345 int
346 p7_trace_GetDomainCount(const P7_TRACE *tr, int *ret_ndom)
347 {
348 int z;
349 int ndom = 0;
350
351 if (tr->ndom > 0)
352 ndom = tr->ndom; /* if we already indexed the domains, we know the answer */
353 else {
354 for (z = 0; z < tr->N; z++)
355 if (tr->st[z] == p7T_B) ndom++;
356 }
357 *ret_ndom = ndom;
358 return eslOK;
359 }
360
361 /* Function: p7_trace_GetStateUseCounts()
362 * Incept: SRE, Sun May 27 10:30:13 2007 [Janelia]
363 *
364 * Purpose: Accumulate counts of each different state type in trace <tr>.
365 *
366 * <counts[]> is allocated for at least <p7T_NSTATETYPES>
367 * integers, indexed by statetype. Upon return,
368 * <counts[p7T_M]> contains the number of match states
369 * in the trace, for example.
370 */
371 int
372 p7_trace_GetStateUseCounts(const P7_TRACE *tr, int *counts)
373 {
374 int x,z;
375
376 for (x = 0; x < p7T_NSTATETYPES; x++) counts[x] = 0;
377
378 for (z = 0; z < tr->N; z++) {
379 x = tr->st[z];
380 if (x < 0 || x >= p7T_NSTATETYPES) ESL_EXCEPTION(eslEINVAL, "bad state type");
381 counts[x]++;
382 }
383 return eslOK;
384 }
385
386 /* Function: p7_trace_GetDomainCoords()
387 * Incept: SRE, Tue Feb 27 13:08:32 2007 [Janelia]
388 *
389 * Purpose: Retrieve the bounds of domain alignment number <which> in
390 * traceback <tr>. <which> starts from 0. The total number
391 * of domains in a trace can be obtained from
392 * <p7_trace_GetDomainCount()>, or caller can just loop
393 * an increasing <which> count until <eslEOD> is returned.
394 *
395 * Start/end in the sequence are returned in <ret_i1>,
396 * <ret_i2>. Start/end in the model are returned in <ret_k1>,
397 * <ret_k2>.
398 *
399 * It only makes sense to call this function on profile
400 * traces.
401 *
402 * By local alignment bounds convention, the domain
403 * alignment is defined as bounded by match states, so <k1>
404 * and <k2> are the coords of the first and last match
405 * state (in range 1..M), and <i1> and <i2> are the coords
406 * of the residues aligned to those match states. Profiles
407 * do allow a Mk->DDD->E trailer; nonetheless, if such a
408 * trailer occurs, the k2 coord still refers to the last
409 * match state's coordinate. Note that such trailers would
410 * only occur in generated or sampled paths, not Viterbi
411 * paths; in Viterbi alignments with exit probabilities of
412 * 1.0, the direct Mk->E path will always have higher
413 * probability than a Mk->DDD->E path.
414 *
415 * Returns: <eslOK> on success, and the coords are returned.
416 * <eslEOD> if the trace doesn't contain a <which>'th
417 * domain, and the coords are all returned as 0.
418 *
419 * Throws: <eslEINVAL> if you stupidly pass a <which> less than 0;
420 * <eslECORRUPT> if something is grievously wrong with <tr>.
421 */
422 int
423 p7_trace_GetDomainCoords(const P7_TRACE *tr, int which,
424 int *ret_i1, int *ret_i2, int *ret_k1, int *ret_k2)
425 {
426 int status;
427 int z;
428
429 if (which < 0) ESL_XEXCEPTION(eslEINVAL, "bad which < 0");
430
431 if (tr->ndom) /* do we have an index? then this'll be easy */
432 {
433 if (which >= tr->ndom) { status = eslEOD; goto ERROR; }
434 *ret_i1 = tr->sqfrom[which];
435 *ret_i2 = tr->sqto[which];
436 *ret_k1 = tr->hmmfrom[which];
437 *ret_k2 = tr->hmmto[which];
438 return eslOK;
439 }
440
441 /* else, the hard way.
442 * skip z to one state past the which'th B state.
443 */
444 for (z = 0; which >= 0 && z < tr->N; z++)
445 if (tr->st[z] == p7T_B) which--;
446 if (z == tr->N) { status = eslEOD; goto ERROR; }
447
448 /* skip to the first M state and record i1,k1:
449 * in a profile trace, this must be the next state.
450 */
451 if (tr->st[z] != p7T_M) ESL_XEXCEPTION(eslECORRUPT, "not a profile trace?");
452 *ret_i1 = tr->i[z];
453 *ret_k1 = tr->k[z];
454
455 /* skip to the end E, then look back at the last M, record i2,k2.
456 */
457 for (; z < tr->N; z++)
458 if (tr->st[z] == p7T_E) break;
459 if (z == tr->N) ESL_EXCEPTION(eslECORRUPT, "invalid trace: no E for a B");
460 do { z--; } while (tr->st[z] == p7T_D); /* roll back over any D trailer */
461 if (tr->st[z] != p7T_M) ESL_EXCEPTION(eslECORRUPT, "invalid trace: no M");
462 *ret_i2 = tr->i[z];
463 *ret_k2 = tr->k[z];
464 return eslOK;
465
466 ERROR:
467 *ret_i1 = 0;
468 *ret_i2 = 0;
469 *ret_k1 = 0;
470 *ret_k2 = 0;
471 return status;
472 }
473 /*---------------- end, access routines -------------------------*/
474
475
476
477
478 /*****************************************************************
479 * 3. Debugging tools.
480 *****************************************************************/
481
482 /* Function: p7_trace_Validate()
483 * Incept: SRE, Fri Jan 5 09:17:24 2007 [Janelia]
484 *
485 * Purpose: Validate the internal data in a trace structure <tr>
486 * representing an alignment of an HMM to a
487 * digital sequence <sq>. The digital sequence may be either
488 * unaligned (usually) or aligned (in the case of "fake"
489 * tracebacks generated from an MSA during a
490 * model construction process).
491 *
492 * We don't pass the HMM that the trace is associated with,
493 * because we might have constructed the trace during
494 * HMM construction when we don't have an HMM yet; but
495 * we always have a digital sequence.
496 *
497 * Intended for debugging, development, and testing
498 * purposes.
499 *
500 * Args: tr - trace to validate
501 * abc - alphabet corresponding to sequence <sq>
502 * sq - digital sequence that <tr> is explaining
503 * errbuf - NULL, or an error message buffer allocated
504 * for at least eslERRBUFSIZE chars.
505 *
506 * Returns: <eslOK> if trace appears fine.
507 * Returns <eslFAIL> if a problem is detected; if <errbuf> is
508 * provided (non-<NULL>), an informative message is formatted
509 * there to indicate the reason for the failure.
510 */
511 int
512 p7_trace_Validate(const P7_TRACE *tr, const ESL_ALPHABET *abc, const ESL_DSQ *dsq, char *errbuf)
513 {
514 int z; /* position in trace */
515 int i; /* position in sequence */
516 int k; /* position in model */
517 char prv; /* type of the previous state */
518 int is_core; /* TRUE if trace is a core trace, not profile */
519
520 /* minimum trace length is a core's B->Mk->E. If we don't have at least that,
521 * we're definitely in trouble
522 */
523 if (tr->N < 3) ESL_FAIL(eslFAIL, errbuf, "trace is too short");
524 if (tr->N > tr->nalloc) ESL_FAIL(eslFAIL, errbuf, "N of %d isn't sensible", tr->N);
525
526 /* Determine if this is a core trace or a profile trace, so we can
527 * construct validation tests appropriately.
528 */
529 if (tr->st[0] == p7T_B) is_core = TRUE;
530 else if (tr->st[0] == p7T_S) is_core = FALSE;
531 else ESL_FAIL(eslFAIL, errbuf, "first state neither S nor B");
532
533 /* Verify "sentinels", the final states of the trace
534 * (before we start looking backwards and forwards from each state in
535 * our main validation loop)
536 */
537 if (is_core && tr->st[tr->N-1] != p7T_E) ESL_FAIL(eslFAIL, errbuf, "last state not E");
538 if (!is_core && tr->st[tr->N-1] != p7T_T) ESL_FAIL(eslFAIL, errbuf, "last state not T");
539 if (tr->k[0] != 0) ESL_FAIL(eslFAIL, errbuf, "first state shouldn't have k set");
540 if (tr->i[0] != 0) ESL_FAIL(eslFAIL, errbuf, "first state shouldn't have i set");
541 if (tr->k[tr->N-1] != 0) ESL_FAIL(eslFAIL, errbuf, "last state shouldn't have k set");
542 if (tr->i[tr->N-1] != 0) ESL_FAIL(eslFAIL, errbuf, "last state shouldn't have i set");
543
544 if (tr->pp != NULL && tr->pp[0] != 0.0) ESL_FAIL(eslFAIL, errbuf, "first state doesn't emit; but post prob isn't 0");
545 if (tr->pp != NULL && tr->pp[tr->N-1] != 0.0) ESL_FAIL(eslFAIL, errbuf, "last state doesn't emit; but post prob isn't 0");
546
547 /* Main validation loop. */
548 k = 0;
549 i = 1;
550 for (z = 1; z < tr->N-1; z++)
551 {
552 for (; dsq[i] != eslDSQ_SENTINEL; i++) /* find next non-gap residue in dsq */
553 if (esl_abc_XIsResidue(abc, dsq[i]) || esl_abc_XIsNonresidue(abc, dsq[i])) break; /* '*' included as emitted "residue" */
554
555 /* watch out for missing data states X: can only be one.
556 * prv state might have to skip over one (but not more) missing data states
557 */
558 prv = (tr->st[z-1] == p7T_X)? tr->st[z-2] : tr->st[z-1];
559
560 switch (tr->st[z]) {
561 case p7T_S:
562 ESL_FAIL(eslFAIL, errbuf, "S must be first state");
563 break;
564
565 case p7T_X:
566 if (! is_core) ESL_FAIL(eslFAIL, errbuf, "X state (missing data) only appears in core traces");
567 if (prv != p7T_B && tr->st[z+1] != p7T_E) /* only B->X and X->E are possible */
568 ESL_FAIL(eslFAIL, errbuf, "bad transition involving missing data (X state) not at start/end");
569 break;
570
571 case p7T_N:
572 if (is_core) ESL_FAIL(eslFAIL, errbuf, "core trace can't contain N");
573 if (tr->k[z] != 0) ESL_FAIL(eslFAIL, errbuf, "no N should have k set");
574 if (prv == p7T_S) { /* 1st N doesn't emit */
575 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "first N shouldn't have i set");
576 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "first N can't have nonzero post prob");
577 } else if (prv == p7T_N) { /* subsequent N's do */
578 if (tr->i[z] != i) ESL_FAIL(eslFAIL, errbuf, "expected i doesn't match trace's i");
579 i++;
580 } else ESL_FAIL(eslFAIL, errbuf, "bad transition to N; expected {S,N}->N");
581 break;
582
583 case p7T_B:
584 if (tr->k[z] != 0) ESL_FAIL(eslFAIL, errbuf, "B shouldn't have k set");
585 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "B shouldn't have i set");
586 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "B can't have nonzero post prob");
587 if (prv != p7T_N && prv != p7T_J)
588 ESL_FAIL(eslFAIL, errbuf, "bad transition to B; expected {N,J}->B");
589 break;
590
591 case p7T_M:
592 if (prv == p7T_B) k = tr->k[z]; else k++; /* on a B->Mk entry, trust k; else verify */
593
594 if (tr->k[z] != k) ESL_FAIL(eslFAIL, errbuf, "expected k doesn't match trace's k");
595 if (tr->i[z] != i) ESL_FAIL(eslFAIL, errbuf, "expected i doesn't match trace's i");
596 if (prv != p7T_B && prv != p7T_M && prv != p7T_D && prv != p7T_I)
597 ESL_FAIL(eslFAIL, errbuf, "bad transition to M; expected {B,M,D,I}->M");
598 i++;
599 break;
600
601 case p7T_D:
602 k++;
603 if (tr->st[z-1] == p7T_X) k = tr->k[z]; /* with fragments, a X->Ik case is possible */
604 if (tr->k[z] != k) ESL_FAIL(eslFAIL, errbuf, "expected k doesn't match trace's k");
605 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "D shouldn't have i set");
606 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "D can't have nonzero post prob");
607 if (is_core) {
608 if (prv != p7T_M && prv != p7T_D && prv != p7T_B)
609 ESL_FAIL(eslFAIL, errbuf, "bad transition to D; expected {B,M,D}->D");
610 } else {
611 if (prv != p7T_M && prv != p7T_D)
612 ESL_FAIL(eslFAIL, errbuf, "bad transition to D; expected {M,D}->D");
613 }
614 break;
615
616 case p7T_I:
617 if (tr->st[z-1] == p7T_X) k = tr->k[z]; /* with fragments, a X->Ik case is possible */
618 if (tr->k[z] != k) ESL_FAIL(eslFAIL, errbuf, "expected k doesn't match trace's k");
619 if (tr->i[z] != i) ESL_FAIL(eslFAIL, errbuf, "expected i doesn't match trace's i");
620 if (is_core) {
621 if (prv != p7T_B && prv != p7T_M && prv != p7T_I)
622 ESL_FAIL(eslFAIL, errbuf, "bad transition to I; expected {B,M,I}->I");
623 } else {
624 if (prv != p7T_M && prv != p7T_I)
625 ESL_FAIL(eslFAIL, errbuf, "bad transition to I; expected {M,I}->I");
626 }
627 i++;
628 break;
629
630 case p7T_E:
631 if (tr->k[z] != 0) ESL_FAIL(eslFAIL, errbuf, "E shouldn't have k set");
632 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "E shouldn't have i set");
633 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "E can't have nonzero post prob");
634 if (is_core) {
635 if (prv != p7T_M && prv != p7T_D && prv != p7T_I)
636 ESL_FAIL(eslFAIL, errbuf, "bad transition to E; expected {M,D,I}->E");
637 } else {
638 if (prv != p7T_M && prv != p7T_D)
639 ESL_FAIL(eslFAIL, errbuf, "bad transition to E; expected {M,D}->E");
640 }
641 break;
642
643 case p7T_J:
644 if (tr->k[z] != 0) ESL_FAIL(eslFAIL, errbuf, "no J should have k set");
645 if (prv == p7T_E) { /* 1st J doesn't emit */
646 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "first J shouldn't have i set");
647 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "first J can't have nonzero post prob");
648 } else if (prv == p7T_J) { /* subsequent J's do */
649 if (tr->i[z] != i) ESL_FAIL(eslFAIL, errbuf, "expected i doesn't match trace's i");
650 i++;
651 } else ESL_FAIL(eslFAIL, errbuf, "bad transition to J; expected {E,J}->J");
652 break;
653
654 case p7T_C:
655 if (is_core) ESL_FAIL(eslFAIL, errbuf, "core trace can't contain C");
656 if (tr->k[z] != 0) ESL_FAIL(eslFAIL, errbuf, "no C should have k set");
657 if (prv == p7T_E) { /* 1st C doesn't emit */
658 if (tr->i[z] != 0) ESL_FAIL(eslFAIL, errbuf, "first C shouldn't have i set");
659 if (tr->pp != NULL && tr->pp[z] != 0.0) ESL_FAIL(eslFAIL, errbuf, "first C can't have nonzero post prob");
660 } else if (prv == p7T_C) { /* subsequent C's do */
661 if (tr->i[z] != i) ESL_FAIL(eslFAIL, errbuf, "expected i doesn't match trace's i");
662 i++;
663 } else ESL_FAIL(eslFAIL, errbuf, "bad transition to C; expected {E,C}->C");
664 break;
665
666 case p7T_T:
667 ESL_FAIL(eslFAIL, errbuf, "T must be last state");
668 break;
669 }
670 }
671
672 /* Trace should have accounted for all residues in the dsq */
673 for (; dsq[i] != eslDSQ_SENTINEL; i++)
674 if (esl_abc_XIsResidue(abc, dsq[i]))
675 ESL_FAIL(eslFAIL, errbuf, "trace didn't account for all residues in the sq");
676
677 /* No k larger than M; no i-1 larger than L (i is sitting on dsq[n+1] sentinel right now) */
678 if (k > tr->M) ESL_FAIL(eslFAIL, errbuf, "M=%d, but k went to %d\n", tr->M, k);
679 if (i-1 > tr->L) ESL_FAIL(eslFAIL, errbuf, "L=%d, but i went to %d\n", tr->L, i);
680
681 return eslOK;
682 }
683
684
685 /* Function: p7_trace_Dump()
686 * Incept: SRE, Fri Jan 5 09:26:04 2007 [Janelia]
687 *
688 * Purpose: Dumps internals of a traceback structure <tr> to <fp>.
689 * If <gm> is non-NULL, also prints transition/emission scores.
690 * If <dsq> is non-NULL, also prints residues (using alphabet
691 * in the <gm>).
692 *
693 * Args: fp - stream to dump to (often stdout)
694 * tr - trace to dump
695 * gm - NULL, or score profile corresponding to trace
696 * dsq - NULL, or digitized seq corresponding to trace
697 *
698 * Returns: <eslOK> on success.
699 *
700 * Throws: <eslEINVAL> if trace contains something corrupt or invalid;
701 * in this case, dump will be aborted, possibly after partial
702 * output.
703 */
704 int
705 p7_trace_Dump(FILE *fp, const P7_TRACE *tr, const P7_PROFILE *gm, const ESL_DSQ *dsq) /* replace void w/ P7_PROFILE */
706 {
707 int z; /* counter for trace position */
708 if (tr == NULL) { fprintf(fp, " [ trace is NULL ]\n"); return eslOK; }
709
710 if (gm == NULL)
711 { /* Yes, this does get used: during model construction. */
712 fprintf(fp, "st k i - traceback len %d\n", tr->N);
713 fprintf(fp, "-- ---- ----\n");
714 for (z = 0; z < tr->N; z++) {
715 fprintf(fp, "%1s %4d %6d\n",
716 p7_hmm_DecodeStatetype(tr->st[z]),
717 tr->k[z],
718 tr->i[z]);
719 }
720 }
721 else
722 {
723 int status;
724 float accuracy = 0.0f;
725 float sc = 0.0f;
726 float tsc;
727 int xi;
728
729
730 fprintf(fp, "st k i transit emission postprob - traceback len %d\n", tr->N);
731 fprintf(fp, "-- ---- ------ -------- -------- --------\n");
732 for (z = 0; z < tr->N; z++)
733 {
734 if (z < tr->N-1)
735 {
736 status = p7_profile_GetT(gm, tr->st[z], tr->k[z], tr->st[z+1], tr->k[z+1], &tsc);
737 if (status != eslOK) return status;
738 }
739 else tsc = 0.0f;
740
741 fprintf(fp, "%1s %4d %6d %8.4f", p7_hmm_DecodeStatetype(tr->st[z]), tr->k[z], tr->i[z], tsc);
742 sc += tsc;
743
744 if (dsq != NULL) {
745 xi = dsq[tr->i[z]];
746
747 if (tr->st[z] == p7T_M) {
748 fprintf(fp, " %8.4f", p7P_MSC(gm, tr->k[z], xi));
749 sc += p7P_MSC(gm, tr->k[z], xi);
750 if (tr->pp != NULL) {
751 fprintf(fp, " %8.4f", tr->pp[z]);
752 accuracy += tr->pp[z];
753 }
754 fprintf(fp, " %c", gm->abc->sym[xi]);
755 }
756 else if (tr->st[z] == p7T_I) {
757 fprintf(fp, " %8.4f", p7P_ISC(gm, tr->k[z], xi));
758 sc += p7P_ISC(gm, tr->k[z], xi);
759 if (tr->pp != NULL) {
760 fprintf(fp, " %8.4f", tr->pp[z]);
761 accuracy += tr->pp[z];
762 }
763 fprintf(fp, " %c", (char) tolower((int) gm->abc->sym[xi]));
764 }
765 else if ((tr->st[z] == p7T_N && tr->st[z-1] == p7T_N) ||
766 (tr->st[z] == p7T_C && tr->st[z-1] == p7T_C) ||
767 (tr->st[z] == p7T_J && tr->st[z-1] == p7T_J)) {
768 fprintf(fp, " %8d", 0);
769 if (tr->pp != NULL) {
770 fprintf(fp, " %8.4f", tr->pp[z]);
771 accuracy += tr->pp[z];
772 }
773 fprintf(fp, " %c", (char) tolower((int) gm->abc->sym[xi]));
774 }
775 }
776 else fprintf(fp, " %8s %8s %c", "-", "-", '-');
777 fputs("\n", fp);
778 }
779 fprintf(fp, " -------- -------- --------\n");
780 fprintf(fp, " total: %8.4f %8.4f\n\n", sc, accuracy);
781 }
782
783
784 return eslOK;
785 }
786
787
788 /* Function: p7_trace_Compare()
789 * Synopsis: Compare two traces for identity
790 * Incept: SRE, Wed Aug 20 09:05:24 2008 [Janelia]
791 *
792 * Purpose: Compare two tracebacks; return <eslOK> if they
793 * are identical, <eslFAIL> if not.
794 *
795 * If posterior probability annotation is present in
796 * both traces, they are compared using <esl_FCompare_old()>
797 * and a relative tolerance of <pptol>.
798 *
799 * If domain indices are present in both traces,
800 * the two indexes are compared.
801 */
802 int
803 p7_trace_Compare(P7_TRACE *tr1, P7_TRACE *tr2, float pptol)
804 {
805 int z,d;
806
807 if (tr1->N != tr2->N) esl_fatal("FAIL");
808 if (tr1->M != tr2->M) esl_fatal("FAIL");
809 if (tr1->L != tr2->L) esl_fatal("FAIL");
810
811 /* Main data in the trace */
812 for (z = 0; z < tr1->N; z++)
813 {
814 if (tr1->st[z] != tr2->st[z]) esl_fatal("FAIL");
815 if (tr1->k[z] != tr2->k[z]) esl_fatal("FAIL");
816 if (tr1->i[z] != tr2->i[z]) esl_fatal("FAIL");
817 }
818
819 /* Optional posterior probability annotation */
820 if (tr1->pp != NULL && tr2->pp != NULL)
821 {
822 for (z = 0; z < tr1->N; z++)
823 if (tr1->i[z] != 0) /* an emission: has a nonzero posterior prob*/
824 {
825 if (esl_FCompare_old(tr1->pp[z], tr2->pp[z], pptol) != eslOK) esl_fatal("FAIL");
826 }
827 else
828 {
829 if (tr1->pp[z] != tr2->pp[z]) esl_fatal("FAIL"); /* both 0.0 */
830 }
831 }
832
833 /* Optional domain index */
834 if (tr1->ndom > 0 && tr2->ndom > 0)
835 {
836 if (tr1->ndom != tr2->ndom) esl_fatal("FAIL");
837
838 for (d = 0; d < tr1->ndom; d++)
839 {
840 if (tr1->tfrom[d] != tr2->tfrom[d]) esl_fatal("FAIL");
841 if (tr1->tto[d] != tr2->tto[d]) esl_fatal("FAIL");
842 if (tr1->sqfrom[d] != tr2->sqfrom[d]) esl_fatal("FAIL");
843 if (tr1->sqto[d] != tr2->sqto[d]) esl_fatal("FAIL");
844 if (tr1->hmmfrom[d] != tr2->hmmfrom[d]) esl_fatal("FAIL");
845 if (tr1->hmmto[d] != tr2->hmmto[d]) esl_fatal("FAIL");
846 }
847 }
848 return eslOK;
849 }
850
851
852
853
854 /* Function: p7_trace_Score()
855 * Incept: SRE, Tue Mar 6 14:40:34 2007 [Janelia]
856 *
857 * Purpose: Score path <tr> for digital target sequence <dsq>
858 * using profile <gm>. Return the lod score in
859 * <ret_sc>.
860 *
861 * Args: tr - traceback path to score
862 * dsq - digitized sequence
863 * gm - score profile
864 * ret_sc - RETURN: lod score of trace <tr>
865 *
866 * Returns: <eslOK> on success, and <*ret_sc> contains the
867 * lod score for the trace.
868 *
869 * Throws: <eslEINVAL> if something's wrong with the trace.
870 * Now <*ret_sc> is returned as $-\infty$.
871 */
872 int
873 p7_trace_Score(P7_TRACE *tr, ESL_DSQ *dsq, P7_PROFILE *gm, float *ret_sc)
874 {
875 float sc; /* total lod score */
876 float tsc; /* a transition score */
877 int z; /* position in tr */
878 int xi; /* digitized symbol in dsq */
879 int status;
880
881 sc = 0.0f;
882 for (z = 0; z < tr->N-1; z++) {
883 xi = dsq[tr->i[z]];
884
885 if (tr->st[z] == p7T_M) sc += p7P_MSC(gm, tr->k[z], xi);
886 else if (tr->st[z] == p7T_I) sc += p7P_ISC(gm, tr->k[z], xi);
887
888 if ((status = p7_profile_GetT(gm, tr->st[z], tr->k[z],
889 tr->st[z+1], tr->k[z+1], &tsc)) != eslOK) goto ERROR;
890 sc += tsc;
891 }
892
893 *ret_sc = sc;
894 return eslOK;
895
896 ERROR:
897 *ret_sc = -eslINFINITY;
898 return status;
899 }
900
901 /* Function: p7_trace_SetPP()
902 * Synopsis: Set posterior probs of an arbitrary trace.
903 * Incept: SRE, Tue Aug 19 14:16:10 2008 [Janelia]
904 *
905 * Purpose: Set the posterior probability fields of an arbitrary
906 * trace <tr>, by accessing posterior residue probabilities
907 * in decoding matrix <pp>.
908 *
909 * In general, <pp> was created by <p7_GDecoding()>
910 * or converted from the optimized matrix created by
911 * <p7_Decoding()>.
912 *
913 * This is classed as a debugging function for the moment,
914 * because in general traces with posterior probabilities are
915 * created directly using optimal accuracy DP routines.
916 * This function allows us to add PP annotation to any
917 * trace.
918 *
919 * Returns: <eslOK> on success.
920 *
921 * Throws: <eslEMEM> on allocation error.
922 * <eslEINVAL> on internal corruptions.
923 */
924 int
925 p7_trace_SetPP(P7_TRACE *tr, const P7_GMX *pp)
926 {
927 float **dp = pp->dp; /* so {MDI}MX() macros work */
928 float *xmx = pp->xmx; /* so XMX() macro works */
929 int z;
930 int status;
931
932 if (tr->pp == NULL) ESL_ALLOC(tr->pp, sizeof(float) * tr->nalloc);
933
934 for (z = 0; z < tr->N; z++)
935 {
936 if (tr->i[z] > 0) /* an emitting state? */
937 {
938 switch (tr->st[z]) {
939 case p7T_M: tr->pp[z] = MMX(tr->i[z], tr->k[z]); break;
940 case p7T_I: tr->pp[z] = IMX(tr->i[z], tr->k[z]); break;
941 case p7T_N: tr->pp[z] = XMX(tr->i[z], p7G_N); break;
942 case p7T_C: tr->pp[z] = XMX(tr->i[z], p7G_C); break;
943 case p7T_J: tr->pp[z] = XMX(tr->i[z], p7G_J); break;
944 default: ESL_EXCEPTION(eslEINVAL, "no such emitting state");
945 }
946 }
947 else
948 tr->pp[z] = 0.0;
949 }
950 return eslOK;
951
952 ERROR:
953 return status;
954 }
955
956 /* Function: p7_trace_GetExpectedAccuracy()
957 * Synopsis: Returns the sum of the posterior residue decoding probs.
958 * Incept: SRE, Tue Aug 19 15:29:18 2008 [Janelia]
959 */
960 float
961 p7_trace_GetExpectedAccuracy(const P7_TRACE *tr)
962 {
963 float accuracy = 0.0;
964 int z;
965
966 for (z = 0; z < tr->N; z++)
967 accuracy += tr->pp[z];
968 return accuracy;
969 }
970
971 /*------------------ end, debugging tools -----------------------*/
972
973
974
975
976 /*****************************************************************
977 * 4. Creating traces by DP traceback
978 *****************************************************************/
979
980 /* Function: p7_trace_Append()
981 * Synopsis: Add an element (state/residue) to a growing trace.
982 *
983 * Purpose: Adds an element to a trace <tr> that is growing
984 * left-to-right. The element is defined by a state type
985 * <st> (such as <p7T_M>); a node index <k> (1..M for
986 * M,D,I main states; else 0); and a dsq position <i> (1..L
987 * for emitters, else 0).
988 *
989 * For CNJ states, which emit on transition, by convention
990 * we associate the emission with the downstream state; therefore
991 * the first state in any run of CNJ states has i=0.
992 *
993 * Reallocates the trace (by doubling) if necessary.
994 *
995 * Caller can grow a trace right-to-left too, if it
996 * plans to call <p7_trace_Reverse()>.
997 *
998 * Returns: <eslOK> on success.
999 *
1000 * Throws: <eslEMEM> on reallocation failure. The element is successfully
1001 * added, but no more elements can be added before this trace is
1002 * destroyed.
1003 *
1004 * <eslEINVAL> if you try to add an element to a trace whose
1005 * reallocation has already failed.
1006 */
1007 int
1008 p7_trace_Append(P7_TRACE *tr, char st, int k, int i)
1009 {
1010 int status;
1011
1012 if ((status = p7_trace_Grow(tr)) != eslOK) return status;
1013
1014 switch (st) {
1015 /* Emit-on-transition states: */
1016 case p7T_N:
1017 case p7T_C:
1018 case p7T_J:
1019 tr->i[tr->N] = ( (tr->st[tr->N-1] == st) ? i : 0);
1020 tr->k[tr->N] = 0;
1021 break;
1022 /* Nonemitting states, outside main model: */
1023 case p7T_X:
1024 case p7T_S:
1025 case p7T_B:
1026 case p7T_E:
1027 case p7T_T: tr->i[tr->N] = 0; tr->k[tr->N] = 0; break;
1028 /* Nonemitting, but in main model (k valid) */
1029 case p7T_D: tr->i[tr->N] = 0; tr->k[tr->N] = k; break;
1030 /* Emitting states, with valid k position in model: */
1031 case p7T_M:
1032 case p7T_I: tr->i[tr->N] = i; tr->k[tr->N] = k; break;
1033 default: ESL_EXCEPTION(eslEINVAL, "no such state; can't append");
1034 }
1035
1036 tr->st[tr->N] = st;
1037 tr->N++;
1038 return eslOK;
1039 }
1040
1041 /* Function: p7_trace_AppendWithPP()
1042 * Synopsis: Add element to growing trace, with posterior probability.
1043 *
1044 * Purpose: Same as <p7_trace_Append()>, but also records a posterior
1045 * probability estimate for emitted residues. <pp> is assumed to be
1046 * zero for nonemitting states even if a nonzero argument is
1047 * mistakenly passed.
1048 */
1049 int
1050 p7_trace_AppendWithPP(P7_TRACE *tr, char st, int k, int i, float pp)
1051 {
1052 int status;
1053
1054 if ((status = p7_trace_Grow(tr)) != eslOK) return status;
1055
1056 switch (st) {
1057 /* Emit-on-transition states: */
1058 case p7T_N:
1059 case p7T_C:
1060 case p7T_J:
1061 if (tr->st[tr->N-1] == st)
1062 {
1063 tr->i[tr->N] = i;
1064 tr->pp[tr->N] = pp;
1065 }
1066 else
1067 {
1068 tr->i[tr->N] = 0;
1069 tr->pp[tr->N] = 0.0;
1070 }
1071 tr->k[tr->N] = 0;
1072 break;
1073 /* Nonemitting states, outside main model: */
1074 case p7T_X:
1075 case p7T_S:
1076 case p7T_B:
1077 case p7T_E:
1078 case p7T_T: tr->i[tr->N] = 0; tr->pp[tr->N] = 0.0; tr->k[tr->N] = 0; break;
1079 /* Nonemitting, but in main model (k valid) */
1080 case p7T_D: tr->i[tr->N] = 0; tr->pp[tr->N] = 0.0; tr->k[tr->N] = k; break;
1081 /* Emitting states, with valid k position in model: */
1082 case p7T_M:
1083 case p7T_I: tr->i[tr->N] = i; tr->pp[tr->N] = pp; tr->k[tr->N] = k; break;
1084 default: ESL_EXCEPTION(eslEINVAL, "no such state; can't append");
1085 }
1086
1087 tr->st[tr->N] = st;
1088 tr->N++;
1089 return eslOK;
1090 }
1091
1092 /* Function: p7_trace_Reverse()
1093 * Synopsis: Reverse the arrays in a traceback structure.
1094 *
1095 * Purpose: Reverse the arrays in a traceback structure. Tracebacks
1096 * from DP algorithms are collected backwards, and they call this
1097 * function when they're done.
1098 *
1099 * At least for now, this invalidates any domain index
1100 * table, if it exists. The expectd order of invocation is
1101 * to create the traceback backwards, <Reverse()> it, then
1102 * <IndexDomains()> it.
1103 *
1104 * Args: tr - the traceback to reverse. tr->N must be set.
1105 *
1106 * Return: <eslOK> on success; <tr> is modified.
1107 */
1108 int
1109 p7_trace_Reverse(P7_TRACE *tr)
1110 {
1111 int z;
1112 int tmp;
1113 float tmpf;
1114
1115 /* For emit-on-transition states N,C,J, traces always obey the
1116 * C-,Cx,Cx,Cx convention even when they were constructed backwards;
1117 * so we make them Cx,Cx,Cx,C- by pulling residues backwards by one,
1118 * just before reversing them. (Other ways of doing this would be
1119 * fine too.
1120 */
1121 for (z = 0; z < tr->N; z++)
1122 {
1123 if ( (tr->st[z] == p7T_N && tr->st[z+1] == p7T_N) ||
1124 (tr->st[z] == p7T_C && tr->st[z+1] == p7T_C) ||
1125 (tr->st[z] == p7T_J && tr->st[z+1] == p7T_J))
1126 {
1127 if (tr->i[z] == 0 && tr->i[z+1] > 0)
1128 {
1129 tr->i[z] = tr->i[z+1];
1130 tr->i[z+1] = 0;
1131 if (tr->pp != NULL) {
1132 tr->pp[z] = tr->pp[z+1];
1133 tr->pp[z+1] = 0.0;
1134 }
1135 }
1136 }
1137 }
1138
1139 /* Reverse the trace in place. */
1140 for (z = 0; z < tr->N/2; z++)
1141 {
1142 tmp = tr->st[tr->N-z-1]; tr->st[tr->N-z-1] = tr->st[z]; tr->st[z] = tmp;
1143 tmp = tr->k[tr->N-z-1]; tr->k[tr->N-z-1] = tr->k[z]; tr->k[z] = tmp;
1144 tmp = tr->i[tr->N-z-1]; tr->i[tr->N-z-1] = tr->i[z]; tr->i[z] = tmp;
1145 if (tr->pp != NULL) {
1146 tmpf = tr->pp[tr->N-z-1]; tr->pp[tr->N-z-1] = tr->pp[z]; tr->pp[z] = tmpf;
1147 }
1148 }
1149 /* don't worry about the middle residue in odd-length N, since we're in-place */
1150 return eslOK;
1151 }
1152
1153
1154 /* Function: p7_trace_Index()
1155 * Synopsis: Internally index the domains in a trace.
1156 * Incept: SRE, Fri Jan 4 11:12:24 2008 [Janelia]
1157 *
1158 * Purpose: Create an internal index of the domains in <tr>.
1159 * This makes calls to <GetDomainCount()> and
1160 * <GetDomainCoords()> more efficient, and it is
1161 * a necessary prerequisite for creating alignments
1162 * of any individual domains in a multidomain trace with
1163 * <p7_alidisplay_Create()>.
1164 *
1165 * Returns: <eslOK> on success.
1166 *
1167 * Throws: <eslEMEM> on allocation failure, in which case the
1168 * data in the trace is still fine, but the domain index
1169 * table isn't constructed.
1170 */
1171 int
1172 p7_trace_Index(P7_TRACE *tr)
1173 {
1174 int z;
1175 int status;
1176
1177 tr->ndom = 0;
1178 for (z = 0; z < tr->N; z++)
1179 {
1180 switch (tr->st[z]) {
1181 case p7T_B:
1182 if ((status = p7_trace_GrowIndex(tr)) != eslOK) goto ERROR;
1183 tr->tfrom[tr->ndom] = z;
1184 tr->sqfrom[tr->ndom] = 0;
1185 tr->hmmfrom[tr->ndom] = 0;
1186 break;
1187
1188 case p7T_M:
1189 if (tr->sqfrom[tr->ndom] == 0) tr->sqfrom[tr->ndom] = tr->i[z];
1190 if (tr->hmmfrom[tr->ndom] == 0) tr->hmmfrom[tr->ndom] = tr->k[z];
1191 tr->sqto[tr->ndom] = tr->i[z];
1192 tr->hmmto[tr->ndom] = tr->k[z];
1193 break;
1194
1195 case p7T_E:
1196 tr->tto[tr->ndom] = z;
1197 tr->ndom++;
1198 break;
1199 }
1200 }
1201 return eslOK;
1202
1203 ERROR:
1204 return status;
1205 }
1206 /*----------- end, creating traces by DP traceback ---------------*/
1207
1208
1209 /*****************************************************************
1210 * 5. Creating faux traces from MSAs
1211 *****************************************************************/
1212
1213 /* Function: p7_trace_FauxFromMSA()
1214 * Synopsis: Create array of faux tracebacks from an existing MSA.
1215 * Incept: SRE, Thu May 21 08:07:25 2009 [Janelia]
1216 *
1217 * Purpose: Given an existing <msa> and an array <matassign> that
1218 * flags the alignment columns that are assigned to consensus
1219 * match states (matassign[1..alen] = 1|0); create an array
1220 * of faux traces <tr[0..msa->nseq-1]>. <optflags> controls
1221 * optional behavior; it can be <p7_DEFAULT> or <p7_MSA_COORDS>,
1222 * as explained below.
1223 *
1224 * The traces are core traces: they start/end with B/E,
1225 * they may use I_0,I_M, and D_1 states. Any flanking
1226 * insertions (outside the first/last consensus column) are
1227 * assigned to I_0 and I_M.
1228 *
1229 * If the input alignment contains sequence fragments,
1230 * caller should first convert leading/trailing gaps to
1231 * missing data symbols. This hack causes entry/exit
1232 * transitions to be encoded in the trace as B->X->{MDI}k
1233 * and {MDI}k->X->E, rather than B->DDDD->Mk, Mk->DDDDD->E
1234 * paths involving terminal deletions, and all functions
1235 * that use traces, such as <p7_trace_Count()>, (should)
1236 * ignore transitions involving <p7T_X> states.
1237 *
1238 * By default (<optflags = p7_DEFAULT>), the <i> coordinate
1239 * in the faux tracebacks is <1..L>, relative to the
1240 * unaligned raw sequences in <msa>, the way most H3 traces
1241 * are supposed to be. In some cases (such as model
1242 * construction from an MSA) it is convenient to reference
1243 * residues in the MSA cooordinate system directly; setting
1244 * <optflags = p7_MSA_COORDS> makes the traces come out
1245 * with <i=1..alen> coords for residues.
1246 *
1247 * Important: an MSA may imply DI and ID transitions that
1248 * are illegal in a core model. If the only purpose of the
1249 * traces is to go straight back into alignment
1250 * construction through a <p7_tracealign_*> function, this
1251 * is ok, because the <p7_tracealign_*> routines can handle
1252 * DI and ID transitions (enabling reconstruction of almost
1253 * exactly the same input alignment, modulo unaligned
1254 * insertions). This is what happens for <hmmalign
1255 * --mapali>, for example. However, if the caller wants to
1256 * use the traces for anything else, these illegal DI and
1257 * ID transitions have to be removed first, and the caller
1258 * should use <p7_trace_Doctor()> to do it.
1259 *
1260 * Args: msa - digital alignment
1261 * matassign - flag for each alignment column, whether
1262 * it is consensus or not. matassign[1..alen] = 1|0;
1263 * matassign[0] = 0
1264 * optflags - p7_DEFAULT | p7_MSA_COORDS
1265 * tr - RETURN: caller provides 0..nseq-1 pointer
1266 * array for holding returned traces.
1267 *
1268 * Returns: <eslOK> on success, and tr[0..nseq-1] now point to newly
1269 * created traces; caller is responsible for freeing these.
1270 *
1271 * Throws: <eslEMEM> on allocation error.
1272 *
1273 * Xref: J5/17: build.c::fake_tracebacks() becomes p7_trace_FauxFromMSA();
1274 * ability to handle MSA or raw coords added.
1275 */
1276 int
1277 p7_trace_FauxFromMSA(ESL_MSA *msa, int *matassign, int optflags, P7_TRACE **tr)
1278 {
1279 int idx; /* counter over seqs in MSA */
1280 int k; /* position in HMM */
1281 int apos; /* position in alignment columns 1..alen */
1282 int rpos; /* position in unaligned sequence residues 1..L */
1283 int showpos; /* coord to actually record: apos or rpos */
1284 int status = eslOK;
1285
1286 for (idx = 0; idx < msa->nseq; idx++) tr[idx] = NULL;
1287
1288 for (idx = 0; idx < msa->nseq; idx++)
1289 {
1290 if ((tr[idx] = p7_trace_Create()) == NULL) goto ERROR;
1291 if ((status = p7_trace_Append(tr[idx], p7T_B, 0, 0)) != eslOK) goto ERROR;
1292
1293 for (k = 0, rpos = 1, apos = 1; apos <= msa->alen; apos++)
1294 {
1295 showpos = (optflags & p7_MSA_COORDS) ? apos : rpos;
1296
1297 if (matassign[apos])
1298 { /* match or delete */
1299 k++;
1300 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos]))
1301 status = p7_trace_Append(tr[idx], p7T_M, k, showpos);
1302 else if (esl_abc_XIsGap (msa->abc, msa->ax[idx][apos]))
1303 status = p7_trace_Append(tr[idx], p7T_D, k, 0);
1304 else if (esl_abc_XIsNonresidue(msa->abc, msa->ax[idx][apos]))
1305 status = p7_trace_Append(tr[idx], p7T_M, k, showpos); /* treat * as a residue! */
1306 else if (esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos]))
1307 {
1308 if (tr[idx]->st[tr[idx]->N-1] != p7T_X)
1309 status = p7_trace_Append(tr[idx], p7T_X, k, 0); /* allow only one X in a row */
1310 }
1311 else ESL_XEXCEPTION(eslEINCONCEIVABLE, "can't happen");
1312 }
1313 else
1314 { /* insert or nothing */
1315 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos]))
1316 status = p7_trace_Append(tr[idx], p7T_I, k, showpos);
1317 else if (esl_abc_XIsNonresidue(msa->abc, msa->ax[idx][apos]))
1318 status = p7_trace_Append(tr[idx], p7T_I, k, showpos); /* treat * as a residue! */
1319 else if (esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos]))
1320 {
1321 if (tr[idx]->st[tr[idx]->N-1] != p7T_X)
1322 status = p7_trace_Append(tr[idx], p7T_X, k, 0);
1323 }
1324 else if (! esl_abc_XIsGap(msa->abc, msa->ax[idx][apos]))
1325 ESL_XEXCEPTION(eslEINCONCEIVABLE, "can't happen");
1326 }
1327
1328 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos])) rpos++;
1329 if (status != eslOK) goto ERROR;
1330 }
1331 if ((status = p7_trace_Append(tr[idx], p7T_E, 0, 0)) != eslOK) goto ERROR;
1332 /* k == M by construction; set tr->L = msa->alen since coords are w.r.t. ax */
1333 tr[idx]->M = k;
1334 tr[idx]->L = msa->alen;
1335 }
1336 return eslOK;
1337
1338
1339 ERROR:
1340 for (idx = 0; idx < msa->nseq; idx++) { p7_trace_Destroy(tr[idx]); tr[idx] = NULL; }
1341 return status;
1342 }
1343
1344
1345
1346 /* Function: p7_trace_Doctor()
1347 * Incept: SRE, Thu May 21 08:45:46 2009 [Janelia]
1348 *
1349 * Purpose: Plan 7 disallows D->I and I->D "chatter" transitions.
1350 * However, these transitions will be implied by many
1351 * alignments. trace_doctor() arbitrarily collapses I->D or
1352 * D->I into a single M position in the trace.
1353 *
1354 * trace_doctor does not examine any scores when it does
1355 * this. In ambiguous situations (D->I->D) the symbol
1356 * will be pulled arbitrarily to the left, regardless
1357 * of whether that's the best column to put it in or not.
1358 *
1359 * Args: tr - trace to doctor
1360 * opt_ndi - optRETURN: number of DI transitions doctored
1361 * opt_nid - optRETURN: number of ID transitions doctored
1362 *
1363 * Return: <eslOK> on success, and the trace <tr> is modified.
1364 */
1365 int
1366 p7_trace_Doctor(P7_TRACE *tr, int *opt_ndi, int *opt_nid)
1367 {
1368 int opos; /* position in old trace */
1369 int npos; /* position in new trace (<= opos) */
1370 int ndi, nid; /* number of DI, ID transitions doctored */
1371
1372 /* overwrite the trace from left to right */
1373 ndi = nid = 0;
1374 opos = npos = 0;
1375 while (opos < tr->N) {
1376 /* fix implied D->I transitions; D transforms to M, I pulled in */
1377 if (tr->st[opos] == p7T_D && tr->st[opos+1] == p7T_I) {
1378 tr->st[npos] = p7T_M;
1379 tr->k[npos] = tr->k[opos]; /* D transforms to M */
1380 tr->i[npos] = tr->i[opos+1]; /* insert char moves back */
1381 opos += 2;
1382 npos += 1;
1383 ndi++;
1384 } /* fix implied I->D transitions; D transforms to M, I is pushed in */
1385 else if (tr->st[opos]== p7T_I && tr->st[opos+1]== p7T_D) {
1386 tr->st[npos] = p7T_M;
1387 tr->k[npos] = tr->k[opos+1]; /* D transforms to M */
1388 tr->i[npos] = tr->i[opos]; /* insert char moves up */
1389 opos += 2;
1390 npos += 1;
1391 nid++;
1392 } /* everything else is just copied */
1393 else {
1394 tr->st[npos] = tr->st[opos];
1395 tr->k[npos] = tr->k[opos];
1396 tr->i[npos] = tr->i[opos];
1397 opos++;
1398 npos++;
1399 }
1400 }
1401 tr->N = npos;
1402
1403 if (opt_ndi != NULL) *opt_ndi = ndi;
1404 if (opt_nid != NULL) *opt_nid = nid;
1405 return eslOK;
1406 }
1407 /*-------------- end, faux traces from MSAs ---------------------*/
1408
1409
1410 /*****************************************************************
1411 * 6. Counting traces into new HMMs.
1412 *****************************************************************/
1413
1414 /* Function: p7_trace_Count()
1415 *
1416 * Purpose: Count a traceback into a count-based core HMM structure.
1417 * (Usually as part of a model parameter re-estimation.)
1418 *
1419 * The traceback may either be a core traceback (as in model
1420 * construction) or a profile traceback (as in model
1421 * reestimation).
1422 *
1423 * If it is a profile traceback, we have to be careful how
1424 * we translate an internal entry path from a score profile
1425 * back to the core model. Sometimes a B->M_k transition is
1426 * an internal entry from local alignment, and sometimes it
1427 * is a wing-folded B->D_1..DDM_k alignment to the core
1428 * model.
1429 *
1430 * This is one of the purposes of the special p7T_X
1431 * 'missing data' state in tracebacks. Local alignment entry
1432 * is indicated by a B->X->{MDI}_k 'missing data' path, and
1433 * direct B->M_k or M_k->E transitions in a traceback are
1434 * interpreted as wing retraction in a glocal model.
1435 *
1436 * The <p7T_X> state is also used in core traces in model
1437 * construction literally to mean missing data, in the
1438 * treatment of sequence fragments.
1439 *
1440 * Args: hmm - counts-based HMM to count <tr> into
1441 * tr - alignment of seq to HMM
1442 * dsq - digitized sequence that traceback aligns to the HMM (1..L)
1443 * (or can be an ax, aligned digital seq)
1444 * wt - weight on this sequence
1445 *
1446 * Return: <eslOK> on success.
1447 * Weighted count events are accumulated in hmm's mat[][], ins[][],
1448 * t[][] fields: the core probability model.
1449 *
1450 * Throws: <eslEINVAL> if something's corrupt in the trace; effect on hmm
1451 * counts is undefined, because it may abort at any point in the trace.
1452 */
1453 int
1454 p7_trace_Count(P7_HMM *hmm, ESL_DSQ *dsq, float wt, P7_TRACE *tr)
1455 {
1456 int z; /* position index in trace */
1457 int i; /* symbol position in seq */
1458 int st,st2; /* state type (cur, nxt) */
1459 int k,k2,ktmp; /* node index (cur, nxt) */
1460 int z1 = 0; /* left bound - may get set to an M position for a left fragment */
1461 int z2 = tr->N-1; /* right bound, ditto for a right fragment. N-1 not N, because main loop accesses z,z+1 */
1462
1463 /* If this is a core fragment trace (it has B->X and/or X->E) then
1464 * set z1 and/or z2 bound on first and/or last M state, so we don't
1465 * count incomplete flanking insertions. A fragment doesn't
1466 * necessarily have X's on both sides because of the way they get
1467 * set from ~'s in an input alignment.
1468 *
1469 * A local alignment profile trace has B->X and X->E, and may have
1470 * >1 domain, but is guaranteed to be B->X->Mk, Mk->X->E, so
1471 * limiting trace counting to z1..z2 would have no effect... nonetheless,
1472 * we check, differentiating core vs. profile trace by the lead B vs S.
1473 *
1474 * It's possible for a core trace to have no M's at all, just
1475 * B->(X)->III->(X)->E, as in bug #h82, so watch out for that; we don't
1476 * count anything in such a trace, even the II transitions, because
1477 * we don't get to see the complete length of the insertion (or the
1478 * IM transition), so we don't want to be estimating the I-state
1479 * geometric distribution from it.
1480 *
1481 * We assume the core trace has already been through TraceDoctor(),
1482 * so it has no DI or ID transitions.
1483 */
1484 if (tr->st[0] == p7T_B && tr->st[1] == p7T_X)
1485 for (z = 2; z < tr->N-1; z++)
1486 if (tr->st[z] == p7T_M) { z1 = z; break; }
1487 if (tr->st[tr->N-1] == p7T_E && tr->st[tr->N-2] == p7T_X)
1488 for (z = tr->N-3; z > 0; z--)
1489 if (tr->st[z] == p7T_M) { z2 = z; break; }
1490
1491 for (z = z1; z < z2; z++)
1492 {
1493 if (tr->st[z] == p7T_X) continue; /* skip missing data */
1494
1495 /* pull some info into tmp vars for notational clarity later. */
1496 st = tr->st[z];
1497 st2 = tr->st[z+1];
1498 k = tr->k[z];
1499 k2 = tr->k[z+1];
1500 i = tr->i[z];
1501
1502 /* Emission counts. */
1503 if (st == p7T_M) esl_abc_FCount(hmm->abc, hmm->mat[k], dsq[i], wt);
1504 else if (st == p7T_I) esl_abc_FCount(hmm->abc, hmm->ins[k], dsq[i], wt);
1505
1506 /* Transition counts */
1507 if (st2 == p7T_X) continue; /* ignore transition to missing data */
1508
1509 if (st == p7T_B) {
1510 if (st2 == p7T_M && k2 > 1) /* wing-retracted B->DD->Mk path */
1511 {
1512 hmm->t[0][p7H_MD] += wt;
1513 for (ktmp = 1; ktmp < k2-1; ktmp++)
1514 hmm->t[ktmp][p7H_DD] += wt;
1515 hmm->t[ktmp][p7H_DM] += wt;
1516 }
1517 else {
1518 switch (st2) {
1519 case p7T_M: hmm->t[0][p7H_MM] += wt; break;
1520 case p7T_I: hmm->t[0][p7H_MI] += wt; break;
1521 case p7T_D: hmm->t[0][p7H_MD] += wt; break;
1522 default: ESL_EXCEPTION(eslEINVAL, "bad transition in trace");
1523 }
1524 }
1525 }
1526 else if (st == p7T_M) {
1527 switch (st2) {
1528 case p7T_M: hmm->t[k][p7H_MM] += wt; break;
1529 case p7T_I: hmm->t[k][p7H_MI] += wt; break;
1530 case p7T_D: hmm->t[k][p7H_MD] += wt; break;
1531 case p7T_E: hmm->t[k][p7H_MM] += wt; break; /* k==M. A local alignment would've been Mk->X->E. */
1532 default: ESL_EXCEPTION(eslEINVAL, "bad transition in trace");
1533 }
1534 }
1535 else if (st == p7T_I) {
1536 switch (st2) {
1537 case p7T_M: hmm->t[k][p7H_IM] += wt; break;
1538 case p7T_I: hmm->t[k][p7H_II] += wt; break;
1539 case p7T_E: hmm->t[k][p7H_IM] += wt; break; /* k==M. */
1540 default: ESL_EXCEPTION(eslEINVAL, "bad transition in trace");
1541 }
1542 }
1543 else if (st == p7T_D) {
1544 switch (st2) {
1545 case p7T_M: hmm->t[k][p7H_DM] += wt; break;
1546 case p7T_D: hmm->t[k][p7H_DD] += wt; break;
1547 case p7T_E: hmm->t[k][p7H_DM] += wt; break; /* k==M. A local alignment would've been Dk->X->E. */
1548 default: ESL_EXCEPTION(eslEINVAL, "bad transition in trace");
1549 }
1550 }
1551 } /* end loop over trace position */
1552 return eslOK;
1553 }
1554 /*--------------------- end, trace counting ---------------------*/
1555
1556
1557 /*****************************************************************
1558 * 7. Unit tests
1559 *****************************************************************/
1560 #ifdef p7TRACE_TESTDRIVE
1561
1562 /* convert an MSA to traces; then traces back to MSA;
1563 * starting and ending MSA should be the same, provided
1564 * the msa doesn't have any ambiguously aligned insertions.
1565 */
1566 static void
1567 utest_faux(ESL_MSA *msa, int *matassign, int M)
1568 {
1569 char *msg = "p7_trace.c:: FauxFromMSA unit test failed";
1570 ESL_MSA *msa2 = NULL;
1571 ESL_SQ **sq = malloc(sizeof(ESL_SQ) * msa->nseq);
1572 P7_TRACE **tr = malloc(sizeof(P7_TRACE) * msa->nseq);
1573 int i;
1574 int optflags = p7_DIGITIZE;
1575
1576 for (i = 0; i < msa->nseq; i++)
1577 if (esl_sq_FetchFromMSA(msa, i, &(sq[i])) != eslOK) esl_fatal(msg);
1578
1579 if (p7_trace_FauxFromMSA(msa, matassign, p7_MSA_COORDS, tr) != eslOK) esl_fatal(msg);
1580 if (p7_tracealign_MSA(msa, tr, M, optflags, &msa2) != eslOK) esl_fatal(msg);
1581 if (esl_msa_Compare(msa, msa2) != eslOK) esl_fatal(msg);
1582 esl_msa_Destroy(msa2);
1583 for (i = 0; i < msa->nseq; i++) p7_trace_Destroy(tr[i]);
1584
1585 if (p7_trace_FauxFromMSA(msa, matassign, p7_DEFAULT, tr) != eslOK) esl_fatal(msg);
1586 if (p7_tracealign_Seqs(sq, tr, msa->nseq, M, optflags, NULL, &msa2) != eslOK) esl_fatal(msg);
1587 if (esl_msa_Compare(msa, msa2) != eslOK) esl_fatal(msg);
1588
1589 esl_msa_Destroy(msa2);
1590 for (i = 0; i < msa->nseq; i++) p7_trace_Destroy(tr[i]);
1591 for (i = 0; i < msa->nseq; i++) esl_sq_Destroy(sq[i]);
1592 free(tr);
1593 free(sq);
1594 return;
1595 }
1596
1597 #endif /*p7TRACE_TESTDRIVE*/
1598 /*--------------------- end, unit tests -------------------------*/
1599
1600 /*****************************************************************
1601 * 8. Test driver
1602 *****************************************************************/
1603 #ifdef p7TRACE_TESTDRIVE
1604 /*
1605 gcc -o p7_trace_utest -msse2 -std=gnu99 -g -O2 -I. -L. -I../easel -L../easel -Dp7TRACE_TESTDRIVE p7_trace.c -lhmmer -leasel -lm
1606 ./p7_trace_utest
1607 */
1608 #include <p7_config.h>
1609
1610 #include "easel.h"
1611 #include "esl_getopts.h"
1612 #include "esl_msa.h"
1613 #include "esl_msafile.h"
1614 #include "esl_random.h"
1615
1616 #include "hmmer.h"
1617
1618 static ESL_OPTIONS options[] = {
1619 /* name type default env range toggles reqs incomp help docgroup*/
1620 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1621 { "-s", eslARG_INT, "42", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0 },
1622 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1623 };
1624
1625 static char usage[] = "[-options]";
1626 static char banner[] = "test driver for P7_TRACE";
1627
1628 int
1629 main(int argc, char **argv)
1630 {
1631 char *msg = "p7_trace_utest failed";
1632 ESL_GETOPTS *go = p7_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1633 ESL_RANDOMNESS *r = esl_randomness_CreateFast(esl_opt_GetInteger(go, "-s"));
1634 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
1635 ESL_MSA *msa = NULL;
1636 int alen = 6;
1637 int M = 4;
1638 int *matassign = malloc(sizeof(int) * (alen+1)); /* 1..alen */
1639
1640 /* Create a test MSA/matassign/M triplet */
1641 /* missing data ~ doesn't work here yet; tracealign_* doesn't propagate p7T_X in any way */
1642 if ((msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n#=GC RF .xxxx.\nseq1 AAAAAA\nseq2 -AAA--\nseq3 AA--AA\n//\n", eslMSAFILE_STOCKHOLM)) == NULL) esl_fatal(msg);
1643 if (esl_msa_Digitize(abc, msa,NULL) != eslOK) esl_fatal(msg);
1644
1645 matassign[0] = 0;
1646 matassign[1] = 0;
1647 matassign[2] = 1;
1648 matassign[3] = 1;
1649 matassign[4] = 1;
1650 matassign[5] = 1;
1651 matassign[6] = 0;
1652
1653 utest_faux(msa, matassign, M);
1654
1655 free(matassign);
1656 esl_msa_Destroy(msa);
1657 esl_alphabet_Destroy(abc);
1658 esl_randomness_Destroy(r);
1659 esl_getopts_Destroy(go);
1660 return eslOK;
1661 }
1662 #endif /*p7TRACE_TESTDRIVE*/
1663 /*--------------------- end, test driver ------------------------*/
1664
1665
1666