Debian Codegraph @

src/cm_parsetree.c

raw symbols SCIP
1 /* cm_parsetree.c
2 * cove 1.0: Mon May 17 09:38:14 1993
3 * moved to cove 2.0, Mon Sep 6 13:34:55 1993
4 * cove4: SRE 29 Feb 2000 [Seattle]
5 * infernal: SRE, Fri Jul 28 08:55:47 2000 [StL]
6 *
7 * Unlike a traceback of a normal HMM alignment, which is linear,
8 * the traceback of a CM is a tree structure. Here
9 * we provide support for the traceback data structure.
10 *
11 * Non-BIFURC states have a NULL right branch.
12 *
13 * The pushdown stack structure has a dummy begin node, and the
14 * end is signified by a final NULL ptr.
15 */
16
17 #include <esl_config.h>
18 #include <p7_config.h>
19 #include "config.h"
20
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdlib.h>
24 #include <ctype.h>
25 #include <math.h>
26
27 #include "easel.h"
28 #include "esl_alphabet.h"
29 #include "esl_random.h"
30 #include "esl_sq.h"
31 #include "esl_sqio.h"
32 #include "esl_stack.h"
33 #include "esl_vectorops.h"
34
35 #include "infernal.h"
36
37 static float get_femission_score (CM_t *cm, ESL_DSQ *dsq, int v, int i, int j);
38 static float get_femission_score_trunc(CM_t *cm, ESL_DSQ *dsq, int v, int i, int j, char mode);
39 static float sample_helper(ESL_RANDOMNESS *r, float *pA, int *validA, int n, int *ret_choice);
40
41 /* Function: CreateParsetree()
42 * Incept: SRE 29 Feb 2000 [Seattle] from cove2.0 code.
43 *
44 * Purpose: Creates a parse tree structure.
45 * The first operation on a newly created tree is
46 * generally to add the root:
47 * InsertTraceNode(tr, -1, TRACE_LEFT_CHILD, 0, L-1, 0);
48 *
49 * Return: ptr to the new tree.
50 */
51 Parsetree_t *
52 CreateParsetree(int size)
53 {
54 int status;
55 Parsetree_t *new;
56
57 ESL_ALLOC(new, sizeof(Parsetree_t));
58 new->memblock = 25; /* allocation block size can be optimized here if you want. */
59 new->nalloc = size;
60 ESL_ALLOC(new->emitl, sizeof(int) * new->nalloc);
61 ESL_ALLOC(new->emitr, sizeof(int) * new->nalloc);
62 ESL_ALLOC(new->state, sizeof(int) * new->nalloc);
63 ESL_ALLOC(new->mode, sizeof(char) * new->nalloc);
64 ESL_ALLOC(new->nxtl, sizeof(int) * new->nalloc);
65 ESL_ALLOC(new->nxtr, sizeof(int) * new->nalloc);
66 ESL_ALLOC(new->prv, sizeof(int) * new->nalloc);
67 new->n = 0;
68 new->is_std = TRUE;
69 new->trpenalty = 0.;
70 new->pass_idx = PLI_PASS_STD_ANY;
71 return new;
72 ERROR:
73 cm_Fail("ERROR allocated parsetree.\n");
74 return NULL; /* never reached */
75 }
76
77 /* Function: GrowParsetree()
78 * Incept: SRE 1 March 2000 [Seattle]
79 *
80 * Purpose: Increase the number of available nodes in a parse tree.
81 */
82 void
83 GrowParsetree(Parsetree_t *tr)
84 {
85 int status;
86 void *tmp;
87 tr->nalloc += tr->memblock;
88 ESL_RALLOC(tr->emitl, tmp, sizeof(int) * tr->nalloc);
89 ESL_RALLOC(tr->emitr, tmp, sizeof(int) * tr->nalloc);
90 ESL_RALLOC(tr->state, tmp, sizeof(int) * tr->nalloc);
91 ESL_RALLOC(tr->mode, tmp, sizeof(char) * tr->nalloc);
92 ESL_RALLOC(tr->nxtl, tmp, sizeof(int) * tr->nalloc);
93 ESL_RALLOC(tr->nxtr, tmp, sizeof(int) * tr->nalloc);
94 ESL_RALLOC(tr->prv, tmp, sizeof(int) * tr->nalloc);
95 return;
96
97 ERROR:
98 cm_Fail("ERROR growing parsetree.\n");
99 }
100
101 /* Function: FreeParsetree()
102 * Incept: SRE 1 March 2000 [Seattle]
103 *
104 * Purpose: Destroy a parse tree.
105 */
106 void
107 FreeParsetree(Parsetree_t *tr)
108 {
109 if (tr)
110 {
111 free(tr->emitl);
112 free(tr->emitr);
113 free(tr->state);
114 free(tr->mode);
115 free(tr->nxtl);
116 free(tr->nxtr);
117 free(tr->prv);
118 free(tr);
119 }
120 }
121
122 /* Function: SizeofParsetree()
123 * Incept: EPN, Wed Dec 2 17:26:45 2009
124 *
125 * Purpose: Return the allocated size of a parsetree in Mb.
126 */
127 float
128 SizeofParsetree(Parsetree_t *tr)
129 {
130 float Mb;
131
132 Mb = 0.;
133 Mb += 3 * sizeof(int); /* n, nalloc, memblock */
134 Mb += tr->nalloc * (sizeof(int)) * 6;
135 Mb += tr->nalloc * (sizeof(char)) * 1;
136 Mb /= 1000000.;
137 /* 6 = emitl,emitr,state,nxtl,nxtr,prv */
138 /* 1 = mode */
139 return Mb;
140 }
141
142 /* Function: InsertTraceNodewithMode()
143 * Incept: SRE 1 March 2000 [Seattle]
144 *
145 * Purpose: Insert a new node in a trace tree, attached to node y,
146 * either TRACE_LEFT_CHILD or TRACE_RIGHT_CHILD.
147 *
148 * Before: After:
149 * y y
150 * / \ / \
151 * a b n b
152 * / \
153 * a -
154 * The new node has index tr->n.
155 * GrowTrace() if necessary.
156 * The new node n gets connectivity:
157 * l = a
158 * r = 1 (a dummy state, e.g. nothing)
159 * prv = y
160 * The old node y gets connectivity :
161 * l or r = n
162 * The downstream node a gets a new parent:
163 * if (a != 1) a's prv = n
164 *
165 * Usually we're attaching a node, so a and b are the
166 * terminal dummy state 1, which does not remember its
167 * parents.
168 *
169 * For the special case of initializing the root node, use y==-1
170 * and whichway==TRACE_LEFT_CHILD.
171 *
172 * <mode> is the alignment mode, either TRMODE_J, TRMODE_L, TRMODE_R, or TRMODE_T.
173 *
174 * Returns: index of new node.
175 */
176 int
177 InsertTraceNodewithMode(Parsetree_t *tr, int y, int whichway, int emitl, int emitr, int state, char mode)
178 {
179 int a;
180 int n;
181
182 n = tr->n;
183 /* a==-1 unless we're inserting a node into an existing tree, which is rare */
184 if (y >= 0)
185 a = (whichway == TRACE_LEFT_CHILD ? tr->nxtl[y] : tr->nxtr[y]);
186 else
187 a = -1; /* special case of initializing the root. */
188
189 if (tr->n == tr->nalloc) GrowParsetree(tr);
190 /* information in new node */
191 tr->emitl[n] = emitl;
192 tr->emitr[n] = emitr;
193 tr->state[n] = state;
194 tr->mode[n] = mode;
195 /* connectivity of new node */
196 tr->nxtl[n] = a;
197 tr->nxtr[n] = -1;
198 tr->prv[n] = y;
199 /* connectivity of parent */
200 if (y >= 0) {
201 if (whichway == TRACE_LEFT_CHILD) tr->nxtl[y] = n;
202 else tr->nxtr[y] = n;
203 }
204 /* connectivity of child,
205 if we're inserting instead of just adding */
206 if (a != -1) tr->prv[a] = n;
207 /* bump counter, return index of new node */
208 tr->n++;
209 return n;
210 }
211
212 /* Function: InsertTraceNode()
213 *
214 * Purpose: Standard, non-mode-aware API
215 * Calls InsertTraceNodewithMode()
216 * with default mode value
217 *
218 * Returns: index of new node
219 */
220 int
221 InsertTraceNode(Parsetree_t *tr, int y, int whichway, int emitl, int emitr, int state)
222 {
223 int n;
224
225 n = InsertTraceNodewithMode(tr, y, whichway, emitl, emitr, state, TRMODE_J);
226
227 return n;
228 }
229
230 /* Function: ParsetreeCount()
231 * Date: SRE, Mon Jul 31 19:19:08 2000 [St. Louis]
232 *
233 * Purpose: Count a parsetree into a counts-based CM structure,
234 * in the course of estimating new CM probability parameters.
235 *
236 * Args: cm - CM to collect counts in
237 * tr - the parse tree to collect from.
238 * dsq - digitized sequence that we're counting symbols from
239 * wgt - weight on this sequence (often just 1.0)
240 *
241 * Returns: (void)
242 */
243 void
244 ParsetreeCount(CM_t *cm, Parsetree_t *tr, ESL_DSQ *dsq, float wgt)
245 {
246 int tidx; /* counter through positions in the parsetree */
247 int v,z; /* parent, child state index in CM */
248
249 /* trivial preorder traverse, since we're already numbered that way */
250 for (tidx = 0; tidx < tr->n; tidx++) {
251 v = tr->state[tidx]; /* index of parent state in CM */
252 if (v != cm->M && cm->sttype[v] != E_st && cm->sttype[v] != B_st) {
253
254 /* count transition */
255 if(tidx < (tr->n-1)) {
256 printf("tidx: %d\n", tidx);
257 z = tr->state[tr->nxtl[tidx]]; /* index of child state in CM */
258
259 if (z == cm->M)
260 cm->end[v] += wgt;
261 else if (v == 0 && z - cm->cfirst[v] >= cm->cnum[v])
262 cm->begin[z] += wgt;
263 else
264 cm->t[v][z - cm->cfirst[v]] += wgt;
265 }
266
267 /* count emission */
268 if (cm->sttype[v] == MP_st)
269 PairCount(cm->abc, cm->e[v], dsq[tr->emitl[tidx]], dsq[tr->emitr[tidx]], wgt);
270 else if (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st)
271 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitl[tidx]], wgt);
272 else if (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st)
273 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitr[tidx]], wgt);
274 }
275 }
276 }
277
278 /* Function: ParsetreeCountExceptTruncatedMPs()
279 * Date: EPN, Thu Nov 3 15:16:05 2022
280 *
281 * Purpose: Count a parsetree into a counts-based CM structure,
282 * in the course of estimating new CM probability parameters.
283 * This version of the function is truncation-mode-aware
284 * which affects emissions, but not transitions.
285 * Some emissions are skipped (e.g. ML emissions in TRMODE_R mode)
286 * and MP states not in TRMODE_J are *skipped*.
287 * After the cm->e counts for all sequences are collected,
288 * ParsetreeCountOnlyTruncatedMPs() should be called for each
289 * parsetree. The reason two functions are necessary is that
290 * ParsetreeCountOnlyTruncatedMPs() uses the counts in cm->e
291 * to determine mean posterior estimates using Dirichlet priors.
292 *
293 * Args: cm - CM to collect counts in
294 * tr - the parse tree to collect from.
295 * dsq - digitized sequence that we're counting symbols from
296 * wgt - weight on this sequence (often just 1.0)
297 *
298 * Returns: (void)
299 */
300 void
301 ParsetreeCountExceptTruncatedMPs(CM_t *cm, Parsetree_t *tr, ESL_DSQ *dsq, float wgt)
302 {
303 int tidx; /* counter through positions in the parsetree */
304 int v,z; /* parent, child state index in CM */
305
306 /* trivial preorder traverse, since we're already numbered that way */
307 for (tidx = 0; tidx < tr->n; tidx++) {
308 v = tr->state[tidx]; /* index of parent state in CM */
309 if ((v != cm->M && cm->sttype[v] != E_st && cm->sttype[v] != B_st) &&
310 ((tr->mode[tidx] == TRMODE_J) || (tr->nxtl[tidx] != -1))) {
311 /* when mode is not TRMODE_J some nodes may have nxtl -1 because they don't
312 * attach lower, e.g. BEGL_S state in TRMODE_J */
313
314 /* count transition */
315 if(tidx < (tr->n-1)) {
316 if(tr->nxtl[tidx] == -1) {
317 cm_Fail("ParsetreeCountExceptTruncatedMPs() unexpectedly left child == -1");
318 }
319 z = tr->state[tr->nxtl[tidx]]; /* index of child state in CM */
320
321 if (z == cm->M)
322 cm->end[v] += wgt;
323 else if (v == 0 && z - cm->cfirst[v] >= cm->cnum[v])
324 cm->begin[z] += wgt;
325 else
326 cm->t[v][z - cm->cfirst[v]] += wgt;
327 }
328
329 /* count emission */
330 if(tr->mode[tidx] == TRMODE_J) {
331 if (cm->sttype[v] == MP_st) {
332 PairCount(cm->abc, cm->e[v], dsq[tr->emitl[tidx]], dsq[tr->emitr[tidx]], wgt);
333 }
334 else if (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
335 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitl[tidx]], wgt);
336 }
337 else if (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
338 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitr[tidx]], wgt);
339 }
340 }
341 else if (tr->mode[tidx] == TRMODE_L) {
342 if (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
343 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitl[tidx]], wgt);
344 }
345 /* skip MP, will handle this later in ParsetreeCountOnlyTruncatedMPs() */
346 }
347 else if(tr->mode[tidx] == TRMODE_R) {
348 if (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
349 esl_abc_FCount(cm->abc, cm->e[v], dsq[tr->emitr[tidx]], wgt);
350 }
351 /* skip MP, will handle this later in ParsetreeCountOnlyTruncatedMPs() */
352 }
353 }
354 }
355
356 /* check for a special case: if final two nodes of the parsetree are
357 * identical insert emissions, this means we have a truncated parsetree
358 * that may contribute to an IL/IR self transition that will be problematically
359 * high (BandCalculationEngine() may estimate a very high W for example)
360 * so we perform a hack to increase the transition count out of this insert
361 * state to the first match state of the following node
362 */
363 if((tr->state[(tr->n-2)] == tr->state[(tr->n-1)]) &&
364 (tr->mode[(tr->n-2)] == tr->mode[(tr->n-1)])) {
365 /* final two nodes have same state and truncation mode */
366 v = tr->state[(tr->n-1)];
367 if((cm->sttype[v] == IL_st && (tr->mode[(tr->n-1)] == TRMODE_J || tr->mode[(tr->n-1)] == TRMODE_L)) ||
368 (cm->sttype[v] == IR_st && (tr->mode[(tr->n-1)] == TRMODE_J || tr->mode[(tr->n-1)] == TRMODE_R))) {
369 /* for all inserts, first transition is to itself (cm->cfirst[v])
370 * for all inserts except MATP_IL, second transition is to first reachable state in the next node,
371 * for MATP_IL second transition is to MATP_IR, third is to first reachable state in the next node
372 */
373 cm->t[v][NumReachableInserts(cm->stid[v])] += wgt;
374 }
375 }
376
377 return;
378 }
379
380
381 /* Function: ParsetreeCountOnlyTruncatedMPs()
382 * Date: EPN, Fri Nov 4 12:11:58 2022
383 *
384 * Purpose: Count truncated MP emissions, for which either the left
385 * or right symbol is missing into a counts-based CM structure,
386 * using mean posterior estimates and a Dirichlet prior and
387 * already collected counts in cm->e of full MP emissions (left
388 * and right symbol both present). This function should be
389 * called for each parsetree after ParsetreeCountExceptTruncatedMPs()
390 * has been called for all parsetrees, so that the mean posterior
391 * estimates are based on all complete basepairs.
392 * This function requires dbl_e a double version of cm->e to
393 * be passed in. This should be a copy of the floats in cm->e
394 * *after* ParsetreeCountExceptTruncatedMPs() is called and
395 * *before* this function is called for any parsetrees, as
396 * it is a copy of the counts of all non-truncated MP emissions.
397 *
398 * The counts in cm->e[v] will be updated, but dbl_e[v] will be
399 * unchanged by this function.
400 *
401 * Args: cm - CM to collect counts in
402 * tr - the parse tree to collect from.
403 * dsq - digitized sequence that we're counting symbols from
404 * wgt - weight on this sequence (often just 1.0)
405 *
406 * pri - the Dirichlet prior to use
407 *
408 * Returns: (void)
409 */
410 void
411 ParsetreeCountOnlyTruncatedMPs(CM_t *cm, Parsetree_t *tr, ESL_DSQ *dsq, float wgt, double **dbl_e, const Prior_t *pri)
412 {
413 int tidx; /* counter through positions in the parsetree */
414 int v; /* state index in CM */
415
416 for (tidx = 0; tidx < tr->n; tidx++) {
417 v = tr->state[tidx]; /* index of parent state in CM */
418 if ((v != cm->M) && (cm->sttype[v] == MP_st)) {
419 if (tr->mode[tidx] == TRMODE_L) {
420 PairCountMarginal(cm->abc, dbl_e[v], cm->e[v], dsq[tr->emitl[tidx]], esl_abc_XGetMissing(cm->abc), wgt, pri);
421 }
422 else if (tr->mode[tidx] == TRMODE_R) {
423 PairCountMarginal(cm->abc, dbl_e[v], cm->e[v], esl_abc_XGetMissing(cm->abc), dsq[tr->emitr[tidx]], wgt, pri);
424 }
425 }
426 }
427 return;
428 }
429 /* Function: ParsetreeScore()
430 * Date: SRE, Wed Aug 2 13:54:07 2000 [St. Louis]
431 *
432 * Purpose: Calculate the score of a given parse tree for a sequence,
433 * given a CM that's prepared in log-odds form. Also calculate
434 * the contribution of structure to that score, by summing the
435 * difference in MP emissions and the marginalized left and right
436 * scores. Also calculate the primary sequence score, the sum of
437 * all singlet emissions, plus marginalized base pair emissions.
438 * Also determine the first (ret_spos) and last (ret_epos) consensus
439 * columns occupied in the parsetree.
440 *
441 * Returns: eslOK on success
442 * eslEINCOMPAT on contract violation.
443 */
444 int
445 ParsetreeScore(CM_t *cm, CMEmitMap_t *emap, char *errbuf, Parsetree_t *tr, ESL_DSQ *dsq, int do_null2, float *ret_sc, float *ret_struct_sc, float *ret_primary_sc, int *ret_spos, int *ret_epos)
446 {
447 int status; /* Easel status code */
448 int tidx; /* counter through positions in the parsetree */
449 int v,y; /* parent, child state index in CM */
450 ESL_DSQ symi, symj; /* symbol indices for emissions, 0..cm->abc->Kp-1 */
451 float sc; /* the log-odds score of the parse tree */
452 char mode;
453 float struct_sc; /* contribution of the structure to the score */
454 float primary_sc; /* contribution of primary sequence emissions to the score */
455 float lsc, rsc;
456 int nd;
457 int sd;
458
459 /* contract check */
460 if(dsq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "ParsetreeScore(): dsq == NULL.");
461 if(ret_sc == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "ParsetreeScore(): ret_sc == NULL.");
462 if(emap == NULL && (ret_spos != NULL || ret_epos != NULL)) ESL_FAIL(eslEINCOMPAT, errbuf, "ParsetreeScore(): emap == NULL but ret_spos and ret_epos != NULL.");
463
464 int spos = cm->clen + 1;
465 int epos = 0;
466
467 /* trivial preorder traverse, since we're already numbered that way */
468 sc = struct_sc = primary_sc = 0.;
469 for (tidx = 0; tidx < tr->n; tidx++) {
470 v = tr->state[tidx]; /* index of parent state in CM */
471 mode = tr->mode[tidx];
472 if (v == cm->M) continue; /* special case: v is EL, local alignment end */
473 nd = cm->ndidx[v];
474 if (cm->sttype[v] != E_st && cm->sttype[v] != B_st) { /* no scores in B,E */
475
476 /* add in contribution of transition score */
477 if(tr->nxtl[tidx] == -1) {
478 sc += 0.; /* we've done a truncated end: no transition score contribution */
479 }
480 else { /* not a truncated end */
481 y = tr->state[tr->nxtl[tidx]]; /* index of child state in CM */
482 if(v == 0) {
483 if(! tr->is_std) {
484 sc += tr->trpenalty;
485 }
486 else if(cm->flags & CMH_LOCAL_BEGIN)
487 sc += cm->beginsc[y];
488 else
489 sc += cm->tsc[v][y - cm->cfirst[v]]; /* non-local transition out of ROOT_S */
490 }
491 else if (y == cm->M) {
492 /* CMH_LOCAL_END is presumably set, else this wouldn't happen */
493 if (mode == TRMODE_J) sd = StateDelta(cm->sttype[v]);
494 else if(mode == TRMODE_L) sd = StateLeftDelta(cm->sttype[v]);
495 else if(mode == TRMODE_R) sd = StateRightDelta(cm->sttype[v]);
496 sc += cm->endsc[v] + (cm->el_selfsc * (tr->emitr[tidx] - tr->emitl[tidx] + 1 - sd));
497 }
498 else {
499 /* y - cm->first[v] gives us the offset in the transition vector */
500 sc += cm->tsc[v][y - cm->cfirst[v]];
501 }
502 }
503
504 /* add in contribution of emission score */
505 if (cm->sttype[v] == MP_st) {
506 symi = dsq[tr->emitl[tidx]];
507 symj = dsq[tr->emitr[tidx]];
508 if (mode == TRMODE_J) {
509 if (symi < cm->abc->K && symj < cm->abc->K) {
510 sc += cm->esc[v][(int) (symi*cm->abc->K+symj)];
511 struct_sc += cm->esc[v][(int) (symi*cm->abc->K+symj)];
512 }
513 else {
514 sc += DegeneratePairScore(cm->abc, cm->esc[v], symi, symj);
515 struct_sc += cm->esc[v][(int) (symi*cm->abc->K+symj)];
516 }
517 lsc = cm->lmesc[v][symi];
518 rsc = cm->rmesc[v][symj];
519 struct_sc -= lsc; /* subtract left marginalized score */
520 struct_sc -= rsc; /* subtract right marginalized score */
521 primary_sc += lsc;
522 primary_sc += rsc;
523 }
524 else if (mode == TRMODE_L)
525 sc += cm->lmesc[v][symi];
526 else if (mode == TRMODE_R)
527 sc += cm->rmesc[v][symj];
528 if(emap != NULL) {
529 spos = ESL_MIN(spos, emap->lpos[nd]);
530 epos = ESL_MAX(epos, emap->rpos[nd]);
531 }
532 }
533 else if ( (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) && ModeEmitsLeft(mode)) {
534 symi = dsq[tr->emitl[tidx]];
535 if (symi < cm->abc->K) lsc = cm->esc[v][(int) symi];
536 else lsc = esl_abc_FAvgScore(cm->abc, symi, cm->esc[v]);
537 sc += lsc;
538 primary_sc += lsc;
539 if(emap != NULL && cm->stid[v] == MATL_ML) {
540 spos = ESL_MIN(spos, emap->lpos[nd]);
541 epos = ESL_MAX(epos, emap->lpos[nd]);
542 }
543 }
544 else if ( (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) && ModeEmitsRight(mode)) {
545 symj = dsq[tr->emitr[tidx]];
546 if (symj < cm->abc->K) rsc = cm->esc[v][(int) symj];
547 else rsc = esl_abc_FAvgScore(cm->abc, symj, cm->esc[v]);
548 sc += rsc;
549 primary_sc += rsc;
550 if(emap != NULL && cm->stid[v] == MATR_MR) {
551 spos = ESL_MIN(spos, emap->rpos[nd]);
552 epos = ESL_MAX(epos, emap->rpos[nd]);
553 }
554 }
555 }
556 }
557
558 if(do_null2) {
559 float corr_sc;
560 if((status = ParsetreeScoreCorrectionNull2(cm, errbuf, tr, dsq, 0, cm->null2_omega, &corr_sc)) != eslOK) return status;
561 sc -= corr_sc;
562 primary_sc -= corr_sc;
563 /* don't subtract corr_sc from struct_sc, b/c we would have subtracted it from
564 * both the marginalized and non-marginalized MP scores, thus it cancels out for struct_sc
565 */
566 }
567 if(ret_sc != NULL) *ret_sc = sc;
568 if(ret_struct_sc != NULL) *ret_struct_sc = struct_sc;
569 if(ret_primary_sc != NULL) *ret_primary_sc = primary_sc;
570
571 if(spos == cm->clen+1) spos = -1;
572 if(epos == 0) epos = -1;
573
574 if(ret_spos != NULL) *ret_spos = spos;
575 if(ret_epos != NULL) *ret_epos = epos;
576 return eslOK;
577 }
578
579
580
581
582 /* Function: PrintParsetree()
583 * Date: SRE, Fri Jul 28 12:47:06 2000 [St. Louis]
584 *
585 * Purpose: Debugging: show a tabular representation of a
586 * parsetree structure.
587 *
588 * This just shows information in the
589 * parsetree structure itself. ParsetreeDump()
590 * is more detailed, showing sequence information
591 * aligned to the tree. PrintParsetree() is
592 * called by cmbuild.c to print a master guide
593 * tree, which doesn't have an individual
594 * sequence aligned to it.
595 *
596 * Args: fp - output stream (stdout?)
597 * tr - the tree to show
598 *
599 * Returns: void
600 */
601 void
602 PrintParsetree(FILE *fp, Parsetree_t *tr)
603 {
604 int x;
605
606 fprintf(fp, "%5s %5s %5s %5s %5s %5s %5s %5s\n",
607 " idx ","emitl", "emitr", "state", " nxtl", " nxtr", " prv ", " mode");
608 fprintf(fp, "%5s %5s %5s %5s %5s %5s %5s %5s\n",
609 "-----", "-----", "-----", "-----", "-----","-----", "-----", "-----");
610 for (x = 0; x < tr->n; x++)
611 fprintf(fp, "%5d %5d %5d %5d %5d %5d %5d %5s\n",
612 x, tr->emitl[x], tr->emitr[x], tr->state[x],
613 tr->nxtl[x], tr->nxtr[x], tr->prv[x], MarginalMode(tr->mode[x]));
614 fprintf(fp, "%5s %5s %5s %5s %5s %5s %5s %5s\n",
615 "-----", "-----", "-----", "-----","-----","-----", "-----", "-----");
616
617 fprintf(fp, "n = %d\n", tr->n);
618 fprintf(fp, "nalloc = %d\n", tr->nalloc);
619 fprintf(fp, "block = %d\n", tr->memblock);
620 }
621
622 /* Function: ParsetreeDump()
623 * Date: SRE, Fri Aug 4 10:43:20 2000 [St. Louis]
624 *
625 * Purpose: Generate a detailed picture of a parsetree data structure,
626 * annotated with relevant information from the sequence
627 * and the model.
628 *
629 * Args: fp - FILE to write output to.
630 * tr - parsetree to examine.
631 * cm - model that was aligned to dsq to generate the parsetree
632 * dsq - digitized sequence that was aligned to cm to generate the parsetree
633 *
634 * Returns: (void)
635 */
636 void
637 ParsetreeDump(FILE *fp, Parsetree_t *tr, CM_t *cm, ESL_DSQ *dsq)
638 {
639 int x, sd;
640 char syml, symr;
641 float tsc;
642 float esc;
643 int v,y;
644 char mode;
645
646 /* if we're a truncated alignment first line is special, it shows the truncation penalty only */
647 fprintf(fp, "Parsetree dump\n");
648 fprintf(fp, "------------------\n");
649 fprintf(fp, "is_std = %s\n", tr->is_std ? "TRUE (alignment is not truncated)" : "FALSE (parsetree was found by a truncated DP algorithm)");
650 fprintf(fp, "pass_idx = %d\n", tr->pass_idx);
651 fprintf(fp, "trpenalty = %.3f\n", tr->trpenalty);
652 fprintf(fp, "parsetree:\n\n");
653 fprintf(fp, "%5s %6s %6s %7s %5s %5s %5s %5s %5s %5s\n",
654 " idx ","emitl", "emitr", "state", " mode", " nxtl", " nxtr", " prv ", " tsc ", " esc ");
655 fprintf(fp, "%5s %6s %6s %7s %5s %5s %5s %5s %5s %5s\n",
656 "-----", "------", "------", "-------", "-----","-----", "-----","-----", "-----", "-----");
657
658 for (x = 0; x < tr->n; x++)
659 {
660 v = tr->state[x];
661 mode = tr->mode[x];
662
663 /* Set syml, symr: one char representation of what we emit, or ' '.
664 * Set esc: emission score, or 0.
665 * Only P, L, R states have emissions.
666 */
667 syml = symr = ' ';
668 esc = 0.;
669 if (cm->sttype[v] == MP_st) {
670 if (mode == TRMODE_J || mode == TRMODE_L) syml = cm->abc->sym[dsq[tr->emitl[x]]];
671 if (mode == TRMODE_J || mode == TRMODE_R) symr = cm->abc->sym[dsq[tr->emitr[x]]];
672 if (mode == TRMODE_J) esc = DegeneratePairScore(cm->abc, cm->esc[v], dsq[tr->emitl[x]], dsq[tr->emitr[x]]);
673 else if (mode == TRMODE_L) esc = cm->lmesc[v][dsq[tr->emitl[x]]];
674 else if (mode == TRMODE_R) esc = cm->rmesc[v][dsq[tr->emitr[x]]];
675 } else if ( (cm->sttype[v] == IL_st || cm->sttype[v] == ML_st) && (mode == TRMODE_J || mode == TRMODE_L) ) {
676 syml = cm->abc->sym[dsq[tr->emitl[x]]];
677 esc = esl_abc_FAvgScore(cm->abc, dsq[tr->emitl[x]], cm->esc[v]);
678 } else if ( (cm->sttype[v] == IR_st || cm->sttype[v] == MR_st) && (mode == TRMODE_J || mode == TRMODE_R) ) {
679 symr = cm->abc->sym[dsq[tr->emitr[x]]];
680 esc = esl_abc_FAvgScore(cm->abc, dsq[tr->emitr[x]], cm->esc[v]);
681 }
682
683 /* Set tsc: transition score, or 0.
684 * B, E, and the special EL state (M, local end) have no transitions.
685 */
686 tsc = 0.;
687 if (v != cm->M && cm->sttype[v] != B_st && cm->sttype[v] != E_st && tr->nxtl[x] != -1) {
688 y = tr->state[tr->nxtl[x]];
689 if(v == 0) {
690 if(! tr->is_std) {
691 tsc = tr->trpenalty;
692 }
693 else if(cm->flags & CMH_LOCAL_BEGIN) {
694 tsc = cm->beginsc[y];
695 }
696 else {
697 tsc = cm->tsc[v][y - cm->cfirst[v]]; /* non-local transition out of ROOT_S */
698 }
699 }
700 else if (y == cm->M) { /* CMH_LOCAL_END is presumably set, else this wouldn't happen */
701 if (mode == TRMODE_J) sd = StateDelta(cm->sttype[v]);
702 else if(mode == TRMODE_L) sd = StateLeftDelta(cm->sttype[v]);
703 else if(mode == TRMODE_R) sd = StateRightDelta(cm->sttype[v]);
704 tsc = cm->endsc[v] + (cm->el_selfsc * (tr->emitr[x] - tr->emitl[x] + 1 - sd));
705 }
706 else { /* y - cm->first[v] gives us the offset in the transition vector */
707 tsc = cm->tsc[v][y - cm->cfirst[v]];
708 }
709 }
710
711 /* Print the info line for this state
712 */
713 fprintf(fp, "%5d %5d%c %5d%c %5d%-2s %5s %5d %5d %5d %5.2f %5.2f\n",
714 x, tr->emitl[x], syml, tr->emitr[x], symr, tr->state[x],
715 Statetype(cm->sttype[v]), MarginalMode(tr->mode[x]),
716 tr->nxtl[x], tr->nxtr[x], tr->prv[x], tsc, esc);
717 }
718 fprintf(fp, "%5s %6s %6s %7s %5s %5s %5s %5s %5s %5s\n",
719 "-----", "------", "------", "-------", "-----","-----","-----", "-----","-----", "-----");
720 fflush(fp);
721 }
722
723
724 /* Function: ParsetreeCompare()
725 * Date: SRE, Sat Aug 12 22:05:38 2000 [Titusville]
726 *
727 * Purpose: Compare two parse trees to each other, for debugging
728 * purposes. If they are not exactly alike, return 0.
729 * Else return 1.
730 */
731 int
732 ParsetreeCompare(Parsetree_t *t1, Parsetree_t *t2)
733 {
734 int x;
735
736 if (t1->n != t2->n) return 0;
737 for (x = 0; x < t1->n; x++)
738 {
739 if (t1->emitl[x] != t2->emitl[x]) return 0;
740 if (t1->emitr[x] != t2->emitr[x]) return 0;
741 if (t1->state[x] != t2->state[x]) return 0;
742 if (t1->mode[x] != t2->mode[x]) return 0;
743 if (t1->nxtl[x] != t2->nxtl[x]) return 0;
744 if (t1->nxtr[x] != t2->nxtr[x]) return 0;
745 }
746 return 1;
747 }
748
749
750 /* Function: SummarizeMasterTrace()
751 * Date: SRE, Fri Jul 28 13:42:30 2000 [St. Louis]
752 *
753 * Purpose: Debugging: count the nodes used in a master trace.
754 * Note that it takes advantage of the overloading of
755 * tr->state; in a master trace, this is a node type
756 * (e.g. MATP_nd), not a state index.
757 *
758 * Args: fp - output file (e.g. stdout)
759 * tr - master trace to summarize
760 *
761 * Returns: void
762 */
763 void
764 SummarizeMasterTrace(FILE *fp, Parsetree_t *tr)
765 {
766 int x;
767 int count[NODETYPES];
768
769 for (x = 0; x < NODETYPES; x++) count[x] = 0;
770 for (x = 0; x < tr->n; x++) count[tr->state[x]]++;
771
772 fprintf(fp, "Summary report for the master trace:\n");
773 fprintf(fp, "------------------------------------\n");
774 fprintf(fp, "Total nodes: %d\n", tr->n);
775 fprintf(fp, "Bifurcations: %d\n", count[0]);
776 fprintf(fp, "MATP: %d\n", count[1]);
777 fprintf(fp, "MATL: %d\n", count[2]);
778 fprintf(fp, "MATR: %d\n", count[3]);
779 fprintf(fp, "BEGL: %d\n", count[4]);
780 fprintf(fp, "BEGR: %d\n", count[5]);
781 fprintf(fp, "ROOT: %d\n", count[6]);
782 fprintf(fp, "END: %d\n", count[7]);
783 }
784
785 /* Function: MasterTraceDisplay()
786 * Date: SRE, Mon Aug 7 10:05:16 2000 [St. Louis]
787 *
788 * Purpose: prettified display of a master trace, for debugging
789 * and planning purposes. works by recursively calling
790 * mtd_visit_node().
791 */
792 static void
793 mtd_visit_node(FILE *fp, Parsetree_t *mtr, CM_t *cm, int v, int depth)
794 {
795 int y;
796 /* find next start states in "binary tree" */
797 for (y = v+1; y < mtr->n; y++)
798 if (mtr->state[y] == END_nd || mtr->state[y] == BIF_nd) break;
799 /* visit right */
800 if (mtr->state[y] == BIF_nd)
801 mtd_visit_node(fp, mtr, cm, mtr->nxtr[y], depth+1);
802 /* deal with root */
803 fprintf(fp, "%*s%d: %d[%d]: %d..%d, %d nt\n", depth*6, "", depth, v, cm->nodemap[v], mtr->emitl[v], mtr->emitr[v], mtr->emitr[v] - mtr->emitl[v] +1);
804 /* visit left */
805 if (mtr->state[y] == BIF_nd)
806 mtd_visit_node(fp, mtr, cm, mtr->nxtl[y], depth+1);
807 }
808 void
809 MasterTraceDisplay(FILE *fp, Parsetree_t *mtr, CM_t *cm)
810 {
811 mtd_visit_node(fp, mtr, cm, 0, 0);
812 }
813
814
815 /* Function : Parsetrees2Alignment()
816 *
817 * Purpose: Creates a MSA from a set of parsetrees and a CM. If
818 * (do_matchonly) the MSA will only include consensus
819 * columns. If (do_full), all consensus columns are
820 * included, regardless of whether they have any residues
821 * in them or not. One reason to do this is so we can
822 * always merge any alignments that were created using the
823 * same CM, because they'll have the same number of
824 * consensus (nongap-RF) columns.
825 *
826 * Args: cm - the CM
827 * errbuf - for error messages
828 * abc - alphabet to use to create the return MSA
829 * sq - sequences, must be digitized (we check for it)
830 * wgt - weights for seqs (NULL for none)
831 * tr - array of tracebacks
832 * postcode - posterior code string (NULL for none)
833 * nseq - number of sequences
834 * insertfp - file to print per-seq insert information to (NULL if none)
835 * elfp - file to print per-seq EL insert information to (NULL if none)
836 * do_full - TRUE to always include all match columns in alignment
837 * do_matchonly - TRUE to ONLY include match columns
838 * allow_trunc - TRUE to add missing (~) chars to truncated parsetrees, FALSE not to
839 * ret_msa - RETURN: MSA, alloc'ed/created here
840 *
841 * Returns: eslOK on success, eslEMEM on memory error, eslEINVALID on contract violation.
842 * Also ret_msa is filled with a new MSA.
843 *
844 */
845 int
846 Parsetrees2Alignment(CM_t *cm, char *errbuf, const ESL_ALPHABET *abc, ESL_SQ **sq, double *wgt,
847 Parsetree_t **tr, char **postcode, int nseq,
848 FILE *insertfp, FILE *elfp, int do_full, int do_matchonly, int allow_trunc,
849 ESL_MSA **ret_msa)
850 {
851 int status; /* easel status flag */
852 CMEmitMap_t *emap = NULL; /* ptr to cm->emap, for convenience */
853 ESL_MSA *msa = NULL; /* multiple sequence alignment */
854 int i; /* counter over traces */
855 int v, nd; /* state, node indices */
856 char mode; /* a marginal alignment mode */
857 int cpos; /* counter over consensus positions (0)1..clen */
858 int *matuse= NULL; /* TRUE if we need a cpos in mult alignment */
859 int *iluse = NULL; /* # of IL insertions after a cpos for 1 trace */
860 int *eluse = NULL; /* # of EL insertions after a cpos for 1 trace */
861 int *iruse = NULL; /* # of IR insertions after a cpos for 1 trace */
862 int *maxil = NULL; /* max # of IL insertions after a cpos */
863 int *maxel = NULL; /* max # of EL insertions after a cpos */
864 int *maxir = NULL; /* max # of IR insertions after a cpos */
865 int *matmap= NULL; /* apos corresponding to a cpos */
866 int *ilmap = NULL; /* first apos for an IL following a cpos */
867 int *elmap = NULL; /* first apos for an EL following a cpos */
868 int *irmap = NULL; /* first apos for an IR following a cpos */
869 int alen; /* length of msa in columns */
870 int apos; /* position in an aligned sequence in MSA */
871 int rpos; /* position in an unaligned sequence in dsq */
872 int *ifirst = NULL; /* first uapos (unaligned position) for an insert following a cpos in cur seq */
873 int *elfirst = NULL; /* first uapos (unaligned position) for an EL following a cpos in cur seq */
874 int tpos; /* position in a parsetree */
875 int el_len; /* length of an EL insertion in residues */
876 int prvnd; /* keeps track of previous node for EL */
877 int nins; /* insert counter used for splitting inserts */
878 int do_post; /* TRUE if postcode != NULL (we should write at least 1 sequence's posteriors) */
879 int do_cur_post; /* TRUE if we're writing posteriors for the current sequence inside a loop */
880 char *tmp_aseq = NULL; /* will hold aligned sequence for current sequence */
881 char *tmp_apc = NULL; /* will hold aligned postcode characters for current sequence */
882 /* s_cposA and e_cposA are only alloc'ed and filled if insertfp || elfp != NULL, b/c they're only purpose is to be written to those files */
883 int *s_cposA = NULL; /* [0..nseq-1] the first consensus position filled by a nongap for seq i */
884 int *e_cposA = NULL; /* [0..nseq-1] the final consensus position filled by a nongap for seq i */
885 int s_cpos; /* first consensus position filled by a nongap for current seq */
886 int e_cpos; /* final consensus position filled by a nongap for current seq */
887 int aulen; /* length of author string for msa */
888
889 /* Contract check. We allow the caller to specify the alphabet they want the
890 * resulting MSA in, but it has to make sense (see next few lines). */
891 if(cm->abc->type == eslRNA) {
892 if(abc->type != eslRNA && abc->type != eslDNA)
893 ESL_XFAIL(eslEINVAL, errbuf, "Parsetrees2Alignment(): cm alphabet is RNA, but requested output alphabet is neither DNA nor RNA.");
894 }
895 else if(cm->abc->K != abc->K) {
896 ESL_XFAIL(eslEINVAL, errbuf, "Parsetrees2Alignment(): cm alphabet size is %d, but requested output alphabet size is %d.", cm->abc->K, abc->K);
897 }
898 /* cm->cmcons must exist */
899 if(cm->cmcons == NULL) ESL_XFAIL(eslEINVAL, errbuf, "Parsetrees2Alignment(): cm-cmcons is NULL");
900
901 do_post = (postcode == NULL) ? FALSE : TRUE;
902 emap = cm->emap; /* for convenience */
903
904 ESL_ALLOC(matuse, sizeof(int)*(emap->clen+1));
905 ESL_ALLOC(iluse, sizeof(int)*(emap->clen+1));
906 ESL_ALLOC(eluse, sizeof(int)*(emap->clen+1));
907 ESL_ALLOC(iruse, sizeof(int)*(emap->clen+1));
908 ESL_ALLOC(maxil, sizeof(int)*(emap->clen+1));
909 ESL_ALLOC(maxel, sizeof(int)*(emap->clen+1));
910 ESL_ALLOC(maxir, sizeof(int)*(emap->clen+1));
911 ESL_ALLOC(matmap, sizeof(int)*(emap->clen+1));
912 ESL_ALLOC(ilmap, sizeof(int)*(emap->clen+1));
913 ESL_ALLOC(elmap, sizeof(int)*(emap->clen+1));
914 ESL_ALLOC(irmap, sizeof(int)*(emap->clen+1));
915 ESL_ALLOC(ifirst, sizeof(int)*(emap->clen+1));
916 ESL_ALLOC(elfirst, sizeof(int)*(emap->clen+1));
917
918 if(insertfp != NULL || elfp != NULL) {
919 ESL_ALLOC(s_cposA, sizeof(int)*nseq);
920 ESL_ALLOC(e_cposA, sizeof(int)*nseq);
921 esl_vec_ISet(s_cposA, nseq, 0); /* all nseq values will be overwritten, actually this initialization is unnec */
922 esl_vec_ISet(e_cposA, nseq, 0); /* all nseq values will be overwritten, actually this initialization is unnec */
923 }
924
925 for (cpos = 0; cpos <= emap->clen; cpos++)
926 {
927 if(!do_full || cpos == 0)
928 matuse[cpos] = 0;
929 else
930 matuse[cpos] = 1;
931 maxil[cpos] = maxel[cpos] = maxir[cpos] = 0;
932 ilmap[cpos] = elmap[cpos] = irmap[cpos] = 0;
933 }
934
935 /* Look at all the traces; find maximum length of
936 * insert needed at each of the clen+1 possible gap
937 * points. (There are three types of insert, IL/EL/IR.)
938 * Also find whether we don't need some of the match
939 * (consensus) columns.
940 */
941 for (i = 0; i < nseq; i++) {
942 for (cpos = 0; cpos <= emap->clen; cpos++)
943 iluse[cpos] = eluse[cpos] = iruse[cpos] = 0;
944
945 for (tpos = 0; tpos < tr[i]->n; tpos++) {
946 v = tr[i]->state[tpos];
947 mode = tr[i]->mode[tpos];
948 if (cm->sttype[v] == EL_st) nd = prvnd;
949 else nd = cm->ndidx[v];
950
951 switch (cm->sttype[v]) {
952 case MP_st:
953 if(ModeEmitsLeft(mode)) matuse[emap->lpos[nd]] = 1;
954 if(ModeEmitsRight(mode)) matuse[emap->rpos[nd]] = 1;
955 break;
956 case ML_st:
957 if(ModeEmitsLeft(mode)) matuse[emap->lpos[nd]] = 1;
958 break;
959 case MR_st:
960 if(ModeEmitsRight(mode)) matuse[emap->rpos[nd]] = 1;
961 break;
962 case IL_st:
963 if(ModeEmitsLeft(mode)) iluse[emap->lpos[nd]]++;
964 break;
965 case IR_st:
966 /* remember, convention on rpos is that IR precedes this
967 * cpos. Make it after the previous cpos, hence the -1.
968 */
969 if(ModeEmitsRight(mode)) iruse[emap->rpos[nd]-1]++;
970 break;
971 case EL_st:
972 /* mode must be TRMODE_J */
973 el_len = tr[i]->emitr[tpos] - tr[i]->emitl[tpos] + 1;
974 eluse[emap->epos[nd]] = el_len;
975 /* not possible to have >1 EL in same place; could assert this */
976 break;
977 }
978
979 prvnd = nd;
980 } /* end looking at trace i */
981
982 for (cpos = 0; cpos <= emap->clen; cpos++)
983 {
984 if (iluse[cpos] > maxil[cpos]) maxil[cpos] = iluse[cpos];
985 if (eluse[cpos] > maxel[cpos]) maxel[cpos] = eluse[cpos];
986 if (iruse[cpos] > maxir[cpos]) maxir[cpos] = iruse[cpos];
987 }
988 } /* end calculating lengths used by all traces */
989
990 /* Now we can calculate the total length of the multiple alignment,
991 * alen; and the maps ilmap, elmap, and irmap that turn a cpos into
992 * an apos in the multiple alignment: e.g. for an IL and EL that
993 * follows consensus position cpos, put it at or after apos =
994 * ilmap[cpos] in aseq[][]. IR's are filled in backwards (3'->5')
995 * and rightflushed.
996 *
997 * EPN, Mon Oct 22 09:40:15 2012
998 * Post-1.1rc1: always put EL insertions *before* (5' of) ILs or
999 * IRs. Previous to this modification ELs were 5' or IRs, but 3' of
1000 * ILs. Since ELs only occur at the end of stem loops, IRs nearly
1001 * always accounted for inserts at the same position as an EL
1002 * (because ILs directly before an END_E state are detached to
1003 * resolve an ambiguity in the CM grammar). This means the
1004 * post-1.1rc1 change only affected models with MATP immediately
1005 * followed by an END_E, where the MATP_IR is is detached and the
1006 * MATP_IL can emit after the same position as an EL. For those
1007 * cases, previously ELs were 3' or the ILs, but now ELs are 5' of
1008 * the ILs. This makes it possible to merge alignments to the same
1009 * model without parsing their secondary structure because we can
1010 * assume ELs are always 5' of inserts.
1011 */
1012 alen = 0;
1013 for (cpos = 0; cpos <= emap->clen; cpos++) {
1014 if (matuse[cpos]) {
1015 matmap[cpos] = alen;
1016 alen++;
1017 }
1018 else matmap[cpos] = -1;
1019
1020 elmap[cpos] = alen;
1021 if(! do_matchonly) alen += maxel[cpos];
1022 ilmap[cpos] = alen;
1023 if(! do_matchonly) alen += maxil[cpos];
1024 if(! do_matchonly) alen += maxir[cpos];
1025 irmap[cpos] = alen-1;
1026 /* note: if do_matchonly, no inserts are printed, ilmap, elmap, irmap are irrelevant */
1027 }
1028
1029 /* We're getting closer.
1030 * Now we know the size of the MSA, allocate it.
1031 */
1032 if ((msa = esl_msa_Create(nseq, -1)) == NULL) { status = eslEMEM; goto ERROR; }
1033 msa->nseq = nseq;
1034 msa->alen = alen;
1035 msa->abc = NULL;
1036 if(do_post) {
1037 ESL_ALLOC(msa->pp, sizeof(char *) * msa->nseq);
1038 }
1039
1040 /* we reuse aseq, copying it to the msa after it's completed for each seq */
1041 ESL_ALLOC(tmp_aseq, sizeof(char) * (msa->alen+1));
1042 if(do_post) { /* these will be reused for each sequence (the aligned postcode arrays are all the same length) */
1043 ESL_ALLOC(tmp_apc, sizeof(char) * (msa->alen+1));
1044 }
1045
1046 for (i = 0; i < nseq; i++) {
1047 s_cpos = emap->clen+1; /* an ESL_MIN with any cpos <= clen will replace this */
1048 e_cpos = 0; /* an ESL_MAX with any cpos > 0 will replace this */
1049
1050 /* Contract check */
1051 if(sq[i]->dsq == NULL) ESL_XFAIL(eslEINVAL, errbuf, "Error in Parsetrees2Alignment(), sq %d is not digitized.\n", i);
1052 do_cur_post = FALSE;
1053 if(do_post) {
1054 do_cur_post = (postcode[i] != NULL) ? TRUE : FALSE;
1055 }
1056
1057 /* Initialize the aseq with all pads '.' (in insert cols)
1058 * and deletes '-' (in match cols).
1059 */
1060 for (apos = 0; apos < alen; apos++) tmp_aseq[apos] = '.';
1061 if(do_cur_post) {
1062 for (apos = 0; apos < alen; apos++) {
1063 tmp_apc[apos] = '.';
1064 }
1065 }
1066
1067 for (cpos = 0; cpos <= emap->clen; cpos++) {
1068 if (matmap[cpos] != -1) {
1069 tmp_aseq[matmap[cpos]] = '-';
1070 }
1071 }
1072 if(do_cur_post) {
1073 for (cpos = 0; cpos <= emap->clen; cpos++) {
1074 if (matmap[cpos] != -1) {
1075 tmp_apc[matmap[cpos]] = '.';
1076 }
1077 }
1078 }
1079 tmp_aseq[alen] = '\0';
1080 if(do_cur_post) tmp_apc[alen] = '\0';
1081
1082 /* Traverse this guy's trace, and place all his
1083 * emitted residues and posteriors.
1084 */
1085 for (cpos = 0; cpos <= emap->clen; cpos++) {
1086 iluse[cpos] = iruse[cpos] = eluse[cpos] = 0;
1087 ifirst[cpos] = elfirst[cpos] = -1;
1088 }
1089
1090 for (tpos = 0; tpos < tr[i]->n; tpos++) {
1091 v = tr[i]->state[tpos];
1092 mode = tr[i]->mode[tpos];
1093 if (cm->sttype[v] == EL_st) nd = prvnd;
1094 else nd = cm->ndidx[v];
1095
1096 switch (cm->sttype[v]) {
1097 case MP_st:
1098 if(ModeEmitsLeft(mode)) {
1099 cpos = emap->lpos[nd];
1100 apos = matmap[cpos];
1101 rpos = tr[i]->emitl[tpos];
1102 tmp_aseq[apos] = abc->sym[sq[i]->dsq[rpos]];
1103 if(do_cur_post) {
1104 tmp_apc[apos] = postcode[i][rpos-1];
1105 }
1106 s_cpos = ESL_MIN(s_cpos, cpos);
1107 e_cpos = ESL_MAX(e_cpos, cpos);
1108 }
1109
1110 if(ModeEmitsRight(mode)) {
1111 cpos = emap->rpos[nd];
1112 apos = matmap[cpos];
1113 rpos = tr[i]->emitr[tpos];
1114 tmp_aseq[apos] = abc->sym[sq[i]->dsq[rpos]];
1115 if(do_cur_post) {
1116 tmp_apc[apos] = postcode[i][rpos-1];
1117 }
1118 s_cpos = ESL_MIN(s_cpos, cpos);
1119 e_cpos = ESL_MAX(e_cpos, cpos);
1120 }
1121 break;
1122
1123 case ML_st:
1124 if(ModeEmitsLeft(mode)) {
1125 cpos = emap->lpos[nd];
1126 apos = matmap[cpos];
1127 rpos = tr[i]->emitl[tpos];
1128 tmp_aseq[apos] = abc->sym[sq[i]->dsq[rpos]];
1129 if(do_cur_post) {
1130 tmp_apc[apos] = postcode[i][rpos-1];
1131 }
1132 s_cpos = ESL_MIN(s_cpos, cpos);
1133 e_cpos = ESL_MAX(e_cpos, cpos);
1134 }
1135 break;
1136
1137 case MR_st:
1138 if(ModeEmitsRight(mode)) {
1139 cpos = emap->rpos[nd];
1140 apos = matmap[cpos];
1141 rpos = tr[i]->emitr[tpos];
1142 tmp_aseq[apos] = abc->sym[sq[i]->dsq[rpos]];
1143 if(do_cur_post) {
1144 tmp_apc[apos] = postcode[i][rpos-1];
1145 }
1146 s_cpos = ESL_MIN(s_cpos, cpos);
1147 e_cpos = ESL_MAX(e_cpos, cpos);
1148 }
1149 break;
1150
1151 case IL_st:
1152 if(ModeEmitsLeft(mode)) {
1153 cpos = emap->lpos[nd];
1154 apos = ilmap[cpos] + iluse[cpos];
1155 rpos = tr[i]->emitl[tpos];
1156 if(iluse[cpos] == 0) ifirst[cpos] = rpos; /* only update ifirst if this is the first insert for this IL */
1157 iluse[cpos]++;
1158 if(do_matchonly) break; /* we don't break until this point in case we're writing to insertfp, in which case we need ifirst[] and iluse[] */
1159 tmp_aseq[apos] = tolower((int) abc->sym[sq[i]->dsq[rpos]]);
1160 if(do_cur_post) {
1161 tmp_apc[apos] = postcode[i][rpos-1];
1162 }
1163 }
1164 break;
1165
1166 case EL_st:
1167 /* we can assert eluse[cpos] always == 0 when we enter,
1168 * because we can only have one EL insertion event per
1169 * cpos. If we ever decide to regularize (split) insertions,
1170 * though, we'll want to calculate eluse in the rpos loop.
1171 */
1172 cpos = emap->epos[nd];
1173 apos = elmap[cpos];
1174 eluse[cpos] = tr[i]->emitr[tpos] - tr[i]->emitl[tpos] + 1;
1175 elfirst[cpos] = tr[i]->emitl[tpos];
1176 if(do_matchonly) break; /* we don't break until this point in case we're writing to elfp, in which case we need elfirst[] and eluse[] */
1177 for (rpos = tr[i]->emitl[tpos]; rpos <= tr[i]->emitr[tpos]; rpos++)
1178 {
1179 tmp_aseq[apos] = tolower((int) abc->sym[sq[i]->dsq[rpos]]);
1180 if(do_cur_post) {
1181 tmp_apc[apos] = postcode[i][rpos-1];
1182 }
1183 apos++;
1184 }
1185 break;
1186
1187 case IR_st:
1188 if(ModeEmitsRight(mode)) {
1189 cpos = emap->rpos[nd]-1; /* -1 converts to "following this one" */
1190 apos = irmap[cpos] - iruse[cpos]; /* writing backwards, 3'->5' */
1191 rpos = tr[i]->emitr[tpos];
1192 ifirst[cpos] = rpos; /* by overwriting each time we will end up with min rpos used by this IR */
1193 iruse[cpos]++;
1194 if(do_matchonly) break; /* we don't break until this point in case we're writing to elfp, in which case we need ifirst[] and iruse[] */
1195 tmp_aseq[apos] = tolower((int) abc->sym[sq[i]->dsq[rpos]]);
1196 if(do_cur_post) {
1197 tmp_apc[apos] = postcode[i][rpos-1];
1198 }
1199 }
1200 break;
1201
1202 case D_st:
1203 if ((cm->stid[v] == MATP_D || cm->stid[v] == MATL_D) && ModeEmitsLeft(mode)) {
1204 cpos = emap->lpos[nd];
1205 if (matuse[cpos]) tmp_aseq[matmap[cpos]] = '-';
1206 }
1207 if ((cm->stid[v] == MATP_D || cm->stid[v] == MATR_D) && ModeEmitsRight(mode)) {
1208 cpos = emap->rpos[nd];
1209 if (matuse[cpos]) tmp_aseq[matmap[cpos]] = '-';
1210 }
1211 break;
1212
1213 } /* end of the switch statement */
1214
1215 prvnd = nd;
1216 /* we only set s_cposA[i] and e_cposA[i] if we'll output them to an insertfp or elfp */
1217 if(insertfp != NULL || elfp != NULL) {
1218 s_cposA[i] = (s_cpos == (emap->clen+1)) ? -1 : s_cpos;
1219 e_cposA[i] = (e_cpos == 0) ? -1 : e_cpos;
1220 }
1221 } /* end traversal over trace i. */
1222
1223 /* copy tmp_aseq to the msa */
1224 if((status = esl_strdup(tmp_aseq, msa->alen, &(msa->aseq[i]))) != eslOK) goto ERROR;
1225
1226 /* add tmp_apc posterior probabilities to msa, if nec */
1227 if(do_cur_post) {
1228 if((status = esl_strdup(tmp_apc, msa->alen, &(msa->pp[i]))) != eslOK) goto ERROR;
1229 }
1230 else if (do_post) { msa->pp[i] = NULL; }
1231
1232 /* rejustify inserts and posteriors (if nec) */
1233 if(! do_matchonly) {
1234 /* IL/EL Insertions are currently flush-left and IR insertions are currently flush-right.
1235 * This is pre-1.0 Infernal behavior. If(cm->align_opts & CM_ALIGN_FLUSHINSERTS) we leave them all alone,
1236 * otherwise we regularize (split) the internal inserts, we flush the 5' inserts right and the 3'
1237 * inserts left (note: pre 1.0 behavior does the opposite, flushes 5' left (assuming they're ROOT_ILs)
1238 * and flushes 3' right (assuming they're ROOT_IRs).
1239 *
1240 * We have to be careful about EL's. We don't want to group IL/IR's and EL's together and then split them
1241 * because we need to annotate IL/IR's as '.'s in the consensus structure and EL's as '~'. So we split
1242 * each group separately.
1243 * post-1.1rc1 release, we now always but EL insertions *before* (5' of) ILs or IRs. This is a change
1244 * relative to 1.0->1.1rc1, in which ILs would come 3' of ELs (although this would only very rarely
1245 * occur in the case of a MATP followed by an END (that's the only case where an IL and EL can emit
1246 * after the same cpos)).
1247 */
1248 if(! (cm->align_opts & CM_ALIGN_FLUSHINSERTS)) /* default behavior, split insert in half */
1249 {
1250 /* Deal with inserts before first consensus position, ELs, then ILs, then IRs
1251 * (new convention post-1.1rc1 see note above, used to be ILs then ELs then IRs)
1252 */
1253
1254 /* EL's are flush left, we want flush right (I think these are impossible, but just in case...) */
1255 rightjustify(abc, msa->aseq[i], maxel[0]);
1256 if(do_cur_post) rightjustify(abc, msa->pp[i], maxel[0]);
1257
1258 /* IL's are flush left, we want flush right */
1259 rightjustify(abc, msa->aseq[i]+maxel[0], maxil[0]);
1260 if(do_cur_post) rightjustify(abc, msa->pp[i]+maxel[0], maxil[0]);
1261
1262 /* IR's are flush right, we want flush right, do nothing */
1263
1264 /* split all internal insertions */
1265 for (cpos = 1; cpos < emap->clen; cpos++)
1266 {
1267 if(maxel[cpos] > 1) /* we're flush LEFT, want to split */
1268 {
1269 apos = matmap[cpos]+1;
1270 for (nins = 0; islower((int) (msa->aseq[i][apos])); apos++)
1271 nins++;
1272 nins /= 2; /* split the insertion in half */
1273 rightjustify(abc, msa->aseq[i]+matmap[cpos]+1+nins, maxel[cpos]-nins);
1274 if(do_cur_post) rightjustify(abc, msa->pp[i]+matmap[cpos]+1+nins, maxel[cpos]-nins);
1275 }
1276
1277 if(maxil[cpos] > 1) /* we're flush LEFT, want to split */
1278 {
1279 apos = matmap[cpos]+1 + maxel[cpos];
1280 for (nins = 0; islower((int) (msa->aseq[i][apos])); apos++)
1281 nins++;
1282 nins /= 2; /* split the insertion in half */
1283 rightjustify(abc, msa->aseq[i]+matmap[cpos]+1+maxel[cpos]+nins, maxil[cpos]-nins);
1284 if(do_cur_post) rightjustify(abc, msa->pp[i]+matmap[cpos]+1+maxel[cpos]+nins, maxil[cpos]-nins);
1285 }
1286
1287 if(maxir[cpos] > 1) /* we're flush RIGHT, want to split */
1288 {
1289 apos = matmap[cpos+1]-1;
1290 for (nins = 0; islower((int) (msa->aseq[i][apos])); apos--)
1291 nins++;
1292 nins ++; nins /= 2; /* split the insertion in half (++ makes it same behavior as IL/EL */
1293 leftjustify(abc, msa->aseq[i]+matmap[cpos]+1 + maxel[cpos] + maxil[cpos], maxir[cpos]-nins);
1294 if(do_cur_post) leftjustify(abc, msa->pp[i]+matmap[cpos]+1 + maxel[cpos] + maxil[cpos], maxir[cpos]-nins);
1295 }
1296 }
1297 /* Deal with inserts after final consensus position, IL's then EL's, then IR's
1298 * EL's are flush left, we want flush left, do nothing
1299 * IL's are flush left, we want flush left, do nothing
1300 * IR's are flush right, we want flush left */
1301 leftjustify(abc, msa->aseq[i]+matmap[emap->clen]+1 + maxel[emap->clen] + maxil[emap->clen], maxir[emap->clen]);
1302 if(do_cur_post) leftjustify(abc, msa->pp[i]+matmap[emap->clen]+1 + maxel[emap->clen] + maxil[emap->clen], maxir[emap->clen]);
1303 }
1304 }
1305
1306 /* if allow_trunc and the parsetree is truncated, add ~ before and/or after final residue */
1307 if(allow_trunc && (! tr[i]->is_std)) {
1308 if(cm_pli_PassEnforcesFirstRes(tr[i]->pass_idx)) {
1309 /* all alignment positions prior to first residue will be ~ */
1310 for(apos = 0; apos < alen; apos++) {
1311 if(isalpha(msa->aseq[i][apos])) break;
1312 msa->aseq[i][apos] = esl_abc_CGetMissing(abc);
1313 }
1314 }
1315 if(cm_pli_PassEnforcesFinalRes(tr[i]->pass_idx)) {
1316 /* all alignment positions after final residue will be ~ */
1317 for(apos = msa->alen-1; apos >= 0; apos--) {
1318 if(isalpha(msa->aseq[i][apos])) break;
1319 msa->aseq[i][apos] = esl_abc_CGetMissing(abc);
1320 }
1321 }
1322 }
1323
1324 /* output insert and/or EL info to the insertfp and elfp output files, if nec */
1325 if(insertfp != NULL || elfp != NULL) {
1326 if(insertfp != NULL) { fprintf(insertfp, "%s %" PRId64 " %d %d", sq[i]->name, sq[i]->n, s_cposA[i], e_cposA[i]); }
1327 if(elfp != NULL) { fprintf(elfp, "%s %" PRId64 " %d %d", sq[i]->name, sq[i]->n, s_cposA[i], e_cposA[i]); }
1328 for (cpos = 0; cpos <= emap->clen; cpos++)
1329 {
1330 if((insertfp != NULL) && ((iluse[cpos] + iruse[cpos]) > 0)) {
1331 fprintf(insertfp, " %d %d %d", cpos, ifirst[cpos], (iluse[cpos] + iruse[cpos])); /* note cpos+1 puts cpos from 1..clen, ifirst[] is already 1..sq->n */
1332 /* Note: only 1 of iluse[cpos] or iruse[cpos] should be != 0 */
1333 }
1334 if((elfp != NULL) && (eluse[cpos] > 0)) {
1335 fprintf(elfp, " %d %d %d", cpos, elfirst[cpos], eluse[cpos]); /* note cpos+1 puts cpos from 1..clen, ifirst[] is already 1..sq->n */
1336 }
1337 }
1338 if(insertfp != NULL) { fprintf(insertfp, "\n"); }
1339 if(elfp != NULL) { fprintf(elfp, "\n"); }
1340 }
1341 } /* end loop over all parsetrees */
1342
1343 /* Gee, wasn't that easy?
1344 * Add the rest of the ("optional") information to the MSA.
1345 */
1346
1347 /* "author" info */
1348 aulen = strlen(INFERNAL_VERSION)+10; /* 10 is length of "Infernal " + 1 for terminating null char */
1349 ESL_ALLOC(msa->au, sizeof(char) * aulen);
1350 snprintf(msa->au, aulen, "Infernal %s", INFERNAL_VERSION);
1351
1352 /* per-seq info */
1353 for (i = 0; i < nseq; i++) {
1354 esl_msa_SetSeqName(msa, i, sq[i]->name, -1);
1355 if (sq[i]->acc[0] != '\0') esl_msa_SetSeqAccession (msa, i, sq[i]->acc, -1);
1356 if (sq[i]->desc[0] != '\0') esl_msa_SetSeqDescription(msa, i, sq[i]->desc, -1);
1357 if (msa->sqlen != NULL) msa->sqlen[i] = sq[i]->n;
1358 if (wgt == NULL) msa->wgt[i] = 1.0;
1359 else msa->wgt[i] = wgt[i];
1360 /* TODO: individual SS annotations */
1361 }
1362
1363 /* Construct the secondary structure consensus line, msa->ss_cons:
1364 * IL, IR are annotated as .
1365 * EL is annotated as ~
1366 * and match columns use the structure code.
1367 * Also the primary sequence consensus/reference coordinate system line,
1368 * msa->rf.
1369 */
1370 ESL_ALLOC(msa->ss_cons, (sizeof(char) * (alen+1)));
1371 ESL_ALLOC(msa->rf, (sizeof(char) * (alen+1)));
1372 for (cpos = 0; cpos <= emap->clen; cpos++)
1373 {
1374 if (matuse[cpos])
1375 { /* CMConsensus is off-by-one right now, 0..clen-1 relative to cpos's 1..clen */
1376
1377 /* bug i1, xref STL7 p.12. Before annotating something as a base pair,
1378 * make sure the paired column is also present.
1379 */
1380 if (cm->cmcons->ct[cpos-1] != -1 && matuse[cm->cmcons->ct[cpos-1]+1] == 0) {
1381 msa->ss_cons[matmap[cpos]] = '.';
1382 msa->rf[matmap[cpos]] = (cm->flags & CMH_RF) ? cm->rf[cpos] : cm->cmcons->cseq[cpos-1];
1383 } else {
1384 msa->ss_cons[matmap[cpos]] = cm->cmcons->cstr[cpos-1];
1385 msa->rf[matmap[cpos]] = (cm->flags & CMH_RF) ? cm->rf[cpos] : cm->cmcons->cseq[cpos-1];
1386 }
1387 }
1388 if ((maxil[cpos] > 0) && (! do_matchonly))
1389 for (apos = ilmap[cpos]; apos < ilmap[cpos] + maxil[cpos]; apos++)
1390 {
1391 msa->ss_cons[apos] = '.';
1392 msa->rf[apos] = '.';
1393 }
1394 if ((maxel[cpos] > 0) && (! do_matchonly))
1395 for (apos = elmap[cpos]; apos < elmap[cpos] + maxel[cpos]; apos++)
1396 {
1397 msa->ss_cons[apos] = '~';
1398 msa->rf[apos] = '~';
1399 }
1400 if ((maxir[cpos] > 0) && (! do_matchonly)) /* remember to write backwards */
1401 for (apos = irmap[cpos]; apos > irmap[cpos] - maxir[cpos]; apos--)
1402 {
1403 msa->ss_cons[apos] = '.';
1404 msa->rf[apos] = '.';
1405 }
1406 }
1407 msa->ss_cons[alen] = '\0';
1408 msa->rf[alen] = '\0';
1409 if (wgt != NULL) msa->flags |= eslMSA_HASWGTS;
1410
1411 if(tmp_aseq != NULL) free(tmp_aseq);
1412 if(tmp_apc != NULL) free(tmp_apc);
1413 if(s_cposA != NULL) free(s_cposA);
1414 if(e_cposA != NULL) free(e_cposA);
1415 free(matuse);
1416 free(iluse);
1417 free(eluse);
1418 free(iruse);
1419 free(maxil);
1420 free(maxel);
1421 free(maxir);
1422 free(matmap);
1423 free(ilmap);
1424 free(elmap);
1425 free(irmap);
1426 free(ifirst);
1427 free(elfirst);
1428 *ret_msa = msa;
1429 return eslOK;
1430
1431 ERROR:
1432 if(tmp_apc != NULL) free(tmp_apc);
1433 if(matuse!= NULL) free(matuse);
1434 if(iluse != NULL) free(iluse);
1435 if(eluse != NULL) free(eluse);
1436 if(iruse != NULL) free(iruse);
1437 if(maxil != NULL) free(maxil);
1438 if(maxel != NULL) free(maxel);
1439 if(maxir != NULL) free(maxir);
1440 if(matmap!= NULL) free(matmap);
1441 if(ilmap != NULL) free(ilmap);
1442 if(elmap != NULL) free(elmap);
1443 if(irmap != NULL) free(irmap);
1444 if(msa != NULL) esl_msa_Destroy(msa);
1445 return status;
1446 }
1447
1448 /* Function: ParsetreeScore_Global2Local()
1449 * Date: EPN, Wed May 23 09:57:38 2007
1450 *
1451 * Purpose: Given a parsetree of dsq that corresponds to a globally
1452 * configured CM, return the highest scoring local parsetree
1453 * of dsq or a subsequence of dsq (due to local begins)
1454 * that is consistent with it. The hope is that this
1455 * score will *be close* to the optimal local parse of dsq so we
1456 * can calculate CP9 filter thresholds without the need to
1457 * search for the optimal local parse.
1458 *
1459 * All residues 1..L must exist in the local parse emitted
1460 * from the same states they were emitted in the global
1461 * parse unless (1) the local parse contains a local begin into
1462 * state v at parstree node t, where tr->emitl[t] > 1 and/or
1463 * tr->emitr[t] < L, (2) residues were emitted from an EL
1464 * state because it was higher scoring than the subtree
1465 * of the global parse.
1466 *
1467 */
1468 float
1469 ParsetreeScore_Global2Local(CM_t *cm, Parsetree_t *tr, ESL_DSQ *dsq, int print_flag)
1470 {
1471 int status;
1472 int tidx; /* counter through positions in the parsetree */
1473 int v,y; /* parent, child state index in CM */
1474 ESL_DSQ symi, symj; /* symbol indices for emissions, 0..Kp-1 */
1475 char mode;
1476 int tp; /* trace index offset, for v's with > tidx (IL or IR)*/
1477 float *tr_esc; /* [0..tr->n-1] score of emissions from each trace node */
1478 float *tr_tsc; /* [0..tr->n-1] score of transitions from each trace node */
1479 int *v2n_map; /* [0..cm->M-1], the trace node each state v corresponds to
1480 * -1 if none */
1481 int *v2n_ct; /* [0..cm->M-1], # of trace nodes state v corresponds to */
1482 float *lsc; /* [0..tr->n-1], the score of the best local parse *
1483 * rooted at v = v2n_map[tidx] for trace node tidx *
1484 * -1 if none */
1485 float max_local_sc; /* the best local parse score consistent with tr */
1486 float below_me_sc; /* score of tr-consistent best local parse under v */
1487 float tmp_endsc; /* score of jumping out of v to EL */
1488 /* Contract check, CM must be LOCALLY configured, (could config to global, but
1489 * we assume we'll be calling this function serially for many parses and don't
1490 * want to need to switch CM back and forth from local/global) */
1491 if((!(cm->flags & CMH_LOCAL_BEGIN)) || (!(cm->flags & CMH_LOCAL_END)))
1492 cm_Fail("ERROR in ParsetreeScore_Global2Local() CM is not in local mode.\n");
1493 if(dsq == NULL)
1494 cm_Fail("ERROR in ParsetreeScore_Global2Local(), dsq is NULL.\n");
1495
1496 /* Allocate and initialize */
1497 ESL_ALLOC(v2n_map, sizeof(int) * cm->M);
1498 ESL_ALLOC(v2n_ct, sizeof(int) * cm->M);
1499 ESL_ALLOC(lsc, sizeof(float) * tr->n);
1500 ESL_ALLOC(tr_esc, sizeof(float) * tr->n);
1501 ESL_ALLOC(tr_tsc, sizeof(float) * tr->n);
1502 esl_vec_ISet(v2n_map, cm->M, -1);
1503 esl_vec_ISet(v2n_ct, cm->M, 0);
1504 esl_vec_FSet(lsc, tr->n, 0.);
1505 esl_vec_FSet(tr_tsc, tr->n, 0.);
1506 esl_vec_FSet(tr_esc, tr->n, 0.);
1507
1508 /* Determine the score that each trace node contributes to the overall parsetree score */
1509
1510 for (tidx = 0; tidx < tr->n; tidx++)
1511 {
1512 v = tr->state[tidx]; /* index of parent state in CM */
1513 v2n_map[v] = tidx;
1514 v2n_ct[v]++; /* insert states could be visited > once */
1515 mode = tr->mode[tidx];
1516 if (v == cm->M)
1517 cm_Fail("ERROR in ParsetreeScore_Global2Local(), EL in parse, but it should be global!\n");
1518 if (cm->sttype[v] != E_st && cm->sttype[v] != B_st) /* no scores in B,E */
1519 {
1520 y = tr->state[tr->nxtl[tidx]]; /* index of child state in CM */
1521
1522 if (y == cm->M)
1523 cm_Fail("ERROR in ParsetreeScore_Global2Local(), EL in parse, but it should be global!\n");
1524 if (v == 0 && y > cm->cnum[0])
1525 cm_Fail("ERROR in ParsetreeScore_Global2Local(), we did a local begin in the parse, but it should be global!\n");
1526 /* for v == 0, we don't care that transition score has changed from global CM that
1527 * was used to generate the parsetree, because the transition from root is not
1528 * considered when we look for best local parse below. */
1529
1530 /* y - cm->first[v] gives us the offset in the transition vector */
1531 tr_tsc[tidx] = cm->tsc[v][y - cm->cfirst[v]];
1532
1533 if (cm->sttype[v] == MP_st)
1534 {
1535 symi = dsq[tr->emitl[tidx]];
1536 symj = dsq[tr->emitr[tidx]];
1537 if (mode == TRMODE_J)
1538 {
1539 if (symi < cm->abc->K && symj < cm->abc->K)
1540 tr_esc[tidx] = cm->esc[v][(int) (symi*cm->abc->K+symj)];
1541 else
1542 tr_esc[tidx] = DegeneratePairScore(cm->abc, cm->esc[v], symi, symj);
1543 }
1544 else if (mode == TRMODE_L)
1545 tr_esc[tidx] = cm->lmesc[v][symi];
1546 else if (mode == TRMODE_R)
1547 tr_esc[tidx] = cm->rmesc[v][symj];
1548 }
1549 else if ( (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) && (mode == TRMODE_J || mode == TRMODE_L) )
1550 {
1551 symi = dsq[tr->emitl[tidx]];
1552 if (symi < cm->abc->K) tr_esc[tidx] = cm->esc[v][(int) symi];
1553 else tr_esc[tidx] = esl_abc_FAvgScore(cm->abc, symi, cm->esc[v]);
1554 }
1555 else if ( (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) && (mode == TRMODE_J || mode == TRMODE_L) )
1556 {
1557 symj = dsq[tr->emitr[tidx]];
1558 if (symj < cm->abc->K) tr_esc[tidx] = cm->esc[v][(int) symj];
1559 else tr_esc[tidx] = esl_abc_FAvgScore(cm->abc, symj, cm->esc[v]);
1560 }
1561 }
1562 }
1563
1564 /* Now traverse CM from inside-out, for each v in the parse,
1565 * keep track of the best local CM score of the parse rooted
1566 * at v, with the possibility of local ends. Keep track
1567 * of maximum score considering all possible local begins */
1568 max_local_sc = IMPOSSIBLE;
1569 for(v = cm->M-1; v > 0; v--)
1570 {
1571 for(tp = 0; tp < v2n_ct[v]; tp++)
1572 {
1573 tidx = v2n_map[v] - tp;
1574 if(print_flag)
1575 printf("loop start tidx: %d esc: %f tsc: %f\n", tidx, tr_esc[tidx], tr_tsc[tidx]);
1576
1577 if(cm->sttype[v] == B_st)
1578 {
1579 below_me_sc = lsc[tr->nxtl[tidx]] + lsc[tr->nxtr[tidx]];
1580 if(print_flag)
1581 {
1582 printf("B state L %d: %f R %d: %f\n", tr->nxtl[tidx], lsc[tr->nxtl[tidx]], tr->nxtr[tidx], lsc[tr->nxtr[tidx]]);
1583 }
1584 }
1585 else if(cm->sttype[v] == E_st)
1586 below_me_sc = 0.;
1587 else
1588 {
1589 below_me_sc = lsc[tr->nxtl[tidx]];
1590 if(print_flag) printf("non B: below_me_sc %d: %f\n", tr->nxtl[tidx], lsc[tr->nxtl[tidx]]);
1591 }
1592 /* Check if we could've jumped to an EL instead of traversing the
1593 * subparse rooted here at v, would it have been worth it? */
1594 tmp_endsc = cm->endsc[v] + /* score of transition to EL */
1595 cm->el_selfsc * /* score of emitting 1 residue */
1596 ((tr->emitr[tidx] - StateRightDelta(cm->sttype[v])) -
1597 (tr->emitl[tidx] + StateLeftDelta(cm->sttype[v])) + 1); /* number of residues EL must emit */
1598 if(below_me_sc < (tmp_endsc - tr_tsc[tidx])) /* careful to consider sc of transition out of v */
1599 {
1600 below_me_sc = tmp_endsc - tr_tsc[tidx]; /* we'll add tr_tsc[idx] back in next */
1601 if(print_flag)
1602 {
1603 printf("\nTOOK LOCAL END!\n");
1604 printf("tmp_endsc: %f cm->endsc: %f + %d emits\n", tmp_endsc, cm->endsc[v], ((tr->emitr[tidx] - StateRightDelta(cm->sttype[v])) - (tr->emitl[tidx] + StateLeftDelta(cm->sttype[v])) + 1));
1605 }
1606 }
1607 lsc[tidx] = tr_esc[tidx] + tr_tsc[tidx] + below_me_sc; /* note we add in tsc even if local end taken */
1608
1609 if(print_flag)
1610 {
1611 printf("tidx: %d\nv: %d\nlsc[tidx]: %f\nbegin_sc: %f\nmax_local_sc: %f\ntmp_endsc: %f\n\n", tidx, v, lsc[tidx], cm->beginsc[v], max_local_sc, tmp_endsc);
1612 printf("tr_esc[tidx]: %f\ntr_tsc[tidx]: %f\nbelow_me_sc: %f\n", tr_esc[tidx], tr_tsc[tidx], below_me_sc);
1613 }
1614 /* Could we have jumped into this state from ROOT_S? Would it have
1615 * been worth it (based on what I've seen so far) */
1616 if(print_flag)
1617 printf("cur max_local_sc: %f\n\n", max_local_sc);
1618 if(max_local_sc < (cm->beginsc[v] + lsc[tidx]))
1619 {
1620 max_local_sc = cm->beginsc[v] + lsc[tidx];
1621 if(print_flag)
1622 printf("\nNEW max_local_sc: %f\n\n", max_local_sc);
1623 }
1624 }
1625 }
1626 free(v2n_map);
1627 free(v2n_ct);
1628 free(lsc);
1629 free(tr_esc);
1630 free(tr_tsc);
1631 /*printf("in ParsetreeScore_Global2Local() returning sc: %f\n", max_local_sc);*/
1632 return max_local_sc;
1633
1634 ERROR:
1635 cm_Fail("ERROR in ParsetreeScore_Global2Local()\n");
1636 return -1.;
1637 }
1638
1639 /* Function: Parsetree2CP9trace()
1640 * Incept: EPN, Wed May 30 09:33:01 2007
1641 *
1642 * Purpose: Convert a CM parsetree into it's implicit CP9 trace.
1643 * Returns: eslOK on success
1644 *
1645 * Args:
1646 * CM_t *cm - the CM, with valid cp9
1647 * Parsetree_t *cm_tr - valid parsetree to convert
1648 * cp9trace_s *ret_cp9_tr - the CP9 trace to return, alloc'ed here
1649 */
1650 int
1651 Parsetree2CP9trace(CM_t *cm, Parsetree_t *tr, CP9trace_t **ret_cp9_tr)
1652 {
1653 /* Check the contract */
1654 if(cm->cp9 == NULL || (!(cm->flags & CMH_CP9)))
1655 cm_Fail("In Parsetree2CP9trace, cm->cp9 is not valid.\n");
1656 if(cm->cp9map == NULL)
1657 cm_Fail("In Parsetree2CP9trace, cm->cp9map is NULL.\n");
1658
1659 int status; /* Easel status */
1660 CP9trace_t *cp9_tr; /* the CP9 trace we're creating */
1661 int **ks_ct = NULL; /* [0..2][0..cp9->M] number of times each state was used
1662 * 1st D: 0 = MATCH, 1 = INSERT, 2 = DELETE */
1663 int tidx; /* counter over parsetree nodes */
1664 int v; /* CM state index */
1665 int k, ks; /* HMM nodes and state indices */
1666 int i; /* generic counter */
1667 int cp9_tr_size; /* number of nodes we'll need for cp9_tr */
1668 int lmost_k; /* left most HMM node visited in parse (often 1) */
1669 int rmost_k; /* right most HMM node visited in parse (often M) */
1670 int ip;
1671 int ins_ct = 0; /* total number of inserts */
1672 CP9_t *cp9 = NULL;
1673
1674 cp9 = cm->cp9;
1675
1676 lmost_k = cp9->M + 1;
1677 rmost_k = 0;
1678
1679 ESL_ALLOC(ks_ct, sizeof(int *) * 3);
1680 for(ks = 0; ks < 3; ks++)
1681 {
1682 ESL_ALLOC(ks_ct[ks], sizeof(int) * (cp9->M+1));
1683 esl_vec_ISet(ks_ct[ks], cp9->M+1, 0);
1684 }
1685
1686 /* Traverse parsetree, keeping track of implied HMM states used by each HMM node. */
1687 v = tr->state[0];
1688 if(v != 0) cm_Fail("ERROR in Parsetree2CP9Trace(), first Parsetree node not root.\n");
1689 /* we leave ks_ct[HMMMATCH][0] as 0 for convenience later, we know it was used. */
1690
1691 for (tidx = 1; tidx < tr->n; tidx++)
1692 {
1693 v = tr->state[tidx]; /* index of parent state in CM */
1694 for(i = 0; i < 2; i++) /* each CM state maps to 0, 1 or 2 HMM states */
1695 {
1696 k = cm->cp9map->cs2hn[v][i];
1697 ks = cm->cp9map->cs2hs[v][i];
1698 if(k == -1) continue; /* when HMM EL's are implemented, we'll have to have a special
1699 * case for them, but for now we visit deletes in between. */
1700 ks_ct[ks][k]++;
1701 if(ks == HMMINSERT) ins_ct++;
1702 }
1703 }
1704 /* Determine the first (leftmost) node used and last (rightmost) node used,
1705 * anything else was skipped by a smith-waterman local begin or end. */
1706 lmost_k = 1;
1707 rmost_k = cp9->M;
1708 if(cp9->flags & CPLAN9_LOCAL_BEGIN)
1709 {
1710 while((ks_ct[HMMMATCH][lmost_k] + ks_ct[HMMINSERT][lmost_k] + ks_ct[HMMDELETE][lmost_k]) == 0)
1711 lmost_k++;
1712 }
1713 if(cp9->flags & CPLAN9_LOCAL_END)
1714 {
1715 while((ks_ct[HMMMATCH][rmost_k] + ks_ct[HMMINSERT][rmost_k] + ks_ct[HMMDELETE][rmost_k]) == 0)
1716 rmost_k--;
1717 }
1718 /* Now build the CP9 trace */
1719 cp9_tr_size = (rmost_k - lmost_k + 1) + ins_ct + 2; /* number of match/deletes we'll visit plus
1720 * number of inserts + begin/end */
1721 CP9AllocTrace(cp9_tr_size, &cp9_tr); /* allow room for B & E */
1722 /* start at node 0 with the begin */
1723 cp9_tr->statetype[0] = CSTB;
1724 cp9_tr->nodeidx[0] = 0;
1725 cp9_tr->pos[0] = 0;
1726 tidx = 1;
1727 i = 1;
1728 /* are there inserts from node 0? */
1729 for(ip = 0; ip < ks_ct[HMMINSERT][0]; ip++)
1730 {
1731 cp9_tr->statetype[tidx] = CSTI;
1732 cp9_tr->nodeidx[tidx] = 0;
1733 cp9_tr->pos[tidx] = i++;
1734 tidx++;
1735 }
1736 /* now go through nodes 1..M */
1737 for(k = lmost_k; k <= rmost_k; k++)
1738 {
1739 if(ks_ct[HMMMATCH][k])
1740 {
1741 cp9_tr->statetype[tidx] = CSTM;
1742 cp9_tr->nodeidx[tidx] = k;
1743 cp9_tr->pos[tidx] = i++;
1744 tidx++;
1745 }
1746 else if(ks_ct[HMMDELETE][k])
1747 {
1748 cp9_tr->statetype[tidx] = CSTD;
1749 cp9_tr->nodeidx[tidx] = k;
1750 cp9_tr->pos[tidx] = 0;
1751 tidx++;
1752 }
1753 else /* skipped due to local end, treat as delete for now */
1754 {
1755 cp9_tr->statetype[tidx] = CSTD;
1756 cp9_tr->nodeidx[tidx] = k;
1757 cp9_tr->pos[tidx] = 0;
1758 tidx++;
1759 }
1760 for(ip = 0; ip < ks_ct[HMMINSERT][k]; ip++)
1761 {
1762 cp9_tr->statetype[tidx] = CSTI;
1763 cp9_tr->nodeidx[tidx] = k;
1764 cp9_tr->pos[tidx] = i++;
1765 tidx++;
1766 }
1767 }
1768 /* all traces end with E state */
1769 cp9_tr->statetype[tidx] = CSTE;
1770 cp9_tr->nodeidx[tidx] = 0;
1771 cp9_tr->pos[tidx] = 0;
1772 tidx++;
1773 cp9_tr->tlen = tidx;
1774
1775 *ret_cp9_tr = cp9_tr;
1776
1777 for(ks = 0; ks < 3; ks++)
1778 if(ks_ct[ks] != NULL) free(ks_ct[ks]);
1779 if(ks_ct != NULL) free(ks_ct);
1780 return eslOK;
1781
1782 ERROR:
1783 for(ks = 0; ks < 3; ks++)
1784 if(ks_ct[ks] != NULL) free(ks_ct[ks]);
1785 if(ks_ct != NULL) free(ks_ct);
1786 return eslFAIL;
1787 }
1788
1789 /* Function: rightjustify()
1790 *
1791 * Purpose: Given a gap-containing string of length n,
1792 * pull all the non-gap characters as far as
1793 * possible to the right, leaving gaps on the
1794 * left side. Used to rearrange the positions
1795 * of insertions in CM generated alignments.
1796 */
1797 void
1798 rightjustify(const ESL_ALPHABET *abc, char *s, int n)
1799 {
1800 int npos;
1801 int opos;
1802
1803 npos = n-1;
1804 opos = n-1;
1805 while (opos >= 0) {
1806 if (esl_abc_CIsGap(abc, s[opos]))
1807 opos--;
1808 else
1809 s[npos--]=s[opos--];
1810 }
1811 while (npos >= 0)
1812 s[npos--] = '.';
1813 }
1814
1815 /* Function: leftjustify()
1816 *
1817 * Purpose: Given a gap-containing string of length n,
1818 * pull all the non-gap characters as far as
1819 * possible to the left, leaving gaps on the
1820 * right side. Used to rearrange the positions
1821 * of insertions in CM generated alignments.
1822 */
1823 void
1824 leftjustify(const ESL_ALPHABET *abc, char *s, int n)
1825 {
1826 int npos;
1827 int opos;
1828
1829 npos = 0;
1830 opos = 0;
1831 while (opos < n) {
1832 if (esl_abc_CIsGap(abc, s[opos]))
1833 opos++;
1834 else
1835 s[npos++]=s[opos++];
1836 }
1837 while (npos < n)
1838 s[npos++] = '.';
1839 }
1840
1841
1842
1843 /* Function: EmitParsetree()
1844 * Incept: SRE, Mon Oct 13 22:35:46 2003 [Rams whupping Falcons, Monday Night Football]
1845 * Easel'ed: EPN, Fri Aug 3 08:15:12 2007
1846 *
1847 * Purpose: Sample a parsetree and sequence from the joint distribution
1848 * Prob(sequence, parsetree | CM).
1849 *
1850 * Be careful screwing with the logic in here. You've got
1851 * two tree traversals going simultaneously: a traversal of
1852 * the CM, and a traversal of the growing parsetree. It
1853 * wasn't obvious how to get it all to work in step
1854 * together. Remember, one of your constraints is that the
1855 * parsetree is numbered in preorder traversal - so you
1856 * must push and defer the right child of a bifurcation,
1857 * rather than attaching it immediately. Another
1858 * constraint is that you must set emitr in the parsetree
1859 * even for nonemitting states, so you must always push a right
1860 * marker along with a parsetree node index tpos, for deferred
1861 * assignment of tr->emitr[tpos]. And since you don't
1862 * know tpos until you've attached the state, you have to
1863 * push the right marker after your deferred attachment of v - not
1864 * when v was produced - which is why you have a double
1865 * deferral of the right emission or marker: you produce
1866 * a V b, push that info onto the pda, pop it back off,
1867 * attach V, store a, push b back onto the pda (now storing
1868 * the trace position tpos for V), then produce from V.
1869 * Yeesh.
1870 *
1871 * Added capacity for local begins/ends. [EPN, Wed May 2 05:59:19 2007]
1872 *
1873 * Args: cm - covariance model to generate from
1874 * errbuf - for error messages
1875 * r - source of randomness
1876 * name - name for the sequence (ESL_SQ name field is mandatory)
1877 * do_digital - TRUE to digitize sq before returning, FALSE not to
1878 * ret_tr - RETURN: generated parse tree. Pass NULL if unwanted.
1879 * ret_sq - RETURN: generated sequence
1880 * ret_N - RETURN: length of generated sequence.
1881 *
1882 * Returns: eslOK on success; eslEMEM on memory error;
1883 * eslEINCONCEIVABLE if something inconceivable happens.
1884 * tr, sq are allocated here; whichever ones the caller
1885 * requests (with non-NULL ret_ pointers) the caller is responsible
1886 * for free'ing:
1887 * FreeParsetree(tr); esl_sq_Destroy(sq);
1888 */
1889 int
1890 EmitParsetree(CM_t *cm, char *errbuf, ESL_RANDOMNESS *r, char *name, int do_digital, Parsetree_t **ret_tr, ESL_SQ **ret_sq, int *ret_N)
1891 {
1892 Parsetree_t *tr = NULL; /* parse tree under construction */
1893 ESL_STACK *pda = NULL; /* pushdown automaton for traversing parse tree */
1894 ESL_STACK *gsq = NULL; /* growing sequence under construction */
1895 ESL_SQ *sq = NULL; /* finished sequence, initially normal alphabet form */
1896 char *seq; /* alphabetic sequence to build sq with */
1897 int N; /* current emitted sequence length */
1898 int tparent; /* parent node index, last attached to parse tree */
1899 int tpos; /* child node index, just attached to parse tree */
1900 int v; /* index of current state */
1901 int y,z; /* indices for next state(s) */
1902 int type; /* PDA_RESIDUE or PDA_STATE */
1903 int lchar, rchar; /* index of emitted chars in cm->abc->sym[], or -1 for nothing */
1904 int whichway; /* how to attach: TRACE_LEFT_CHILD or TRACE_RIGHT_CHILD */
1905 int x; /* tmp variable for sampling MP emission */
1906 int lpos; /* tmp variable for inserting EL trace node */
1907 float *tmp_tvec = NULL; /* tmp transition vector to choose from,
1908 * for dealing with local end transitions */
1909 int status;
1910
1911 /* Contract check */
1912 if(cm->flags & CMH_LOCAL_END && (fabs(sreEXP2(cm->el_selfsc) - 1.0) < 0.01))
1913 ESL_FAIL(eslEINVAL, errbuf, "EL self transition probability %f is too high, would emit long (too long) EL insertions.", sreEXP2(cm->el_selfsc));
1914 if(cm->abc == NULL)
1915 ESL_FAIL(eslEINVAL, errbuf, "CM does not have a valid alphabet.");
1916 if(ret_sq != NULL && name == NULL)
1917 ESL_FAIL(eslEINVAL, errbuf, "EmitParsetree requires a sequence name for the sequence it's creating.");
1918
1919 tr = CreateParsetree(100);
1920 if ((pda = esl_stack_ICreate()) == NULL) {status = eslEMEM; goto ERROR; }
1921 if ((gsq = esl_stack_CCreate()) == NULL) {status = eslEMEM; goto ERROR; }
1922 N = 0;
1923 ESL_ALLOC(tmp_tvec, sizeof(float) * (MAXCONNECT+1)); /* enough room for max possible transitions, plus
1924 * a local end transition */
1925 /* Init by pushing root state's info onto pda
1926 */
1927 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit an rchar */
1928 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit an lchar either */
1929 if((status = esl_stack_IPush(pda, TRACE_LEFT_CHILD)) != eslOK) goto ERROR;
1930 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* attach this state to parsetree node -1 (init) */
1931 if((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR; /* it's the root state, v=0 */
1932 if((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
1933
1934 /* Iterate until the pda is empty...
1935 */
1936 while (esl_stack_IPop(pda, &type) != eslEOD)
1937 {
1938 if (type == PDA_RESIDUE)
1939 {
1940 esl_stack_IPop(pda, &tpos);
1941 esl_stack_IPop(pda, &rchar);
1942
1943 if (rchar != -1) {
1944 if((status = esl_stack_CPush(gsq, cm->abc->sym[rchar])) != eslOK) goto ERROR;
1945 N++;
1946 }
1947 tr->emitr[tpos] = N;
1948 }
1949 else if (type == PDA_STATE)
1950 {
1951 esl_stack_IPop(pda, &v);
1952 esl_stack_IPop(pda, &tparent);
1953 esl_stack_IPop(pda, &whichway);
1954 esl_stack_IPop(pda, &lchar);
1955 esl_stack_IPop(pda, &rchar);
1956
1957 /* Attach state v to the parent parsetree node that generated it,
1958 * which is tparent. Set emitl now; emitr gets deferred and set later.
1959 * The insertion function returns tpos, the index of the node in the
1960 * parse tree that we just created.
1961 */
1962 tpos = InsertTraceNode(tr, tparent, whichway, N+1, -1, v);
1963
1964 /* If v emitted left: add that symbol to the growing seq.
1965 */
1966 if (lchar != -1)
1967 {
1968 if((status = esl_stack_CPush(gsq, cm->abc->sym[lchar])) != eslOK) goto ERROR;
1969 N++;
1970 }
1971
1972 /* Push right emission info for state v onto the pda, now
1973 * that we know tpos for where v is in the parsetree. We have
1974 * to do this even if rchar is -1, to be sure that we will set the emitr
1975 * bound properly even for nonemitting states in the parsetree.
1976 */
1977 if((status = esl_stack_IPush(pda, rchar)) != eslOK) goto ERROR;
1978 if((status = esl_stack_IPush(pda, tpos)) != eslOK) goto ERROR;
1979 if((status = esl_stack_IPush(pda, PDA_RESIDUE)) != eslOK) goto ERROR;
1980
1981 /* Decide what state we're going to next.
1982 * B is special case of a bifurcation to two S states.
1983 */
1984 if (cm->sttype[v] == B_st)
1985 {
1986 y = cm->cfirst[v]; /* left child */
1987 z = cm->cnum[v]; /* right child */
1988
1989 /* Push the right start state's info
1990 */
1991 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit right */
1992 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit left */
1993 if((status = esl_stack_IPush(pda, TRACE_RIGHT_CHILD)) != eslOK) goto ERROR; /* attach as right child of the B */
1994 if((status = esl_stack_IPush(pda, tpos)) != eslOK) goto ERROR; /* attach it to B, which is tpos in parsetree*/
1995 if((status = esl_stack_IPush(pda, z)) != eslOK) goto ERROR; /* state z */
1996 if((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
1997
1998 /* Push the left start state's info
1999 */
2000 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit right */
2001 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* doesn't emit left */
2002 if((status = esl_stack_IPush(pda, TRACE_LEFT_CHILD)) != eslOK) goto ERROR; /* attach as left child of the B */
2003 if((status = esl_stack_IPush(pda, tpos)) != eslOK) goto ERROR; /* attach it to B, which is tpos in parsetree*/
2004 if((status = esl_stack_IPush(pda, y)) != eslOK) goto ERROR; /* state z */
2005 if((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
2006 }
2007 else
2008 {
2009 if(v == 0 && cm->flags & CMH_LOCAL_BEGIN) { /* ROOT_S with local begins, special */
2010 if(cm->flags & CM_EMIT_NO_LOCAL_BEGINS) { /* even though local begins are on, we don't allow them during emission */
2011 if(cm->root_trans == NULL) ESL_FAIL(eslEINCONCEIVABLE, errbuf, "EmitParsetree(), cm->flags CM_EMIT_NO_LOCAL_BEGINS and CM_EMIT_GLOBAL flags raised, but cm->root_trans is NULL.");
2012 y = cm->cfirst[v] + esl_rnd_FChoose(r, cm->root_trans, cm->cnum[0]); /* choose next state, y, from 0's children using initial transitions (those from global model, read from CM file) */
2013 }
2014 else {
2015 y = esl_rnd_FChoose(r, cm->begin, cm->M); /* choose next state, y */
2016 }
2017 }
2018 else if(cm->flags & CMH_LOCAL_END) /* special case, we could transit to EL, if CM_EMIT_NO_LOCAL_ENDS flag is down */
2019 {
2020 if(cm->flags & CM_EMIT_NO_LOCAL_ENDS) { /* even though local ends are on, we dont allow them during emission */
2021 /* create temporary vector for choosing transition */
2022 esl_vec_FSet(tmp_tvec, (MAXCONNECT+1), 0.);
2023 esl_vec_FCopy(cm->t[v], cm->cnum[v], tmp_tvec);
2024 esl_vec_FNorm(tmp_tvec, cm->cnum[v]);
2025 y = cm->cfirst[v] + esl_rnd_FChoose(r, tmp_tvec, cm->cnum[v]); /* choose next state, y, but don't include a local end as a possibility */
2026 }
2027 else { /* we may choose a child of v, or a local end */
2028 esl_vec_FSet(tmp_tvec, (MAXCONNECT+1), 0.);
2029 esl_vec_FCopy(cm->t[v], cm->cnum[v], tmp_tvec);
2030 tmp_tvec[cm->cnum[v]] = cm->end[v];
2031 y = esl_rnd_FChoose(r, tmp_tvec, (cm->cnum[v]+1)); /* choose next state, y's offset */
2032 if(y == cm->cnum[v]) y = cm->M; /* local end */
2033 else y += cm->cfirst[v];
2034 }
2035 }
2036 else
2037 y = cm->cfirst[v] + esl_rnd_FChoose(r, cm->t[v], cm->cnum[v]); /* choose next state, y */
2038
2039 switch (cm->sttype[y]) {
2040 case MP_st:
2041 x = esl_rnd_FChoose(r, cm->e[y], cm->abc->K*cm->abc->K);
2042 lchar = x / cm->abc->K;
2043 rchar = x % cm->abc->K;
2044 break;
2045 case ML_st:
2046 case IL_st:
2047 lchar = esl_rnd_FChoose(r, cm->e[y], cm->abc->K);
2048 rchar = -1;
2049 break;
2050 case MR_st:
2051 case IR_st:
2052 lchar = -1;
2053 rchar = esl_rnd_FChoose(r, cm->e[y], cm->abc->K);
2054 break;
2055 case EL_st: /* EL emits on transition, here we don't emit */
2056 lchar = -1;
2057 rchar = -1;
2058 break;
2059 default:
2060 lchar = -1;
2061 rchar = -1;
2062 }
2063 if (cm->sttype[y] == E_st)
2064 {
2065 /*InsertTraceNode(tr, tpos, TRACE_LEFT_CHILD, -1, -1, y);*/
2066 InsertTraceNode(tr, tpos, TRACE_LEFT_CHILD, N+1, N, y);
2067 }
2068 else if(cm->sttype[y] == EL_st) /* y == cm->M */
2069 {
2070 lpos = N+1; /* remember lpos, we need it after we emit from EL */
2071 /* Now choose number of residues emitted from EL, could be 0.
2072 * We do this here b/c convention for EL is to have a single trace node,
2073 * even if multiple residues are emitted. */
2074 esl_vec_FSet(tmp_tvec, (MAXCONNECT+1), 0.);
2075 tmp_tvec[0] = sreEXP2(cm->el_selfsc); /* EL self probability */
2076 tmp_tvec[1] = 1. - tmp_tvec[0]; /* probability of going to implicit END */
2077 y = esl_rnd_FChoose(r, tmp_tvec, 2); /* choose next state, either EL or implicit END */
2078 while(y == 0) /* we've self-transitioned, emit 1 res from NULL distro */
2079 {
2080 lchar = esl_rnd_FChoose(r, cm->null, cm->abc->K);
2081 if((status = esl_stack_CPush(gsq, cm->abc->sym[lchar])) != eslOK) goto ERROR;
2082 N++;
2083 y = esl_rnd_FChoose(r, tmp_tvec, 2); /* choose next state, either EL or implicit END */
2084 }
2085 InsertTraceNode(tr, tpos, TRACE_LEFT_CHILD, lpos, N, cm->M); /* careful to reset y to cm->M */
2086 }
2087 else
2088 {
2089 if((status = esl_stack_IPush(pda, rchar)) != eslOK) goto ERROR; /* does it emit right? */
2090 if((status = esl_stack_IPush(pda, lchar)) != eslOK) goto ERROR; /* does it emit left? */
2091 if((status = esl_stack_IPush(pda, TRACE_LEFT_CHILD)) != eslOK) goto ERROR; /* non-B's: attach as left child by conv */
2092 if((status = esl_stack_IPush(pda, tpos)) != eslOK) goto ERROR; /* attach it to v, which is tpos in parsetree*/
2093 if((status = esl_stack_IPush(pda, y)) != eslOK) goto ERROR; /* next state we're going to */
2094 if((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
2095 }
2096 } /* end of PDA_STATE logic */
2097 } /* end of else (which we enter if v not a B state) */
2098 } /* end of main "while esl_stack_IPop()" loop */
2099
2100 if((seq = esl_stack_Convert2String(gsq)) == NULL) goto ERROR; /* this destroys gsq char stack */
2101 if(name != NULL) sq = esl_sq_CreateFrom(name, seq, NULL, NULL, NULL);
2102 else sq = esl_sq_CreateFrom("seq", seq, NULL, NULL, NULL);
2103 if(sq == NULL) goto ERROR;
2104 free(seq); /* we made a copy of this when creating sq */
2105 /* name can only be NULL if ret_sq == NULL, so we're throwing it away anyway */
2106
2107 /* digitize if nec */
2108 if(do_digital)
2109 if((status = esl_sq_Digitize(cm->abc, sq)) != eslOK) goto ERROR;
2110 /*ParsetreeDump(stdout, tr, cm, dsq);*/
2111
2112 esl_stack_Destroy(pda);
2113
2114 free(tmp_tvec);
2115 if (ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
2116 if (ret_sq != NULL) *ret_sq = sq; else esl_sq_Destroy(sq);
2117 if (ret_N != NULL) *ret_N = N;
2118 return eslOK;
2119
2120 ERROR:
2121 if(tr != NULL) FreeParsetree(tr);
2122 if(gsq != NULL) esl_stack_Destroy(gsq);
2123 if(pda != NULL) esl_stack_Destroy(pda);
2124 if(sq != NULL) esl_sq_Destroy(sq);
2125 if(tmp_tvec != NULL) free(tmp_tvec);
2126 return status;
2127 }
2128
2129 /* Function: ParsetreeScoreCorrectionNull2()
2130 * based on TraceScoreCorrection() from HMMER:
2131 * EPN 08.24.06 Janelia
2132 *
2133 * Purpose: Calculate a correction (in log_2 odds) to be
2134 * applied to a sequence, using a second null model,
2135 * based on a traceback. All emissions are corrected;
2136 * The null model is constructed /post hoc/ as the
2137 * average over all the emission distributions used by the trace.
2138 *
2139 * <omega> is the prior probability of the null3 model.
2140 * The log of this value is the penalty for the null3
2141 * correction. If <omega> is 1./65536., which it is
2142 * by default (1/2^16), we apply a 16 bit penalty.
2143 *
2144 * Return: ret_sc: the log_2-odds score correction.
2145 * eslEINCOMPAT on contract violation
2146 */
2147 int
2148 ParsetreeScoreCorrectionNull2(CM_t *cm, char *errbuf, Parsetree_t *tr, ESL_DSQ *dsq, int start, float omega, float *ret_sc)
2149 {
2150 int status;
2151 float *p; /* null2 model distribution */
2152 float *sc; /* null2 model scores */
2153 int a,b; /* residue index counters */
2154 int v; /* state index counter */
2155 int i, j; /* seq posn counter */
2156 int tidx;
2157 float score;
2158 float struct_score; /* structure contribution to the score */
2159
2160 if(ret_sc == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "ParsetreeScoreCorrectionNull2() ret_sc is NULL.");
2161
2162 /* Rarely, the alignment was totally impossible, and tr is NULL.
2163 */
2164 if (tr == NULL) return 0.0;
2165
2166 /* Set up model: average over the emission distributions of
2167 * all M, I states that appear in the trace. Ad hoc? Sure, you betcha.
2168 */
2169 /* trivial preorder traverse, since we're already numbered that way */
2170 ESL_ALLOC(p, sizeof(float) * cm->abc->K);
2171 esl_vec_FSet(p, cm->abc->K, 0.0);
2172 for (tidx = 0; tidx < tr->n; tidx++) {
2173 v = tr->state[tidx]; /* index of parent state in CM */
2174 if(cm->sttype[v] == MP_st) {
2175 /* we treat this as two match states. */
2176 for(a = 0; a < cm->abc->K; a++) {
2177 /* first add contribution to null2 for left half. */
2178 for(b = (a * cm->abc->K); b < ((a+1) * cm->abc->K); b++) p[a] += cm->e[v][b];
2179 /* now add contribution for right half. */
2180 for(b = a; b < (cm->abc->K * cm->abc->K); b += cm->abc->K) p[a] += cm->e[v][b];
2181 }
2182 }
2183 else if(cm->sttype[v] == ML_st || cm->sttype[v] == IL_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
2184 esl_vec_FAdd(p, cm->e[v], cm->abc->K);
2185 }
2186 }
2187 esl_vec_FNorm(p, cm->abc->K);
2188
2189 ESL_ALLOC(sc, sizeof(float) * (cm->abc->Kp));
2190 /* calculate null2 scores of each possible emission, first the base alphabet */
2191 for (a = 0; a < cm->abc->K; a++) sc[a] = sreLOG2(p[a] / cm->null[a]);
2192 /* the ambiguities */
2193 for (a = cm->abc->K+1; a < cm->abc->Kp-1; a++) sc[a] = esl_abc_FAvgScore(cm->abc, a, sc);
2194
2195 /* Score all the state emissions that appear in the trace.
2196 */
2197 score = struct_score = 0;
2198 for (tidx = 0; tidx < tr->n; tidx++) {
2199 v = tr->state[tidx]; /* index of parent state in CM */
2200 i = tr->emitl[tidx];
2201 j = tr->emitr[tidx];
2202 if (cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) score += sc[dsq[i+start-1]];
2203 if (cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) score += sc[dsq[j+start-1]];
2204 }
2205 /* Apply an ad hoc log(omega) fudge factor penalty;
2206 * interpreted as a prior, saying that the third null model is
2207 * <omega> as likely as the standard null model.
2208 * <omega> is by default 1/(2^16), so this is by default a
2209 * 16 bit penalty.
2210 */
2211 score += sreLOG2(omega);
2212
2213 /* Return the correction to the bit score. */
2214 ESL_DPRINTF1(("#DEBUG: ParsetreeScoreCorrectionNull2 return sc: %f\n", LogSum2(0., score)));
2215 free(sc);
2216 free(p);
2217 score = LogSum2(0., score);
2218 *ret_sc = score;
2219 return eslOK;
2220
2221 ERROR:
2222 ESL_FAIL(status, errbuf, "ParsetreeScoreCorrectionNull2(): memory allocation error.");
2223 return status; /* NEVERREACHED*/
2224 }
2225
2226
2227 /* Function: ParsetreeScoreCorrectionNull3()
2228 * Incept: EPN, Sat May 3 15:38:24 2008
2229 *
2230 * Purpose: Calculate a correction (in log_2 odds) to be
2231 * applied to a sequence, using a third null model, the
2232 * composition of the target sequence.
2233 * All emissions are corrected;
2234 * The null model is constructed /post hoc/ as the
2235 * distribution of the target sequence; if the target
2236 * sequence is 40% A, 5% C, 5% G, 40% U, then the null
2237 * model is (0.4, 0.05, 0.05, 0.4).
2238 *
2239 * NOTE: (start) is offset in dsq such that tr->emitl[0] corresponds
2240 * to the residue in dsq[1];
2241 *
2242 * <omega> is the prior probability of the null3 model.
2243 * The log of this value is the penalty for the null3
2244 * correction. If <omega> is 1./65536., which it is
2245 * by default (1/2^16), we apply a 16 bit penalty.
2246 *
2247 * Return: ret_sc: the log_2-odds score correction.
2248 * eslEINCOMPAT on contract violation
2249 */
2250 int
2251 ParsetreeScoreCorrectionNull3(CM_t *cm, char *errbuf, Parsetree_t *tr, ESL_DSQ *dsq, int start, float omega, float *ret_sc)
2252 {
2253 int status;
2254 float *p; /* null3 model distribution */
2255 float *sc; /* null3 model scores */
2256 int a; /* residue index counters */
2257 int v; /* state index counter */
2258 int i, j; /* seq posn counter */
2259 int tidx;
2260 float score;
2261 float struct_score; /* structure contribution to the score */
2262
2263 if(ret_sc == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "ParsetreeScoreCorrectionNull3() ret_sc is NULL.");
2264 /* Rarely, the alignment was totally impossible, and tr is NULL.
2265 */
2266 if (tr == NULL) return 0.0;
2267
2268 /* get composition of full subseq in parse from tr->emitl[0]..tr->emitr[0],
2269 * starting at dsq+start-1 b/c coords in tr->emit* are offset relative to dsq by start
2270 * such that tr->emitl[0] always equals 1.
2271 * Note: we're INcluding any EL emissions here in ACGU composition calculation but then
2272 * EXcluding them when we correct the score below (not sure if this is right),
2273 * in a way we're always assuming scores of ELs are 0.0, meaning there's no difference
2274 * between the probability they're emitted by the model and any possible NULL model.
2275 */
2276 get_alphabet_comp(cm->abc, dsq+start-1, tr->emitl[0], tr->emitr[0], &p);
2277 ESL_ALLOC(sc, sizeof(float) * (cm->abc->Kp));
2278 /* calculate null3 scores of each possible emission, first the base alphabet */
2279 for (a = 0; a < cm->abc->K; a++) {
2280 sc[a] = sreLOG2(p[a] / cm->null[a]);
2281 /*printf("p[%d]: %.3f sc %.3f\n", a, p[a], sc[a]);*/
2282 }
2283 /* the ambiguities */
2284 for (a = cm->abc->K+1; a < cm->abc->Kp-1; a++) sc[a] = esl_abc_FAvgScore(cm->abc, a, sc);
2285
2286 /* Score all the state emissions that appear in the trace.
2287 */
2288 score = struct_score = 0.;
2289 for (tidx = 0; tidx < tr->n; tidx++) {
2290 v = tr->state[tidx]; /* index of parent state in CM */
2291 i = tr->emitl[tidx];
2292 j = tr->emitr[tidx];
2293 if (cm->sttype[v] == MP_st || cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) score += sc[dsq[i+start-1]];
2294 if (cm->sttype[v] == MP_st || cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) score += sc[dsq[j+start-1]];
2295 }
2296 /* Apply an ad hoc log(omega) fudge factor penalty;
2297 * interpreted as a prior, saying that the third null model is
2298 * <omega> as likely as the standard null model.
2299 * <omega> is by default 1/(2^16), so this is by default a
2300 * 16 bit penalty.
2301 */
2302 score += sreLOG2(omega);
2303
2304 /* Return the correction to the bit score. */
2305 /*printf("ParsetreeScoreCorrectionNull3 return sc: %f\n", LogSum2(0., score));*/
2306 ESL_DPRINTF1(("#DEBUG: ParsetreeScoreCorrectionNull3 return sc: %f\n", LogSum2(0., score)));
2307 free(sc);
2308 free(p);
2309 score = LogSum2(0., score);
2310 *ret_sc = score;
2311 return eslOK;
2312
2313 ERROR:
2314 ESL_FAIL(status, errbuf, "ParsetreeScoreCorrectionNull3(): memory allocation error.");
2315 return status; /* NEVERREACHED*/
2316 }
2317
2318 /* Function: ScoreCorrectionNull3()
2319 * Incept: EPN, Sat May 10 17:58:03 2008
2320 *
2321 * Purpose: Calculate a correction (in log_2 odds) to be
2322 * applied to a sequence, using a third null model, the
2323 * composition of the target sequence.
2324 * All emissions are corrected;
2325 * The null model is constructed /post hoc/ as the
2326 * distribution of the target sequence; if the target
2327 * sequence is 40% A, 5% C, 5% G, 40% U, then the null
2328 * model is (0.4, 0.05, 0.05, 0.4).
2329 *
2330 * Note: no trace or parsetree is needed. The bit score correction
2331 * can be derived solely by the nucleotide composition of the hit and
2332 * it's length.
2333 *
2334 * <omega> is the prior probability of the null3 model.
2335 * The log of this value is the penalty for the null3
2336 * correction. If <omega> is 1./65536., which it is
2337 * by default (1/2^16), we apply a 16 bit penalty.
2338 *
2339 * Args: abc - alphabet for hit (only used to get alphabet size, which is size of <comp>)
2340 * null0- the first null model used when building the CM, usually cm->null or cm->cp9->null
2341 * comp - [0..a..abc->K-1] frequency of residue a in the hit we're correcting the score for,
2342 * passed in b/c we can efficiently compute this during scanning DP funcs instead of
2343 * calcing it each time per hit which is wasteful for many, possibly overlapping hits
2344 * which is the case during model calibration with cmcalibrate.
2345 * len - length of the hit
2346 * ret_sc- RETURN: the correction to the score, caller subtracts this from hit score to get
2347 * corrected score.
2348 *
2349 * Return: void, ret_sc: the log_2-odds score correction.
2350 */
2351 void
2352 ScoreCorrectionNull3(const ESL_ALPHABET *abc, float *null0, float *comp, int len, float omega, float *ret_sc)
2353 {
2354 int a; /* residue index counters */
2355 float score = 0.;
2356
2357 /*printf("\n");
2358 esl_vec_FDump(stdout, comp, abc->K, NULL);*/
2359
2360 for (a = 0; a < abc->K; a++) score += sreLOG2(comp[a] / null0[a]) * comp[a] * len;
2361
2362 /* Apply an ad hoc log(omega) fudge factor penalty;
2363 * interpreted as a prior, saying that the third null model is
2364 * <omega> as likely as the standard null model.
2365 * <omega> is by default 1/(2^16), so this is by default a
2366 * 16 bit penalty.
2367 */
2368 score += sreLOG2(omega);
2369
2370 /* Return the correction to the bit score. */
2371
2372 /* Return the correction to the bit score. */
2373 /*printf("ScoreCorrectionNull3 return sc: %.3f\n", LogSum2(0., score));*/
2374 ESL_DPRINTF3(("#DEBUG: ScoreCorrectionNull3 return sc: %f\n", LogSum2(0., score)));
2375 score = LogSum2(0., score);
2376 *ret_sc = score;
2377 return;
2378 }
2379
2380
2381 /* Function: ScoreCorrectionNull3CompUnknown()
2382 * Incept: EPN, Thu May 22 13:16:04 2008
2383 *
2384 * Purpose: Calculate a correction (in log_2 odds) to be
2385 * applied to a sequence, using a third null model, the
2386 * composition of the target sequence.
2387 * All emissions are corrected;
2388 * The null model is constructed /post hoc/ as the
2389 * distribution of the target sequence; if the target
2390 * sequence is 40% A, 5% C, 5% G, 40% U, then the null
2391 * model is (0.4, 0.05, 0.05, 0.4).
2392 *
2393 * Same as ScoreCorrectionNull3() except that no <comp> vector is needed,
2394 * the composition is determined within this function.
2395 *
2396 * <omega> is the prior probability of the null3 model.
2397 * The log of this value is the penalty for the null3
2398 * correction. If <omega> is 1./65536., which it is
2399 * by default (1/2^16), we apply a 16 bit penalty.
2400 *
2401 * Args: abc - alphabet for hit (only used to get alphabet size, which is size of <comp>)
2402 * null0- the first null model used when building the CM, usually cm->null or cm->cp9->null
2403 * dsq - the sequence the hit resides in
2404 * start- start position of hit in dsq
2405 * end - end position of hit in dsq
2406 * ret_sc- RETURN: the correction to the score, caller subtracts this from hit score to get
2407 * corrected score.
2408 * Return: void, ret_sc: the log_2-odds score correction.
2409 */
2410 void
2411 ScoreCorrectionNull3CompUnknown(const ESL_ALPHABET *abc, float *null0, ESL_DSQ *dsq, int start, int stop, float omega, float *ret_sc)
2412 {
2413 float score = 0.;
2414 float *comp; /* null3 model distribution */
2415
2416 get_alphabet_comp(abc, dsq, start, stop, &comp);
2417 ScoreCorrectionNull3(abc, null0, comp, (stop-start+1), omega, &score);
2418 free(comp);
2419 *ret_sc = score;
2420 return;
2421 }
2422
2423
2424
2425 /* Function: ParsetreeCountMPEmissions()
2426 * Date: EPN, Thu May 22 14:11:28 2008
2427 *
2428 * Purpose: Given a parsetree, return the number of residues emitted by MP states.
2429 *
2430 * Returns: Number of residues emitted by MP states in <tr>.
2431 */
2432 int
2433 ParsetreeCountMPEmissions(CM_t *cm, Parsetree_t *tr)
2434 {
2435 int tidx;
2436 int nres_by_mp = 0;
2437
2438 for (tidx = 0; tidx < tr->n; tidx++) {
2439 if(cm->sttype[tr->state[tidx]] == MP_st) nres_by_mp += 2;
2440 }
2441 return nres_by_mp;
2442 }
2443
2444 /* Function: Alignment2Parsetrees()
2445 * EPN, Fri Jul 11 09:49:50 2008
2446 *
2447 * Purpose: Given a MSA <msa>, a CM <cm> and a guidetree <mtr> for <cm>,
2448 * Determine the implicit parsetrees of the sequences in the
2449 * MSA to the CM. Return the parsetrees in <ret_tr> if non-NULL,
2450 * sequence objects in <ret_sq> if non-null.
2451 *
2452 * Dealign the MSA seqs in <ret_sq> and convert from aligned to
2453 * unaligned coordinates in <ret_tr>.
2454 *
2455 * Args: msa - MSA we want to infer parsetrees from
2456 * cm - CM we're aligning to
2457 * mtr - master parsetree, guide tree for CM
2458 * errbuf - easel error message
2459 * ret_sq - Return: dealigned msa seqs in digital form
2460 * ret_tr - Return: parsetree for seqs in dealigned coords
2461 *
2462 * Returns: eslOK on success, eslEINCOMPAT on contract violation, eslEMEM on memory error
2463 * <ret_tr>, <ret_sq>, see 'Purpose'.
2464 */
2465 int
2466 Alignment2Parsetrees(ESL_MSA *msa, CM_t *cm, Parsetree_t *mtr, char *errbuf, ESL_SQ ***ret_sq, Parsetree_t ***ret_tr)
2467 {
2468 int status;
2469 int i; /* counter over aseqs */
2470 int apos; /* aligned position index */
2471 int uapos; /* unaligned position index */
2472 int x; /* counter of parsetree nodes */
2473 int *map = NULL; /* for current seq, [0..msa->alen] map from aligned posns to unaligned (non-gap) posns */
2474 int *used_el = NULL; /* [0..msa->alen] used_el[apos] is TRUE if position apos is modeled by EL state, FALSE if not */
2475 char *uaseq = NULL; /* current seq, dealigned from the MSA */
2476 char *aseq = NULL; /* current seq, aligned text */
2477 Parsetree_t **tr = NULL; /* [0..msa->nseq-1] new parsetrees, one per seq in msa */
2478 ESL_SQ **sq = NULL; /* [0..msa->nseq-1] new ESL_SQ objects, one per seq in msa */
2479
2480 /* Contract check */
2481 if(msa == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "Alignment2Parsetrees() msa is NULL.\n");
2482 if(! (msa->flags & eslMSA_DIGITAL)) ESL_FAIL(eslEINCOMPAT, errbuf, "Alignment2Parsetrees() msa is not digitized.\n");
2483 if(ret_tr == NULL && ret_sq == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "Alignment2Parsetrees() ret_sq and ret_tr both NULL.");
2484
2485 if(ret_tr != NULL) ESL_ALLOC(tr, (sizeof(Parsetree_t *) * msa->nseq));
2486 if(ret_sq != NULL) ESL_ALLOC(sq, (sizeof(ESL_SQ *) * msa->nseq));
2487 ESL_ALLOC(aseq, sizeof(char) * (msa->alen+1));
2488 ESL_ALLOC(map, sizeof(int) * (msa->alen+1));
2489 ESL_ALLOC(used_el, sizeof(int) * (msa->alen+1));
2490 map[0] = -1; /* invalid */
2491 used_el[0] = FALSE; /* invalid */
2492 if(msa->rf != NULL) {
2493 for(apos = 0; apos < msa->alen; apos++) {
2494 used_el[apos+1] = (msa->rf[apos] == '~') ? TRUE : FALSE;
2495 }
2496 }
2497 else {
2498 /* no msa->rf, impossible to tell if any columns are EL, assume none are */
2499 esl_vec_ISet(used_el, msa->alen+1, FALSE);
2500 }
2501
2502 for (i = 0; i < msa->nseq; i++) {
2503 uapos = 1;
2504 /* map aligned to dealigned coords (digitized coords, 1..alen) for this seq
2505 * map is needed b/c we want the parsetree in dealigned coords so we can
2506 * call Parsetrees2Alignment with it, but mtr is in aligned coords, and
2507 * Transmogrify works in aligned coords, so after calling Transmogrify
2508 * we have to convert tr->emitl and tr->emitr to dealigned coords using map.
2509 */
2510 for(apos = 1; apos <= msa->alen; apos++)
2511 map[apos] = esl_abc_XIsGap(msa->abc, msa->ax[i][apos]) ? -1 : uapos++;
2512 /* get text seq, we need digitized AND text seqs for Transmogrify */
2513 esl_abc_Textize(msa->abc, msa->ax[i], msa->alen, aseq);
2514 esl_strdup(aseq, -1, &uaseq);
2515 /* dealign seq */
2516 esl_strdealign(uaseq, uaseq, "-_.~", NULL);
2517 /* Transmogrify the aligned seq to get a parsetree */
2518 if(ret_tr != NULL) {
2519 if((status = Transmogrify(cm, errbuf, mtr, msa->ax[i], used_el, msa->alen, &(tr[i]))) != eslOK) return status;
2520 /*ParsetreeDump(stdout, tr[i], cm, msa->ax[i]);*/
2521 /* tr[i] is in alignment coords, convert it to unaligned coords, */
2522 for(x = 0; x < tr[i]->n; x++) {
2523 /*printf("i: %d x: %d emitl %d emitr %d\n", i, x, tr[i]->emitl[x], tr[i]->emitr[x]);*/
2524 if(tr[i]->emitl[x] != -1) {
2525 /*printf("\tmapl: %d\n", map[i][tr[i]->emitl[x]]);*/
2526 tr[i]->emitl[x] = map[tr[i]->emitl[x]];
2527 }
2528 if(tr[i]->emitr[x] != -1) {
2529 /*printf("\tmapr: %d\n", map[i][tr[i]->emitr[x]]);*/
2530 tr[i]->emitr[x] = map[tr[i]->emitr[x]];
2531 }
2532 }
2533 }
2534 if(ret_sq != NULL) {
2535 sq[i] = esl_sq_CreateFrom(msa->sqname[i], uaseq, NULL, NULL, NULL);
2536 esl_sq_Digitize(cm->abc, sq[i]);
2537 }
2538 free(uaseq); /* this gets reallocated and filled per seq in esl_strdup() call above */
2539 }
2540 free(aseq);
2541 free(map);
2542 free(used_el);
2543
2544 /* tr and sq are only allocated if ret_tr and ret_sq were non-null */
2545 if(ret_tr != NULL) *ret_tr = tr;
2546 if(ret_sq != NULL) *ret_sq = sq;
2547
2548 return eslOK;
2549
2550 ERROR:
2551 if(map != NULL) free(map);
2552 if(used_el != NULL) free(used_el);
2553 if(uaseq != NULL) free(uaseq);
2554 if(aseq != NULL) free(aseq);
2555 return status;
2556 }
2557
2558 /* Function: ParsetreeMode()
2559 * Incept: EPN, Thu Nov 10 11:31:04 2011
2560 *
2561 * Purpose: Return the alignment mode of a parsetree.
2562 */
2563 char
2564 ParsetreeMode(Parsetree_t *tr)
2565 {
2566 return tr->mode[0];
2567 }
2568
2569 /* Function: ParsetreeToCMBounds()
2570 * Incept: EPN, Wed Jan 4 05:34:32 2012
2571 *
2572 * Purpose: Determine the CM consensus position (cpos) boundaries
2573 * spanned in a parsetree. Return two sets of boundaries:
2574 *
2575 * <cfrom_span>..<cto_span>: first..final cpos spanned by
2576 * any state in parsetree (regardless of truncation mode).
2577 *
2578 * <cfrom_emit>..<cto_emit>: first..final cpos spanned by
2579 * any state in parsetree in relevant truncation mode
2580 * (J or L for MATP&MATL, J or R for MATP&MATR)
2581 *
2582 * <first_emit>..<final_emit>: first..final cpos that
2583 * emits a residue (doesn't use a delete state or
2584 * silent off-mode state).
2585 *
2586 * Args: cm - the covariance model
2587 * tr - the parsetree
2588 * have_i0 - TRUE if first res of source sequence is emitted in tr
2589 * have_j0 - TRUE if final res of source sequence is emitted in tr
2590 * errbuf - for error messages
2591 * ret_cfrom_span - RETURN: cfrom_span, explained in Purpose.
2592 * ret_cto_span - RETURN: cto_span, explained in Purpose.
2593 * ret_cfrom_emit - RETURN: cfrom_emit, explained in Purpose.
2594 * ret_cto_span - RETURN: cto_emit, explained in Purpose.
2595 * ret_first_emit - RETURN: first_emit, explained in Purpose.
2596 * ret_final_emit - RETURN: final_emit, explained in Purpose.
2597 *
2598 *
2599 * Returns: eslOK on success.
2600 * eslEINVAL if cm->emap is NULL.
2601 */
2602 int
2603 ParsetreeToCMBounds(CM_t *cm, Parsetree_t *tr, int have_i0, int have_j0, char *errbuf, int *ret_cfrom_span, int *ret_cto_span, int *ret_cfrom_emit, int *ret_cto_emit, int *ret_first_emit, int *ret_final_emit)
2604 {
2605 int ti; /* counter over parsetree nodes */
2606 int v, nd; /* state, node index */
2607 int prv_v; /* previous state */
2608 int sdl, sdr; /* state left delta, state right delta for current state */
2609 int insert_sd; /* number of insert residues emitted for current state */
2610 char mode; /* truncation mode */
2611 int is_left; /* does current node/state emit left? */
2612 int is_right; /* does current node/state emit right? */
2613 int cfrom_span; /* first position spanned by any state of the full parsetree: we guess at this if we're truncated */
2614 int cto_span; /* first position spanned by any state of the full parsetree: we guess at this if we're truncated */
2615 int cfrom_emit; /* first model position spanned by any state in parsetree in relevant mode
2616 * (J or L for MATP&MATL, J or R for MATP&MATR) */
2617 int cto_emit; /* final model position spanned by any state in parsetree in relevant mode
2618 * (J or L for MATP&MATL, J or R for MATP&MATR) */
2619 int first_emit; /* first model consensus position that emits a residue */
2620 int final_emit; /* final model consensus position that emits a residue */
2621 int lpos, rpos; /* boundaries of a consensus subtree */
2622
2623 /* if parsetree/alignment is in J mode (not L, R, or T) then
2624 * cfrom_span == cfrom_emit and cto_span == cto_emit
2625 *
2626 * if first/final consensus positions used are not
2627 * gaps (aligned to delete states) then
2628 * cfrom_emit == first_emit and cto_emit == final_emit
2629 */
2630
2631 if(cm->emap == NULL) ESL_FAIL(eslEINVAL, errbuf, "ParsetreeToCMBounds(), cm->emap is NULL");
2632
2633 cfrom_span = cfrom_emit = first_emit = cm->clen+1;
2634 cto_span = cto_emit = final_emit = 0;
2635
2636 for (ti = 0; ti < tr->n; ti++) {
2637 v = tr->state[ti];
2638 mode = tr->mode[ti];
2639 sdl = StateLeftDelta(cm->sttype[v]);
2640 sdr = StateRightDelta(cm->sttype[v]);
2641 if(v != cm->M) {
2642 nd = cm->ndidx[v];
2643 lpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) ? cm->emap->lpos[nd] : cm->emap->lpos[nd] + 1;
2644 rpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) ? cm->emap->rpos[nd] : cm->emap->rpos[nd] - 1;
2645
2646 if (cm->sttype[v] == IL_st) { is_left = TRUE; is_right = FALSE; insert_sd = 1; }
2647 else if(cm->sttype[v] == IR_st) { is_left = FALSE; is_right = TRUE; insert_sd = 1; }
2648 else if(cm->ndtype[nd] == MATP_nd) { is_left = TRUE; is_right = TRUE; insert_sd = 0; }
2649 else if(cm->ndtype[nd] == MATL_nd) { is_left = TRUE; is_right = FALSE; insert_sd = 0; }
2650 else if(cm->ndtype[nd] == MATR_nd) { is_left = FALSE; is_right = TRUE; insert_sd = 0; }
2651 else { is_left = FALSE; is_right = FALSE; insert_sd = 0; }
2652 }
2653 else { /* v == cm->M, special case, use previous state and treat as left and right and possibly insert (see below) */
2654 prv_v = tr->state[ti-1];
2655 mode = tr->mode[ti-1];
2656 sdl = 0; /* this prevents EL from affecting first/final_emit */
2657 sdr = 0; /* this prevents EL from affecting first/final_emit */
2658 is_left = TRUE;
2659 is_right = TRUE;
2660 nd = 1 + cm->ndidx[prv_v]; /* calculate node that EL replaced */
2661 lpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) ? cm->emap->lpos[nd] : cm->emap->lpos[nd] + 1;
2662 rpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) ? cm->emap->rpos[nd] : cm->emap->rpos[nd] - 1;
2663 }
2664
2665
2666 if(is_left) {
2667 if(ModeEmitsLeft(mode) || v == cm->M) {
2668 cfrom_emit = ESL_MIN(cfrom_emit, lpos + insert_sd); /* '+ insert_sd' for cfrom b/c we insert after match/delete */
2669 cto_emit = ESL_MAX(cto_emit, lpos);
2670 if(sdl > 0 && cm->sttype[v] != IL_st) { /* inserts don't impact first_emit/final_emit */
2671 first_emit = ESL_MIN(first_emit, lpos);
2672 final_emit = ESL_MAX(final_emit, lpos);
2673 }
2674 }
2675 }
2676 if(is_right) {
2677 if(ModeEmitsRight(mode) || v == cm->M) {
2678 cfrom_emit = ESL_MIN(cfrom_emit, rpos + insert_sd); /* '+ insert_sd' for cfrom b/c we insert after match/delete */
2679 cto_emit = ESL_MAX(cto_emit, rpos);
2680 if(sdr > 0 && cm->sttype[v] != IR_st) { /* inserts don't impact first_emit/final_emit */
2681 first_emit = ESL_MIN(first_emit, rpos);
2682 final_emit = ESL_MAX(final_emit, rpos);
2683 }
2684 }
2685 }
2686 }
2687
2688 /* Final step, define cfrom_span/cto_span. These will be the
2689 * lpos/rpos of the node the parsetree is rooted at if the hit is
2690 * not truncated. If it is truncated we define these as guesses at
2691 * the the first and final positions spanned by the full parsetree,
2692 * i.e. the parsetree of the full sequence if it were not
2693 * truncated. (We can't possibly know what these are, so we guess.)
2694 * We use these guesses to display number of truncated positions 5'
2695 * and/or 3' in the CM_ALIDISPLAY.
2696 */
2697 if(ret_cfrom_span != NULL || ret_cto_span != NULL) {
2698 nd = cm->ndidx[tr->state[1]];
2699 cfrom_span = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) ? cm->emap->lpos[nd] : cm->emap->lpos[nd] + 1;
2700 cto_span = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) ? cm->emap->rpos[nd] : cm->emap->rpos[nd] - 1;
2701 /* aligned fragment is from g..h (1<=g<=h<=clen) in consensus positions,
2702 * nd is currently the lowest node in the model tree that spans g..h.
2703 */
2704 if(tr->pass_idx == PLI_PASS_5P_ONLY_FORCE && have_i0) {
2705 /* a 5' truncation only */
2706 rpos = cto_span;
2707 /* find highest nd in the tree whose subtree ends at exactly cto_span
2708 * we'll guess that our full hit would be rooted at that node if it wasn't truncated.
2709 */
2710 while(rpos == cto_span && nd > 0) {
2711 nd--;
2712 rpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) ? cm->emap->rpos[nd] : cm->emap->rpos[nd] - 1;
2713 }
2714 cfrom_span = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) ? cm->emap->lpos[nd] : cm->emap->lpos[nd] + 1;
2715 }
2716 if(tr->pass_idx == PLI_PASS_3P_ONLY_FORCE && have_j0) {
2717 /* a 3' truncation only */
2718 lpos = cfrom_span;
2719 /* find highest nd in the tree whose subtree begins at exactly cfrom_span
2720 * we'll guess that our full hit would be rooted at that node if it wasn't truncated.
2721 */
2722 while(lpos == cfrom_span && nd > 0) {
2723 nd--;
2724 lpos = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) ? cm->emap->lpos[nd] : cm->emap->lpos[nd] + 1;
2725 }
2726 cto_span = (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) ? cm->emap->rpos[nd] : cm->emap->rpos[nd] - 1;
2727 }
2728 if(tr->pass_idx == PLI_PASS_5P_AND_3P_FORCE && have_i0 && have_j0) {
2729 /* 5' and 3' truncation and we have the first and final residue aligned */
2730 /* we guess it was a full hit */
2731 cfrom_span = 1;
2732 cto_span = cm->clen;
2733 }
2734 if(tr->pass_idx == PLI_PASS_5P_AND_3P_ANY) {
2735 /* we've allowed truncated hits anywhere, not sure what to do here... */
2736 /* we guess it was a full hit */
2737 cfrom_span = 1;
2738 cto_span = cm->clen;
2739 }
2740 if(tr->pass_idx == PLI_PASS_STD_ANY) {
2741 /* sanity check */
2742 if(cfrom_emit != cfrom_span) ESL_FAIL(eslFAIL, errbuf, "ParsetreeToCMBounds(), std pipeline pass, cfrom_emit != cfrom_span (bug)");
2743 if(cto_emit != cto_span) ESL_FAIL(eslFAIL, errbuf, "ParsetreeToCMBounds(), std pipeline pass, cto_emit != cto_span (bug)");
2744 }
2745 }
2746
2747 if(ret_cfrom_span != NULL) *ret_cfrom_span = cfrom_span;
2748 if(ret_cto_span != NULL) *ret_cto_span = cto_span;
2749 if(ret_cfrom_emit != NULL) *ret_cfrom_emit = cfrom_emit;
2750 if(ret_cto_emit != NULL) *ret_cto_emit = cto_emit;
2751 if(ret_first_emit != NULL) *ret_first_emit = first_emit;
2752 if(ret_final_emit != NULL) *ret_final_emit = final_emit;
2753
2754 return eslOK;
2755 }
2756
2757
2758 /* Function: cm_StochasticParsetree()
2759 * Incept: EPN, Thu Nov 15 16:45:32 2007
2760 * EPN, Wed Jan 11 10:52:11 2012 [Updated]
2761 *
2762 * Purpose: Sample a parsetree from a non-banded float Inside
2763 * matrix. The Inside matrix must have been already filled by
2764 * cm_InsideAlign(). Renamed from SampleFromInside() [EPN,
2765 * Wed Sep 14 06:17:11 2011].
2766 *
2767 * Args: cm - the model
2768 * errbuf - char buffer for reporting errors
2769 * dsq - digitized sequence
2770 * L - length of dsq
2771 * mx - pre-calculated Inside matrix (floats)
2772 * r - source of randomness
2773 * ret_tr - RETURN: sampled parsetree
2774 * ret_sc - RETURN: score of sampled parsetree
2775 *
2776 * Returns: <eslOK> on success.
2777 * Throws: <eslEMEM> if we run out of memory.
2778 */
2779
2780 int
2781 cm_StochasticParsetree(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, CM_MX *mx, ESL_RANDOMNESS *r, Parsetree_t **ret_tr, float *ret_sc)
2782 {
2783 int status; /* easel status code */
2784 int v, y, z, b; /* state indices */
2785 int yoffset; /* transition offset in a states transition vector */
2786 int i, j; /* sequence position indices */
2787 int d; /* j - i + 1; the current subseq length */
2788 int k; /* right subseq fragment length for bifurcs */
2789 int bifparent; /* for connecting bifurcs */
2790 Parsetree_t *tr = NULL; /* trace we're building */
2791 ESL_STACK *pda = NULL; /* the stack */
2792 int vec_size; /* size of pA, validA */
2793 int cur_vec_size; /* number of elements we're currently using in pA, validA */
2794 float *pA = NULL; /* prob vector of possible paths to take, used for various state types */
2795 int *validA = NULL; /* is pA a valid choice? (or was it supposed to be IMPOSSIBLE) */
2796 int el_is_possible; /* TRUE if we can jump to EL from current state (and we're in local mode) FALSE if not */
2797 float fsc = 0.; /* score of the parsetree we're sampling */
2798 int choice; /* index represeting sampled choice */
2799 int sd, sdr; /* state delta, state right delta */
2800
2801 /* the DP matrix, filled by prior call to cm_InsideAlign() */
2802 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
2803
2804 /* allocate and initialize probability vectors */
2805 vec_size = ESL_MAX(L+1, ESL_MAX(cm->M, MAXCONNECT+1));
2806 /* multipurpose vectors, we need up to L+1 elements for bifs, M elements for root, MAXCONNECT+1 for other states */
2807 ESL_ALLOC(pA, sizeof(float) * vec_size);
2808 ESL_ALLOC(validA, sizeof(int) * vec_size);
2809 esl_vec_FSet(pA, vec_size, IMPOSSIBLE);
2810 esl_vec_ISet(validA, vec_size, FALSE);
2811
2812 /* Create a parse tree structure and initialize it by adding the root state, with appropriate mode */
2813 tr = CreateParsetree(100);
2814 InsertTraceNode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0); /* init: attach the root S */
2815
2816 /* Stochastically traceback through the TrInside matrix
2817 * this section of code is adapted from cm_dpsmall.c:insideT().
2818 */
2819 if ((pda = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }
2820
2821 v = 0;
2822 j = d = L;
2823 i = 1;
2824 fsc = 0.;
2825 while (1) {
2826 if (cm->sttype[v] == B_st) {
2827 y = cm->cfirst[v];
2828 z = cm->cnum[v];
2829
2830 cur_vec_size = d+1;
2831 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE); /* only valid k's will be reset to a non-IMPOSSIBLE score, d+1 and d+2 store special cases in L and R mode, remain invalid for J and T mode */
2832
2833 /* Set pA[] as (float-ized) log odds scores for each valid right fragment length, k,
2834 * and choose a k.
2835 */
2836 for(k = 0; k <= d; k++) {
2837 pA[k] = alpha[y][j-k][d-k] + alpha[z][j][k];
2838 }
2839 /* sample k */
2840 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (B_st) is 0.");
2841 k = choice;
2842
2843 /* Store info about the right fragment that we'll retrieve later:
2844 */
2845 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR; /* remember the end j */
2846 if((status = esl_stack_IPush(pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
2847 if((status = esl_stack_IPush(pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
2848
2849 /* Deal with attaching left start state.
2850 */
2851 j = j-k;
2852 d = d-k;
2853 i = j-d+1;
2854 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
2855 v = y;
2856 }
2857 else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
2858 /* We don't trace back from an E or EL. Instead, we're done with the
2859 * left branch of the tree, and we try to swing over to the right
2860 * branch by popping a right start off the stack and attaching
2861 * it. If the stack is empty, then we're done with the
2862 * traceback altogether. This is the only way to break the
2863 * while (1) loop.
2864 */
2865 if (esl_stack_IPop(pda, &bifparent) == eslEOD) break;
2866 esl_stack_IPop(pda, &d);
2867 esl_stack_IPop(pda, &j);
2868 v = tr->state[bifparent]; /* recover state index of B */
2869 y = cm->cnum[v]; /* find state index of right S */
2870 i = j-d+1;
2871 /* attach the S to the right */
2872 InsertTraceNode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y);
2873 v = y;
2874 }
2875 else {
2876 if((v > 0) || (! (cm->flags & CMH_LOCAL_BEGIN))) { /* not a ROOT_S or local begins are off */
2877 /* add in emission score (or 0.0 if we're a non-emitter) */
2878 fsc += get_femission_score(cm, dsq, v, i, j);
2879 sd = StateDelta(cm->sttype[v]);
2880 sdr = StateRightDelta(cm->sttype[v]);
2881
2882 /* set pA[] as (float-ized) log odds scores for each child we can transit to,
2883 * plus a local end (if possible), and choose a transition.
2884 */
2885 cur_vec_size = cm->cnum[v];
2886 el_is_possible = FALSE;
2887 if((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
2888 el_is_possible = TRUE;
2889 cur_vec_size++;
2890 }
2891 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
2892 for(yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
2893 y = cm->cfirst[v] + yoffset;
2894 pA[yoffset] = cm->tsc[v][yoffset] + alpha[y][j-sdr][d-sd];
2895 }
2896 if(el_is_possible) {
2897 pA[cur_vec_size-1] = cm->endsc[v] + alpha[cm->M][j][d];
2898 }
2899 /* sample yoffset */
2900 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (non B_st) is 0.");
2901 yoffset = choice;
2902 if(yoffset < cm->cnum[v]) {
2903 fsc += cm->tsc[v][yoffset];
2904 }
2905 else {
2906 yoffset = USED_EL; /* we chose EL */
2907 fsc += cm->endsc[v] + (cm->el_selfsc * (d - sd)); /* transition to EL plus score of all EL emissions */
2908 }
2909 }
2910 else { /* v == 0 && (cm->flags && CMH_LOCAL_BEGIN) ( local begins are on ) */
2911 cur_vec_size = cm->M; /* pretend all states are possible to begin into, but they're not as some will remain IMPOSSIBLE */
2912 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
2913 for(y = 0; y < cm->M; y++) {
2914 if(NOT_IMPOSSIBLE(cm->beginsc[y])) {
2915 pA[y] = cm->beginsc[y] + alpha[y][j][d];
2916 }
2917 }
2918 /* sample b */
2919 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid local begins is 0.");
2920 b = choice;
2921 fsc += cm->beginsc[b];
2922 yoffset = USED_LOCAL_BEGIN;
2923 }
2924
2925 /* adjust i and j appropriately based on state type */
2926 switch (cm->sttype[v]) {
2927 case D_st: break;
2928 case MP_st: i++; j--; break;
2929 case ML_st: i++; break;
2930 case MR_st: j--; break;
2931 case IL_st: i++; break;
2932 case IR_st: j--; break;
2933 case S_st: break;
2934 default: ESL_FAIL(eslEINCONCEIVABLE, errbuf, "'Inconceivable!'\n'You keep using that word...'");
2935 }
2936 d = j-i+1;
2937
2938 if (yoffset == USED_EL) {
2939 /* a local alignment end */
2940 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M);
2941 v = cm->M; /* now we're in EL */
2942 }
2943 else if (yoffset == USED_LOCAL_BEGIN) {
2944 /* local begin; can only happen once, from root */
2945 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b);
2946 v = b;
2947 }
2948 else {
2949 y = cm->cfirst[v] + yoffset;
2950 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
2951 v = y;
2952 }
2953 /* ParsetreeDump(stdout, tr, cm, dsq);*/
2954 }
2955 }
2956 if(pda != NULL) esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
2957 if(pA != NULL) free(pA);
2958 if(validA != NULL) free(validA);
2959
2960 #if eslDEBUGLEVEL >= 2
2961 /* ParsetreeDump(stdout, tr, cm, dsq); */
2962 float sc;
2963 ParsetreeScore(cm, cm->emap, errbuf, tr, dsq, FALSE, &sc, NULL, NULL, NULL, NULL);
2964 printf("#DEBUG: parsetree score: %.4f\n", sc);
2965 printf("#DEBUG: fsc: %.4f\n", fsc);
2966 #endif
2967
2968 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
2969 if(ret_sc != NULL) *ret_sc = fsc;
2970
2971 ESL_DPRINTF1(("#DEBUG: cm_StochasticParsetree() return sc: %f\n", fsc));
2972 return eslOK;
2973
2974 ERROR:
2975 if(pda != NULL) esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
2976 if(pA != NULL) free(pA);
2977 if(validA != NULL) free(validA);
2978
2979 if(tr != NULL) FreeParsetree(tr);
2980
2981 if(ret_tr != NULL) *ret_tr = NULL;
2982 if(ret_sc != NULL) *ret_sc = 0.;
2983
2984 ESL_FAIL(status, errbuf, "out of memory");
2985 return status; /* NEVER REACHED */
2986 }
2987
2988 /* Function: cm_StochasticParsetreeHB()
2989 * Incept: EPN, Fri Sep 7 11:02:15 2007
2990 * EPN, Wed Jan 11 16:21:59 2012 [updated]
2991 *
2992 * Purpose: Sample a parsetree from a HMM banded float
2993 * Inside matrix. The Inside matrix must have been already
2994 * filled by cm_InsideAlignHB(). Analogous
2995 * to cm_StochasticParsetree(), but uses HMM bands.
2996 *
2997 * Args: cm - the model
2998 * errbuf - char buffer for reporting errors
2999 * dsq - digitized sequence
3000 * L - length of dsq
3001 * mx - pre-calculated Inside matrix
3002 * r - source of randomness
3003 * ret_tr - RETURN: sampled parsetree
3004 * ret_sc - RETURN: score of sampled parsetree
3005 *
3006 * Returns: <eslOK> on success.
3007 * Throws: <eslEMEM> if we run out of memory.
3008 */
3009 int
3010 cm_StochasticParsetreeHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, CM_HB_MX *mx, ESL_RANDOMNESS *r, Parsetree_t **ret_tr, float *ret_sc)
3011 {
3012 int status; /* easel status code */
3013 int v, y, z, b; /* state indices */
3014 int yoffset; /* transition offset in a states transition vector */
3015 int i, j; /* sequence position indices */
3016 int d; /* j - i + 1; the current subseq length */
3017 int k; /* right subseq fragment length for bifurcs */
3018 int bifparent; /* for connecting bifurcs */
3019 Parsetree_t *tr = NULL; /* trace we're building */
3020 ESL_STACK *pda = NULL; /* the stack */
3021 int vec_size; /* size of pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3022 int cur_vec_size; /* number of elements we're currently using in pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3023 float *pA = NULL; /* prob vector of possible paths to take, used for various state types */
3024 int *validA = NULL; /* is pA a valid choice? (or was it supposed to be IMPOSSIBLE) */
3025 int el_is_possible; /* TRUE if we can jump to EL from current state (and we're in local mode) FALSE if not */
3026 float fsc = 0.; /* score of the parsetree we're sampling */
3027 int choice; /* index represeting sampled choice */
3028 int sd, sdr; /* state delta, state right delta */
3029
3030 /* variables used in HMM banded version but no nonbanded version */
3031 int jp_v; /* j - jmin[v] */
3032 int jp_y, dp_y ; /* j - jmin[y], d - hdmin[y][jp_y] */
3033 int jp_z, kp_z; /* j - jmin[z], d - hdmin[z][jp_z] */
3034 int jp_y_sdr; /* j - jmin[y] - vms_sdr */
3035 int dp_y_sd; /* hdmin[y][jp_y_vms_sdr] - vms_sd */
3036 int jp_0; /* j offset in ROOT_S's (v==0) j band */
3037 int kmin, kmax; /* min/max k */
3038
3039 /* the DP matrix */
3040 float ***alpha = mx->dp; /* pointer to the alpha DP matrix */
3041
3042 /* ptrs to cp9b info, for convenience */
3043 CP9Bands_t *cp9b = cm->cp9b;
3044 int *jmin = cp9b->jmin;
3045 int *jmax = cp9b->jmax;
3046 int **hdmin = cp9b->hdmin;
3047 int **hdmax = cp9b->hdmax;
3048
3049 /* allocate and initialize probability vectors */
3050 vec_size = ESL_MAX(L+3, ESL_MAX(cm->M, MAXCONNECT+1));
3051 /* multipurpose vectors, we need up to L+3 elements for bifs, M elements for root, 3*MAXCONNECT+1 for other states */
3052 ESL_ALLOC(pA, sizeof(float) * vec_size);
3053 ESL_ALLOC(validA, sizeof(int) * vec_size);
3054 esl_vec_FSet(pA, vec_size, IMPOSSIBLE);
3055 esl_vec_ISet(validA, vec_size, FALSE);
3056
3057 /* ensure a full alignment to ROOT_S (v==0) is possible */
3058 if (cp9b->jmin[0] > L || cp9b->jmax[0] < L) ESL_FAIL(eslEINVAL, errbuf, "cm_StochasticParsetreeHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cp9b->jmin[0], cp9b->jmax[0]);
3059 jp_0 = L - jmin[0];
3060 if (cp9b->hdmin[0][jp_0] > L || cp9b->hdmax[0][jp_0] < L) ESL_FAIL(eslEINVAL, errbuf, "cm_StochasticParsetreeHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cp9b->hdmin[0][jp_0], cp9b->hdmax[0][jp_0]);
3061
3062 /* Create a parse tree structure and initialize it by adding the root state, with appropriate mode */
3063 tr = CreateParsetree(100);
3064 InsertTraceNode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0); /* init: attach the root S */
3065
3066 /* Stochastically traceback through the TrInside matrix
3067 * this section of code is adapted from cm_dpsmall.c:insideT().
3068 */
3069 if ((pda = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; }
3070
3071 v = 0;
3072 j = d = L;
3073 i = 1;
3074 jp_v = j - jmin[v];
3075 fsc = 0.;
3076 while (1) {
3077 if (cm->sttype[v] == B_st) {
3078 y = cm->cfirst[v];
3079 z = cm->cnum[v];
3080 jp_z = j-jmin[z];
3081 k = kp_z + hdmin[z][jp_z]; /* k = offset len of right fragment */
3082
3083 /* Determine valid k values. This is complex, and
3084 * uncommented. It was taken from
3085 * cm_dpalign.c:cm_CYKInsideAlignHB(), the B_st case. The code
3086 * there is commented somewhat extensively. I'm pretty sure this
3087 * is the most efficient (or at least close to it) way to find
3088 * the valid cells in the DP matrix we're looking for.
3089 */
3090 jp_v = j - jmin[v];
3091 jp_y = j - jmin[y];
3092 jp_z = j - jmin[z];
3093 if(j < jmin[v] || j > jmax[v]) ESL_FAIL(eslFAIL, errbuf, "cm_StochasticParsetreeHB() B_st v: %d j: %d outside band jmin: %d jmax: %d\n", v, j, jmin[v], jmax[v]);
3094 if(d < hdmin[v][jp_v] || d > hdmax[v][jp_v]) ESL_FAIL(eslFAIL, errbuf, "cm_StochasticParsetreeHB() B_st v: %d j: %d d: %d outside band dmin: %d dmax: %d\n", v, j, d, hdmin[v][jp_v], hdmax[v][jp_v]);
3095 kmin = ((j-jmax[y]) > (hdmin[z][jp_z])) ? (j-jmax[y]) : hdmin[z][jp_z];
3096 kmax = ( jp_y < (hdmax[z][jp_z])) ? jp_y : hdmax[z][jp_z];
3097
3098 cur_vec_size = d+1;
3099 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE); /* only valid k's will be reset to a non-IMPOSSIBLE score */
3100
3101 /* Set pA[] as (float-ized) log odds scores for each valid right fragment length, k,
3102 * and choose a k.
3103 */
3104 for(k = kmin; k <= kmax; k++) {
3105 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
3106 kp_z = k-hdmin[z][jp_z];
3107 dp_y = d-hdmin[y][jp_y-k];
3108 pA[k] = alpha[y][jp_y-k][dp_y-k] + alpha[z][jp_z][kp_z];
3109 }
3110 }
3111 /* sample k */
3112 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (B_st) is 0.");
3113 k = choice;
3114
3115 /* Store info about the right fragment that we'll retrieve later:
3116 */
3117 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR; /* remember the end j */
3118 if((status = esl_stack_IPush(pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
3119 if((status = esl_stack_IPush(pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
3120
3121 /* Deal with attaching left start state.
3122 */
3123 j = j-k;
3124 d = d-k;
3125 i = j-d+1;
3126 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
3127 v = y;
3128 }
3129 else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
3130 /* We don't trace back from an E or EL. Instead, we're done with the
3131 * left branch of the tree, and we try to swing over to the right
3132 * branch by popping a right start off the stack and attaching
3133 * it. If the stack is empty, then we're done with the
3134 * traceback altogether. This is the only way to break the
3135 * while (1) loop.
3136 */
3137 if (esl_stack_IPop(pda, &bifparent) == eslEOD) break;
3138 esl_stack_IPop(pda, &d);
3139 esl_stack_IPop(pda, &j);
3140 v = tr->state[bifparent]; /* recover state index of B */
3141 y = cm->cnum[v]; /* find state index of right S */
3142 i = j-d+1;
3143 /* attach the S to the right */
3144 InsertTraceNode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y);
3145 v = y;
3146 }
3147 else {
3148 if((v > 0) || (! (cm->flags & CMH_LOCAL_BEGIN))) { /* not a ROOT_S or local begins are off */
3149 /* add in emission score (or 0.0 if we're a non-emitter) */
3150 fsc += get_femission_score(cm, dsq, v, i, j);
3151 sd = StateDelta(cm->sttype[v]);
3152 sdr = StateRightDelta(cm->sttype[v]);
3153
3154 /* set pA[] as (float-ized) log odds scores for each child we can transit to,
3155 * plus a local end (if possible), and choose a transition */
3156 cur_vec_size = cm->cnum[v];
3157 el_is_possible = FALSE;
3158 if((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
3159 el_is_possible = TRUE;
3160 cur_vec_size++;
3161 }
3162 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
3163 for(yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
3164 y = cm->cfirst[v] + yoffset;
3165 if((j-sdr) >= jmin[y] && (j-sdr) <= jmax[y]) { /* j-sdr is valid in y */
3166 jp_y_sdr = j - jmin[y] - sdr;
3167 if((d-sd) >= hdmin[y][jp_y_sdr] && (d-sd) <= hdmax[y][jp_y_sdr]) {
3168 dp_y_sd = d - hdmin[y][jp_y_sdr] - sd;
3169 pA[yoffset] = cm->tsc[v][yoffset] + alpha[y][jp_y_sdr][dp_y_sd];
3170 }
3171 }
3172 }
3173 if(el_is_possible) {
3174 pA[cur_vec_size-1] = cm->endsc[v] + alpha[cm->M][j][d]; /* remember EL deck is non-banded */
3175 }
3176 /* sample yoffset */
3177 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (non-B_st) is 0.");
3178 yoffset = choice;
3179 if(yoffset < cm->cnum[v]) {
3180 fsc += cm->tsc[v][yoffset];
3181 }
3182 else {
3183 yoffset = USED_EL; /* we chose EL */
3184 fsc += cm->endsc[v] + (cm->el_selfsc * (d - sd)); /* transition to EL plus score of all EL emissions */
3185 }
3186 }
3187 else { /* v == 0 && (cm->flags && CMH_LOCAL_BEGIN) ( local begins are on ) */
3188 cur_vec_size = cm->M; /* pretend all states are possible to begin into, but they're not as some will remain IMPOSSIBLE */
3189 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
3190 for(y = 0; y < cm->M; y++) {
3191 if(NOT_IMPOSSIBLE(cm->beginsc[y])) {
3192 if(j >= jmin[y] && j <= jmax[y]) { /* j is valid in y */
3193 jp_y = j - jmin[y];
3194 if(d >= hdmin[y][jp_y] && d <= hdmax[y][jp_y]) {
3195 dp_y = d - hdmin[y][jp_y];
3196 pA[y] = cm->beginsc[y] + alpha[y][jp_y][dp_y];
3197 }
3198 }
3199 }
3200 }
3201 /* sample b */
3202 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid local begins is 0.");
3203 b = choice;
3204 fsc += cm->beginsc[b];
3205 yoffset = USED_LOCAL_BEGIN;
3206 }
3207
3208 /* adjust i and j appropriately based on state type */
3209 switch (cm->sttype[v]) {
3210 case D_st: break;
3211 case MP_st: i++; j--; break;
3212 case ML_st: i++; break;
3213 case MR_st: j--; break;
3214 case IL_st: i++; break;
3215 case IR_st: j--; break;
3216 case S_st: break;
3217 default: ESL_FAIL(eslEINCONCEIVABLE, errbuf, "'Inconceivable!'\n'You keep using that word...'");
3218 }
3219 d = j-i+1;
3220
3221 if (yoffset == USED_EL) {
3222 /* a local alignment end */
3223 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M);
3224 v = cm->M; /* now we're in EL */
3225 }
3226 else if (yoffset == USED_LOCAL_BEGIN) {
3227 /* local begin; can only happen once, from root */
3228 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b);
3229 v = b;
3230 }
3231 else {
3232 y = cm->cfirst[v] + yoffset;
3233 InsertTraceNode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y);
3234 v = y;
3235 }
3236 /* ParsetreeDump(stdout, tr, cm, dsq); */
3237 }
3238 }
3239 if(pda != NULL) esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
3240 if(pA != NULL) free(pA);
3241 if(validA != NULL) free(validA);
3242
3243 #if eslDEBUGLEVEL >= 2
3244 /* ParsetreeDump(stdout, tr, cm, dsq); */
3245 float sc;
3246 ParsetreeScore(cm, cm->emap, errbuf, tr, dsq, FALSE, &sc, NULL, NULL, NULL, NULL);
3247 printf("#DEBUG: parsetree score: %f\n", sc);
3248 printf("#DEBUG: fsc: %.4f\n", fsc);
3249 #endif
3250
3251 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
3252 if(ret_sc != NULL) *ret_sc = fsc;
3253
3254 ESL_DPRINTF1(("#DEBUG: cm_StochasticParsetreeHB() return sc: %f\n", fsc));
3255 return eslOK;
3256
3257 ERROR:
3258 if(pda != NULL) esl_stack_Destroy(pda); /* it should be empty; we could check; naaah. */
3259 if(pA != NULL) free(pA);
3260 if(validA != NULL) free(validA);
3261
3262 if(tr != NULL) FreeParsetree(tr);
3263
3264 if(ret_tr != NULL) *ret_tr = NULL;
3265 if(ret_sc != NULL) *ret_sc = 0.;
3266
3267 ESL_FAIL(status, errbuf, "out of memory");
3268 return status; /* NEVER REACHED */
3269 }
3270
3271
3272 /* Function: cm_TrStochasticParsetree()
3273 * Incept: EPN, Mon Jan 9 08:58:34 2012
3274 *
3275 * Purpose: Sample a parsetree from a non-banded truncated float Inside
3276 * matrix. The Inside matrix must have been already filled by
3277 * cm_TrInsideAlign(). Based on cm_StochasticParsetree().
3278 *
3279 * Args: cm - the model
3280 * errbuf - char buffer for reporting errors
3281 * dsq - digitized sequence
3282 * L - length of dsq
3283 * preset_mode - pre-determined alignment mode, TRMODE_UNKNOWN to allow any
3284 * pass_idx - pipeline pass index, indicates what truncation penalty to use
3285 * mx - pre-calculated Inside matrix (floats)
3286 * r - source of randomness
3287 * ret_tr - RETURN: sampled parsetree
3288 * ret_mode - RETURN: mode of sampled parsetree
3289 * ret_sc - RETURN: score of sampled parsetree
3290 *
3291 * Returns: <eslOK> on success.
3292 * Throws: <eslEMEM> if we run out of memory.
3293 */
3294 int
3295 cm_TrStochasticParsetree(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, char preset_mode, int pass_idx,
3296 CM_TR_MX *mx, ESL_RANDOMNESS *r, Parsetree_t **ret_tr, char *ret_mode, float *ret_sc)
3297 {
3298 int status; /* easel status code */
3299 int v, y, z, b; /* state indices */
3300 int yoffset; /* transition offset in a states transition vector */
3301 int p; /* counter for pA */
3302 int i, j; /* sequence position indices */
3303 int d; /* j - i + 1; the current subseq length */
3304 int k; /* right subseq fragment length for bifurcs */
3305 int bifparent; /* for connecting bifurcs */
3306 Parsetree_t *tr = NULL; /* trace we're building */
3307 ESL_STACK *i_pda = NULL; /* the stack, integers */
3308 ESL_STACK *c_pda = NULL; /* the stack, characters */
3309 int vec_size; /* size of pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3310 int cur_vec_size; /* number of elements we're currently using in pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3311 float *pA = NULL; /* prob vector of possible paths to take, used for various state types */
3312 int *validA = NULL; /* is pA a valid choice? (or was it supposed to be IMPOSSIBLE) */
3313 char *y_modeA = NULL; /* y_mode[x] is alignment mode for state y corresponding to pA[x] */
3314 char *z_modeA = NULL; /* z_mode[x] is alignment mode for state z corresponding to pA[x] */
3315 int *kA = NULL; /* kA[x] is k index corresponding to pA[x], for bifurcs */
3316 int *yoffsetA = NULL; /* yoffsetA[x] is yoffset index corresponding to yoffsetA[x] */
3317 int Jel_is_possible; /* TRUE if we can jump to EL from current state in J mode (with local ends on), FALSE if not */
3318 int Lel_is_possible; /* TRUE if we can jump to EL from current state in L mode (with local ends on), FALSE if not */
3319 int Rel_is_possible; /* TRUE if we can jump to EL from current state in R mode (with local ends on), FALSE if not */
3320 float fsc = 0.; /* score of the parsetree we're sampling */
3321 int choice; /* index represeting sampled choice */
3322
3323 /* other variables used in truncated version, but not standard version (not in cm_CYKInsideAlign()) */
3324 char parsetree_mode; /* truncation mode of sampled parseetree */
3325 char v_mode, y_mode, z_mode, b_mode; /* truncation mode for states v, y, z, b */
3326 int Jntrans, Rntrans, Lntrans; /* number of transitions for current state, each mode */
3327 float *JpA = NULL; /* prob vector for possible transitions to take, J mode */
3328 float *LpA = NULL; /* prob vector for possible transitions to take, L mode */
3329 float *RpA = NULL; /* prob vector for possible transitions to take, R mode */
3330 int vms_sd, vms_sdr; /* mode-specific state delta, state right delta */
3331 int do_J, do_L, do_R, do_T; /* allow transitions to J, L, R modes from current state? */
3332 int filled_L, filled_R, filled_T; /* will we ever use L, R, and T matrices? (determined from <preset_mode>) */
3333 int allow_S_trunc_end; /* set to true to allow d==0 BEGL_S and BEGR_S truncated ends */
3334 int pty_idx; /* index for truncation penalty, determined by pass_idx */
3335 float trpenalty; /* truncation penalty, differs based on pass_idx and if we're local or global */
3336
3337 /* the DP matrix */
3338 float ***Jalpha = mx->Jdp; /* pointer to the Jalpha DP matrix */
3339 float ***Lalpha = mx->Ldp; /* pointer to the Lalpha DP matrix */
3340 float ***Ralpha = mx->Rdp; /* pointer to the Ralpha DP matrix */
3341 float ***Talpha = mx->Tdp; /* pointer to the Talpha DP matrix */
3342
3343 /* allocate and initialize probability vectors */
3344 vec_size = ESL_MAX(L+3, ESL_MAX(cm->M, 3*MAXCONNECT+1));
3345 /* multipurpose vectors, we need up to L+3 elements for bifs, M elements for root, 3*MAXCONNECT+1 for other states */
3346 ESL_ALLOC(pA, sizeof(float) * vec_size);
3347 ESL_ALLOC(validA, sizeof(int) * vec_size);
3348 ESL_ALLOC(y_modeA, sizeof(char) * vec_size);
3349 ESL_ALLOC(z_modeA, sizeof(char) * vec_size);
3350 ESL_ALLOC(kA, sizeof(int) * vec_size);
3351 ESL_ALLOC(yoffsetA, sizeof(int) * vec_size);
3352 esl_vec_FSet(pA, vec_size, IMPOSSIBLE);
3353 esl_vec_ISet(validA, vec_size, FALSE);
3354 esl_vec_ISet(kA, vec_size, 0);
3355 esl_vec_ISet(yoffsetA, vec_size, 0);
3356 for(p = 0; p < vec_size; p++) y_modeA[p] = TRMODE_UNKNOWN;
3357 for(p = 0; p < vec_size; p++) z_modeA[p] = TRMODE_UNKNOWN;
3358
3359 /* per-mode vectors */
3360 ESL_ALLOC(JpA, sizeof(float) * (MAXCONNECT+1));
3361 ESL_ALLOC(LpA, sizeof(float) * (MAXCONNECT+1));
3362 ESL_ALLOC(RpA, sizeof(float) * (MAXCONNECT+1));
3363 esl_vec_FSet(JpA, MAXCONNECT+1, 0.);
3364 esl_vec_FSet(LpA, MAXCONNECT+1, 0.);
3365 esl_vec_FSet(RpA, MAXCONNECT+1, 0.);
3366
3367 /* Determine which matrices we might use, based on <preset_mode>, if TRMODE_UNKNOWN, filled_L, filled_R, filled_T will all be set as TRUE */
3368 if((status = cm_TrFillFromMode(preset_mode, &filled_L, &filled_R, &filled_T)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetree(), bogus mode: %d", preset_mode);
3369 /* Determine truncation penalty index, from <pass_idx> */
3370 if((pty_idx = cm_tr_penalties_IdxForPass(pass_idx)) == -1) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_TrStochasticParsetree(), unexpected pass idx: %d", pass_idx);
3371
3372 /* Truncated specific step: sample alignment marginal mode if <preset_mode> == TRMODE_UNKNOWN */
3373 parsetree_mode = preset_mode;
3374 if (preset_mode == TRMODE_UNKNOWN) {
3375 cur_vec_size = 4;
3376 pA[0] = Jalpha[0][L][L]; validA[0] = TRUE;
3377 pA[1] = Lalpha[0][L][L]; validA[1] = TRUE;
3378 pA[2] = Ralpha[0][L][L]; validA[2] = TRUE;
3379 pA[3] = Talpha[0][L][L]; validA[3] = TRUE;
3380 /* sample mode */
3381 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetree() no valid alignment modes.");
3382 if (choice == 0) parsetree_mode = TRMODE_J;
3383 else if(choice == 1) parsetree_mode = TRMODE_L;
3384 else if(choice == 2) parsetree_mode = TRMODE_R;
3385 else if(choice == 3) parsetree_mode = TRMODE_T;
3386 /*printf("cm_TrStochasticParsetree() sampled %s (%g %g %g %g)\n", MarginalMode(parsetree_mode), pA[0], pA[1], pA[2], pA[3]);*/
3387 }
3388
3389 /* Create a parse tree structure and initialize it by adding the root state, with appropriate mode */
3390 tr = CreateParsetree(100);
3391 tr->is_std = FALSE; /* lower is_std flag, now we'll know this parsetree was created by a truncated (non-standard) alignment function */
3392 tr->pass_idx = pass_idx;
3393 InsertTraceNodewithMode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0, parsetree_mode); /* init: attach the root S */
3394
3395 /* Stochastically traceback through the TrInside matrix
3396 * this section of code is adapted from cm_dpsmall.c:insideT().
3397 */
3398 i_pda = esl_stack_ICreate();
3399 c_pda = esl_stack_CCreate();
3400 if(i_pda == NULL) goto ERROR;
3401 if(c_pda == NULL) goto ERROR;
3402
3403 v = 0;
3404 j = d = L;
3405 i = 1;
3406 v_mode = parsetree_mode;
3407 fsc = 0.;
3408 while (1) {
3409 /* check for super special case in truncated alignment sampling: */
3410 if(d == 0 && v_mode == TRMODE_UNKNOWN && (cm->stid[v] == BEGL_S || cm->stid[v] == BEGR_S)) {
3411 /* If d==0, v_mode is TRMODE_UNKNOWN, v is BEGL_S or BEGR_S
3412 * we've used a special case for a B_st (see that section for
3413 * details), we've emitted the full sequence under either the
3414 * BEGL_S or the BEGR_S and now we're on the other side (v is
3415 * the sister BEGR_S or BEGL_S) that emits nothing (hence d==0),
3416 * we do a truncated end and exit.
3417 */
3418 allow_S_trunc_end = TRUE; /* this sets yoffset to USED_TRUNC_END in the final 'else' of the code block below */
3419 }
3420 else {
3421 allow_S_trunc_end = FALSE;
3422 }
3423
3424 if (cm->sttype[v] == B_st) {
3425 y = cm->cfirst[v];
3426 z = cm->cnum[v];
3427
3428 cur_vec_size = d+3;
3429 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE); /* only valid k's will be reset to a non-IMPOSSIBLE score, d+1 and d+2 store special cases in L and R mode, remain invalid for J and T mode */
3430 esl_vec_ISet(kA, cur_vec_size, -1); /* only valid k's will be reset to a non -1 value */
3431 for(p = 0; p < cur_vec_size; p++) y_modeA[p] = TRMODE_UNKNOWN;
3432 for(p = 0; p < cur_vec_size; p++) z_modeA[p] = TRMODE_UNKNOWN;
3433
3434 /* Set pA[] as (float-ized) log odds scores for each valid right fragment length, k, and choose a k.
3435 * We handle each mode separately (note I checked the filled_* values are TRUE, in most cases they must be,
3436 * but we check anyway, if there's something wrong we'll catch it when we check if any validA[] values
3437 * have been set to TRUE below).
3438 */
3439 if(v_mode == TRMODE_J) {
3440 /* v is J, y and z must be J mode also */
3441 for(k = 0; k <= d; k++) {
3442 pA[k] = Jalpha[y][j-k][d-k] + Jalpha[z][j][k];
3443 kA[k] = k;
3444 y_modeA[k] = TRMODE_J;
3445 z_modeA[k] = TRMODE_J;
3446 }
3447 /* no additional special cases in J mode */
3448 }
3449 else if(v_mode == TRMODE_L && filled_L) {
3450 /* v is L, y will be J or L, z will be L */
3451 for(k = 0; k <= d; k++) {
3452 pA[k] = Jalpha[y][j-k][d-k] + Lalpha[z][j][k];
3453 kA[k] = k;
3454 y_modeA[k] = TRMODE_J;
3455 z_modeA[k] = TRMODE_L;
3456 }
3457 /* allow for the two special L cases, if they're valid */
3458 pA[d+1] = Jalpha[y][j][d]; /* entire sequence is on left in J mode, k is 0 */
3459 kA[d+1] = 0;
3460 y_modeA[d+1] = TRMODE_J;
3461 z_modeA[d+1] = TRMODE_UNKNOWN;
3462
3463 pA[d+2] = Lalpha[y][j][d]; /* entire sequence is on left in J mode, k is 0 */
3464 kA[d+2] = 0;
3465 y_modeA[d+2] = TRMODE_L;
3466 z_modeA[d+2] = TRMODE_UNKNOWN;
3467 }
3468 else if(v_mode == TRMODE_R && filled_R) {
3469 /* v is R, y will be R, z will be J or R */
3470 for(k = 0; k <= d; k++) {
3471 pA[k] = Ralpha[y][j-k][d-k] + Jalpha[z][j][k];
3472 kA[k] = k;
3473 y_modeA[k] = TRMODE_R;
3474 z_modeA[k] = TRMODE_J;
3475 }
3476 /* allow for the two special R cases, if they're valid */
3477 pA[d+1] = Jalpha[z][j][d]; /* entire sequence is on right in J mode, k is d */
3478 kA[d+1] = d;
3479 y_modeA[d+1] = TRMODE_UNKNOWN;
3480 z_modeA[d+1] = TRMODE_J;
3481
3482 pA[d+2] = Ralpha[z][j][d]; /* entire sequence is on right in J mode, k is d */
3483 kA[d+2] = d;
3484 y_modeA[d+2] = TRMODE_UNKNOWN;
3485 z_modeA[d+2] = TRMODE_R;
3486 }
3487 else if(v_mode == TRMODE_T && filled_R && filled_L) {
3488 /* v is T, y will be R, z will be L */
3489 for(k = 1; k < d; k++) {
3490 pA[k] = Ralpha[y][j-k][d-k] + Lalpha[z][j][k];
3491 kA[k] = k;
3492 y_modeA[k] = TRMODE_R;
3493 z_modeA[k] = TRMODE_L;
3494 }
3495 }
3496 /* sample k */
3497 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (B_st) is 0.");
3498 y_mode = y_modeA[choice];
3499 z_mode = z_modeA[choice];
3500 k = kA[choice];
3501 /* kA[choice] will usually be choice, unless its a special case
3502 * and v_mode is L or R mode.
3503 */
3504
3505 /* Store info about the right fragment that we'll retrieve later:
3506 */
3507 if((status = esl_stack_IPush(i_pda, j)) != eslOK) goto ERROR; /* remember the end j */
3508 if((status = esl_stack_IPush(i_pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
3509 if((status = esl_stack_IPush(i_pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
3510 if((status = esl_stack_CPush(c_pda, z_mode)) != eslOK) goto ERROR; /* remember the mode of the right fragment */
3511
3512 /* Deal with attaching left start state.
3513 */
3514 j = j-k;
3515 d = d-k;
3516 i = j-d+1;
3517 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y, y_mode);
3518 v = y;
3519 v_mode = y_mode;
3520 }
3521 else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
3522 /* We don't trace back from an E or EL. Instead, we're done with the
3523 * left branch of the tree, and we try to swing over to the right
3524 * branch by popping a right start off the stack and attaching
3525 * it. If the stack is empty, then we're done with the
3526 * traceback altogether. This is the only way to break the
3527 * while (1) loop.
3528 */
3529 if (esl_stack_IPop(i_pda, &bifparent) == eslEOD) break;
3530 esl_stack_IPop(i_pda, &d);
3531 esl_stack_IPop(i_pda, &j);
3532 esl_stack_CPop(c_pda, &y_mode);
3533 v = tr->state[bifparent]; /* recover state index of B */
3534 y = cm->cnum[v]; /* find state index of right S */
3535 i = j-d+1;
3536 /* attach the S to the right */
3537 InsertTraceNodewithMode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y, y_mode);
3538 v = y;
3539 v_mode = y_mode;
3540 }
3541 else {
3542 /* v != B_st && v != E_st && v != EL_st */
3543 if (v == 0) { /* ROOT_S, we choose a truncated begin state, irregardless of whether we're in local or global mode */
3544 /* determine which modes we can transition to, we're an S state, so only same-mode transitions are possible */
3545 do_J = (v_mode == TRMODE_J) ? TRUE : FALSE;
3546 do_L = (v_mode == TRMODE_L) ? TRUE : FALSE;
3547 do_R = (v_mode == TRMODE_R) ? TRUE : FALSE;
3548 do_T = (v_mode == TRMODE_T) ? TRUE : FALSE;
3549 /* note: exactly 1 of do_J, do_L, do_R, do_T will be TRUE */
3550
3551 cur_vec_size = cm->M; /* pretend all states are possible to begin into, but they're not as some will remain IMPOSSIBLE */
3552 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
3553 for(y = 0; y < cm->M; y++) {
3554 trpenalty = (cm->flags & CMH_LOCAL_BEGIN) ? cm->trp->l_ptyAA[pty_idx][y] : cm->trp->g_ptyAA[pty_idx][y];
3555 if(NOT_IMPOSSIBLE(trpenalty)) {
3556 if(do_J) pA[y] = trpenalty + Jalpha[y][j][d];
3557 if(filled_L && do_L) pA[y] = trpenalty + Lalpha[y][j][d];
3558 if(filled_R && do_R) pA[y] = trpenalty + Ralpha[y][j][d];
3559 if(filled_T && do_T && cm->sttype[y] == B_st) {
3560 pA[y] = trpenalty + Talpha[y][j][d];
3561 }
3562 }
3563 }
3564 /* sample b */
3565 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid local begins is 0.");
3566 b = choice;
3567 b_mode = v_mode; /* can't change mode out of a S_st */
3568 trpenalty = (cm->flags & CMH_LOCAL_BEGIN) ? cm->trp->l_ptyAA[pty_idx][b] : cm->trp->g_ptyAA[pty_idx][b];
3569 fsc += trpenalty;
3570 yoffset = USED_TRUNC_BEGIN;
3571
3572 /* set the truncation penalty parameter of the parsetree */
3573 tr->trpenalty = trpenalty;
3574 }
3575 else { /* standard case: v != 0 && v != E_st && v != EL_st && v != B_st */
3576 /* add in emission score (or 0.0 if we're a non-emitter) */
3577 fsc += get_femission_score_trunc(cm, dsq, v, i, j, v_mode); /* this is okay even if allow_S_trunc_end is TRUE (b/c then we're a silent S_st and add 0.0) */
3578 /* check for special cases:
3579 * special case 1: allow_S_trunc_end == TRUE (set above if d==0, v_mode is TRMODE_UNKNOWN, v is BEGL_S or BEGR_S)
3580 * special case 2: d==1, v_mode is TRMODE_L, v emits left
3581 * special case 3: d==1, v_mode is TRMODE_R, v emits right
3582 * In all 3 cases, we use a truncated end and don't transition anywhere.
3583 * See comments above where allow_S_trunc_end is set for details on first
3584 * case.
3585 * Second and third cases allow truncated alignments to end at any point
3586 * in the parsetree (as long as full sequence is emitted).
3587 */
3588 if(allow_S_trunc_end) { /* this was set above if d==0, stid = BEGL_S or BEGR_S and v_mode == TRMODE_UNKNOWN */
3589 yoffset = USED_TRUNC_END;
3590 y_mode = TRMODE_UNKNOWN; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
3591 }
3592 else if(d == 1 && v_mode == TRMODE_L && StateLeftDelta(cm->sttype[v]) == 1) { /* special case 1 */
3593 yoffset = USED_TRUNC_END;
3594 y_mode = TRMODE_L; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
3595 }
3596 else if(d == 1 && v_mode == TRMODE_R && StateRightDelta(cm->sttype[v]) == 1) { /* special case 2 */
3597 yoffset = USED_TRUNC_END;
3598 y_mode = TRMODE_R; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
3599 }
3600 else { /* usual case, determine where we transition and go there */
3601 /* determine mode-specific state delta values, and which modes we can transition to */
3602 if(v_mode == TRMODE_J) {
3603 vms_sd = StateDelta(cm->sttype[v]);
3604 vms_sdr = StateRightDelta(cm->sttype[v]);
3605 do_J = TRUE;
3606 do_L = FALSE;
3607 do_R = FALSE;
3608 }
3609 else if(v_mode == TRMODE_L) {
3610 vms_sd = StateLeftDelta(cm->sttype[v]);
3611 vms_sdr = 0;
3612 do_J = (StateRightDelta(cm->sttype[v]) == 1) ? TRUE : FALSE; /* can transition from L to J mode only if a right emitter */
3613 do_L = TRUE;
3614 do_R = FALSE;
3615 }
3616 else if(v_mode == TRMODE_R) {
3617 vms_sd = StateRightDelta(cm->sttype[v]);
3618 vms_sdr = StateRightDelta(cm->sttype[v]);
3619 do_J = (StateLeftDelta(cm->sttype[v]) == 1) ? TRUE : FALSE; /* can transition from R to J mode only if a left emitter */
3620 do_L = FALSE;
3621 do_R = TRUE;
3622 }
3623
3624 /* fill JpA, LpA and RpA with log odds scores for each child we can transit to,
3625 * add a local end in any mode (if possible) */
3626 Jntrans = (do_J) ? cm->cnum[v] : 0;
3627 Lntrans = (do_L) ? cm->cnum[v] : 0;
3628 Rntrans = (do_R) ? cm->cnum[v] : 0;
3629 Jel_is_possible = FALSE;
3630 Lel_is_possible = FALSE;
3631 Rel_is_possible = FALSE;
3632 if((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
3633 if(do_J) { Jel_is_possible = TRUE; Jntrans++; }
3634 if(do_L) { Lel_is_possible = TRUE; Lntrans++; }
3635 if(do_R) { Rel_is_possible = TRUE; Rntrans++; }
3636 }
3637 /* init JpA, LpA, RpA */
3638 esl_vec_FSet(JpA, MAXCONNECT+1, IMPOSSIBLE);
3639 esl_vec_FSet(LpA, MAXCONNECT+1, IMPOSSIBLE);
3640 esl_vec_FSet(RpA, MAXCONNECT+1, IMPOSSIBLE);
3641 /* fill JpA, LpA, RpA separately */
3642 for(yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
3643 y = cm->cfirst[v] + yoffset;
3644 if(do_J) JpA[yoffset] = cm->tsc[v][yoffset] + Jalpha[y][j-vms_sdr][d-vms_sd];
3645 if(filled_L && do_L) LpA[yoffset] = cm->tsc[v][yoffset] + Lalpha[y][j-vms_sdr][d-vms_sd];
3646 if(filled_R && do_R) RpA[yoffset] = cm->tsc[v][yoffset] + Ralpha[y][j-vms_sdr][d-vms_sd];
3647 }
3648 if(Jel_is_possible) JpA[Jntrans-1] = cm->endsc[v] + Jalpha[cm->M][j][d]; /* remember EL deck is non-banded */
3649 if(Lel_is_possible) LpA[Lntrans-1] = cm->endsc[v] + Lalpha[cm->M][j][d]; /* remember EL deck is non-banded */
3650 if(Rel_is_possible) RpA[Rntrans-1] = cm->endsc[v] + Ralpha[cm->M][j][d]; /* remember EL deck is non-banded */
3651
3652 /* create one big vector of all possibilities, and for convenience keep track of mode and mode-specific index (q) of each */
3653 cur_vec_size = Jntrans + Lntrans + Rntrans;
3654 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
3655 p = 0;
3656 for(yoffset = 0; yoffset < Jntrans; yoffset++) { pA[p] = JpA[yoffset]; y_modeA[p] = TRMODE_J; yoffsetA[p] = yoffset; p++; }
3657 for(yoffset = 0; yoffset < Lntrans; yoffset++) { pA[p] = LpA[yoffset]; y_modeA[p] = TRMODE_L; yoffsetA[p] = yoffset; p++; }
3658 for(yoffset = 0; yoffset < Rntrans; yoffset++) { pA[p] = RpA[yoffset]; y_modeA[p] = TRMODE_R; yoffsetA[p] = yoffset; p++; }
3659
3660 /* sample yoffset */
3661 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of valid transitions (non B_st) is 0.");
3662 y_mode = y_modeA[choice];
3663 yoffset = yoffsetA[choice];
3664 if((y_mode == TRMODE_J && Jel_is_possible && yoffset == (Jntrans-1)) ||
3665 (y_mode == TRMODE_L && Lel_is_possible && yoffset == (Lntrans-1)) ||
3666 (y_mode == TRMODE_R && Rel_is_possible && yoffset == (Rntrans-1))) {
3667 yoffset = USED_EL; /* we chose EL */
3668 fsc += cm->endsc[v] + (cm->el_selfsc * (d - StateDelta(cm->sttype[v]))); /* transition to EL plus score of all EL emissions */
3669 }
3670 else {
3671 fsc += cm->tsc[v][yoffset];
3672 }
3673 }
3674 }
3675
3676 /* adjust i and j appropriately based on state type and mode */
3677 switch (cm->sttype[v]) {
3678 case D_st:
3679 case S_st:
3680 break;
3681 case MP_st:
3682 if ( v_mode == TRMODE_J ) i++;
3683 if ( v_mode == TRMODE_L && d > 0 ) i++;
3684 if ( v_mode == TRMODE_J ) j--;
3685 if ( v_mode == TRMODE_R && d > 0 ) j--;
3686 break;
3687 case ML_st:
3688 if ( v_mode == TRMODE_J ) i++;
3689 if ( v_mode == TRMODE_L && d > 0 ) i++;
3690 break;
3691 case MR_st:
3692 if ( v_mode == TRMODE_J ) j--;
3693 if ( v_mode == TRMODE_R && d > 0 ) j--;
3694 break;
3695 case IL_st:
3696 if ( v_mode == TRMODE_J ) i++;
3697 if ( v_mode == TRMODE_L && d > 0 ) i++;
3698 break;
3699 case IR_st:
3700 if ( v_mode == TRMODE_J ) j--;
3701 if ( v_mode == TRMODE_R && d > 0 ) j--;
3702 break;
3703 default: ESL_FAIL(eslEINVAL, errbuf, "bogus state type %d \n", cm->sttype[v]);
3704 }
3705 d = j-i+1;
3706
3707 if (yoffset == USED_EL || yoffset == USED_TRUNC_END) {
3708 /* a local alignment end or a truncation end */
3709 if(yoffset == USED_EL) {
3710 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M, y_mode);
3711 }
3712 v = cm->M; /* now we're in EL (if USED_TRUNC_END, we act like we are) */
3713 v_mode = y_mode;
3714 }
3715 else if (yoffset == USED_TRUNC_BEGIN) {
3716 /* truncated begin; can only happen once, from root */
3717 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b, b_mode);
3718 v = b;
3719 v_mode = b_mode;
3720 }
3721 else {
3722 y = cm->cfirst[v] + yoffset;
3723 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y, y_mode);
3724 v = y;
3725 v_mode = y_mode;
3726 }
3727 /* ParsetreeDump(stdout, tr, cm, dsq); */
3728 }
3729 }
3730 if(i_pda != NULL) esl_stack_Destroy(i_pda); /* it should be empty; we could check; naaah. */
3731 if(c_pda != NULL) esl_stack_Destroy(c_pda); /* it should be empty; we could check; naaah. */
3732 if(pA != NULL) free(pA);
3733 if(validA != NULL) free(validA);
3734 if(y_modeA != NULL) free(y_modeA);
3735 if(z_modeA != NULL) free(z_modeA);
3736 if(kA != NULL) free(kA);
3737 if(yoffsetA != NULL) free(yoffsetA);
3738 if(JpA != NULL) free(JpA);
3739 if(LpA != NULL) free(LpA);
3740 if(RpA != NULL) free(RpA);
3741
3742 #if eslDEBUGLEVEL >= 2
3743 /* ParsetreeDump(stdout, tr, cm, dsq); */
3744 float sc;
3745 ParsetreeScore(cm, cm->emap, errbuf, tr, dsq, FALSE, &sc, NULL, NULL, NULL, NULL);
3746 printf("#DEBUG: parsetree score: %.4f\n", sc);
3747 printf("#DEBUG: fsc: %.4f\n", fsc);
3748 #endif
3749
3750 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
3751 if(ret_mode != NULL) *ret_mode = parsetree_mode;
3752 if(ret_sc != NULL) *ret_sc = fsc;
3753
3754 ESL_DPRINTF1(("#DEBUG: cm_TrStochasticParsetree() return sc: %f\n", fsc));
3755 return eslOK;
3756
3757 ERROR:
3758 if(i_pda != NULL) esl_stack_Destroy(i_pda); /* it should be empty; we could check; naaah. */
3759 if(c_pda != NULL) esl_stack_Destroy(c_pda); /* it should be empty; we could check; naaah. */
3760 if(pA != NULL) free(pA);
3761 if(validA != NULL) free(validA);
3762 if(y_modeA != NULL) free(y_modeA);
3763 if(z_modeA != NULL) free(z_modeA);
3764 if(kA != NULL) free(kA);
3765 if(yoffsetA != NULL) free(yoffsetA);
3766 if(JpA != NULL) free(JpA);
3767 if(LpA != NULL) free(LpA);
3768 if(RpA != NULL) free(RpA);
3769
3770 if(tr != NULL) FreeParsetree(tr);
3771
3772 if(ret_tr != NULL) *ret_tr = NULL;
3773 if(ret_mode != NULL) *ret_mode = TRMODE_UNKNOWN;
3774 if(ret_sc != NULL) *ret_sc = 0.;
3775
3776 ESL_FAIL(status, errbuf, "out of memory");
3777 return status; /* NEVER REACHED */
3778 }
3779
3780 /* Function: cm_TrStochasticParsetreeHB()
3781 * Incept: EPN, Tue Jan 10 05:56:55 2012
3782 *
3783 * Purpose: Sample a parsetree from a HMM banded truncated float
3784 * Inside matrix. The Inside matrix must have been already
3785 * filled by cm_TrInsideAlignHB(). Based on
3786 * cm_StochasticParsetreeHB(), analogous to
3787 * cm_TrStochasticParsetree() but uses HMM bands.
3788 *
3789 * Args: cm - the model
3790 * errbuf - char buffer for reporting errors
3791 * dsq - digitized sequence
3792 * L - length of dsq
3793 * preset_mode - pre-determined alignment mode, TRMODE_UNKNOWN to allow any
3794 * pass_idx - pipeline pass index, indicates what truncation penalty to use
3795 * mx - pre-calculated Inside matrix (floats)
3796 * r - source of randomness
3797 * ret_tr - RETURN: sampled parsetree
3798 * ret_mode - RETURN: mode of sampled parsetree
3799 * ret_sc - RETURN: score of sampled parsetree
3800 *
3801 * Returns: <eslOK> on success.
3802 * Throws: <eslEMEM> if we run out of memory.
3803 */
3804 int
3805 cm_TrStochasticParsetreeHB(CM_t *cm, char *errbuf, ESL_DSQ *dsq, int L, char preset_mode, int pass_idx,
3806 CM_TR_HB_MX *mx, ESL_RANDOMNESS *r, Parsetree_t **ret_tr, char *ret_mode, float *ret_sc)
3807 {
3808 int status; /* easel status code */
3809 int v, y, z, b; /* state indices */
3810 int yoffset; /* transition offset in a states transition vector */
3811 int p; /* counter for pA */
3812 int i, j; /* sequence position indices */
3813 int d; /* j - i + 1; the current subseq length */
3814 int k; /* right subseq fragment length for bifurcs */
3815 int bifparent; /* for connecting bifurcs */
3816 Parsetree_t *tr = NULL; /* trace we're building */
3817 ESL_STACK *i_pda = NULL; /* the stack, integers */
3818 ESL_STACK *c_pda = NULL; /* the stack, characters */
3819 int vec_size; /* size of pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3820 int cur_vec_size; /* number of elements we're currently using in pA, validA, y_modeA, z_modeA, kA, yoffsetA */
3821 float *pA = NULL; /* prob vector of possible paths to take, used for various state types */
3822 int *validA = NULL; /* is pA a valid choice? (or was it supposed to be IMPOSSIBLE) */
3823 char *y_modeA = NULL; /* y_mode[x] is alignment mode for state y corresponding to pA[x] */
3824 char *z_modeA = NULL; /* z_mode[x] is alignment mode for state z corresponding to pA[x] */
3825 int *kA = NULL; /* kA[x] is k index corresponding to pA[x], for bifurcs */
3826 int *yoffsetA = NULL; /* yoffsetA[x] is yoffset index corresponding to yoffsetA[x] */
3827 int Jel_is_possible; /* TRUE if we can jump to EL from current state in J mode (with local ends on), FALSE if not */
3828 int Lel_is_possible; /* TRUE if we can jump to EL from current state in L mode (with local ends on), FALSE if not */
3829 int Rel_is_possible; /* TRUE if we can jump to EL from current state in R mode (with local ends on), FALSE if not */
3830 float fsc = 0.; /* score of the parsetree we're sampling */
3831 int choice; /* index represeting sampled choice */
3832
3833 /* other variables used in truncated version, but not standard version (not in cm_StochasticParsetree() */
3834 char parsetree_mode; /* truncation mode of sampled parseetree */
3835 char v_mode, y_mode, z_mode, b_mode; /* truncation mode for states v, y, z, b */
3836 int Jntrans, Rntrans, Lntrans; /* number of transitions for current state, each mode */
3837 float *JpA = NULL; /* prob vector for possible transitions to take, J mode */
3838 float *LpA = NULL; /* prob vector for possible transitions to take, L mode */
3839 float *RpA = NULL; /* prob vector for possible transitions to take, R mode */
3840 int vms_sd, vms_sdr; /* mode-specific state delta, state right delta */
3841 int do_J, do_L, do_R, do_T; /* allow transitions to J, L, R modes from current state? */
3842 int filled_L, filled_R, filled_T; /* will we ever use L, R, and T matrices? (determined from <preset_mode>) */
3843 int allow_S_trunc_end; /* set to true to allow d==0 BEGL_S and BEGR_S truncated ends, even if outside bands */
3844 int pty_idx; /* index for truncation penalty, determined by pass_idx */
3845 float trpenalty; /* truncation penalty, differs based on pass_idx and if we're local or global */
3846
3847 /* variables used in HMM banded version but no nonbanded version */
3848 int jp_v; /* j - jmin[v] */
3849 int jp_y, dp_y ; /* j - jmin[y], d - hdmin[y][jp_y] */
3850 int jp_z, kp_z; /* j - jmin[z], d - hdmin[z][jp_z] */
3851 int dp_z; /* d - hdmin[z][jp_z] */
3852 int jp_y_vms_sdr; /* j - jmin[y] - vms_sdr */
3853 int dp_y_vms_sd; /* hdmin[y][jp_y_vms_sdr] - vms_sd */
3854 int jp_0; /* L offset in ROOT_S's (v==0) j band */
3855 int Lp_0; /* L offset in ROOT_S's (v==0) d band */
3856 int kmin, kmax; /* min/max k */
3857 int kn, kx; /* min/max k in T mode */
3858
3859 /* the DP matrix */
3860 float ***Jalpha = mx->Jdp; /* pointer to the Jalpha DP matrix */
3861 float ***Lalpha = mx->Ldp; /* pointer to the Lalpha DP matrix */
3862 float ***Ralpha = mx->Rdp; /* pointer to the Ralpha DP matrix */
3863 float ***Talpha = mx->Tdp; /* pointer to the Talpha DP matrix */
3864
3865 /* ptrs to cp9b info, for convenience */
3866 CP9Bands_t *cp9b = cm->cp9b;
3867 int *jmin = cp9b->jmin;
3868 int *jmax = cp9b->jmax;
3869 int **hdmin = cp9b->hdmin;
3870 int **hdmax = cp9b->hdmax;
3871
3872 /* allocate and initialize probability vectors */
3873 vec_size = ESL_MAX(L+3, ESL_MAX(cm->M, 3*MAXCONNECT+1));
3874 /* multipurpose vectors, we need up to L+3 elements for bifs, M elements for root, 3*MAXCONNECT+1 for other states */
3875 ESL_ALLOC(pA, sizeof(float) * vec_size);
3876 ESL_ALLOC(validA, sizeof(int) * vec_size);
3877 ESL_ALLOC(y_modeA, sizeof(char) * vec_size);
3878 ESL_ALLOC(z_modeA, sizeof(char) * vec_size);
3879 ESL_ALLOC(kA, sizeof(int) * vec_size);
3880 ESL_ALLOC(yoffsetA, sizeof(int) * vec_size);
3881 esl_vec_FSet(pA, vec_size, IMPOSSIBLE);
3882 esl_vec_ISet(validA, vec_size, FALSE);
3883 esl_vec_ISet(kA, vec_size, 0);
3884 esl_vec_ISet(yoffsetA, vec_size, 0);
3885 for(p = 0; p < vec_size; p++) y_modeA[p] = TRMODE_UNKNOWN;
3886 for(p = 0; p < vec_size; p++) z_modeA[p] = TRMODE_UNKNOWN;
3887
3888 /* per-mode vectors */
3889 ESL_ALLOC(JpA, sizeof(float) * (MAXCONNECT+1));
3890 ESL_ALLOC(LpA, sizeof(float) * (MAXCONNECT+1));
3891 ESL_ALLOC(RpA, sizeof(float) * (MAXCONNECT+1));
3892 esl_vec_FSet(JpA, MAXCONNECT+1, 0.);
3893 esl_vec_FSet(LpA, MAXCONNECT+1, 0.);
3894 esl_vec_FSet(RpA, MAXCONNECT+1, 0.);
3895
3896 /* Determine which matrices we might use, based on <preset_mode>, if TRMODE_UNKNOWN, filled_L, filled_R, filled_T will all be set as TRUE */
3897 if((status = cm_TrFillFromMode(preset_mode, &filled_L, &filled_R, &filled_T)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetreeHB(), bogus mode: %d", preset_mode);
3898 /* Determine truncation penalty index, from <pass_idx> */
3899 if((pty_idx = cm_tr_penalties_IdxForPass(pass_idx)) == -1) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_TrStochasticParsetreeHB(), unexpected pass idx: %d", pass_idx);
3900
3901 /* ensure a full alignment to ROOT_S (v==0) is possible */
3902 if (preset_mode == TRMODE_J && (! cp9b->Jvalid[0])) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB()(): preset_mode is J mode, but cp9b->Jvalid[v] is FALSE");
3903 if (preset_mode == TRMODE_L && (! cp9b->Lvalid[0])) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB()(): preset_mode is L mode, but cp9b->Lvalid[v] is FALSE");
3904 if (preset_mode == TRMODE_R && (! cp9b->Rvalid[0])) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB()(): preset_mode is R mode, but cp9b->Rvalid[v] is FALSE");
3905 if (preset_mode == TRMODE_T && (! cp9b->Tvalid[0])) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB()(): preset_mode is T mode, but cp9b->Tvalid[v] is FALSE");
3906 if (preset_mode == TRMODE_UNKNOWN && (! (cp9b->Jvalid[0] || cp9b->Lvalid[0] || cp9b->Rvalid[0] || cp9b->Tvalid[0]))) {
3907 ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB()(): no marginal mode is allowed for state 0");
3908 }
3909 if (cp9b->jmin[0] > L || cp9b->jmax[0] < L) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB(): L (%d) is outside ROOT_S's j band (%d..%d)\n", L, cp9b->jmin[0], cp9b->jmax[0]);
3910 jp_0 = L - jmin[0];
3911 if (cp9b->hdmin[0][jp_0] > L || cp9b->hdmax[0][jp_0] < L) ESL_FAIL(eslEINVAL, errbuf, "cm_TrStochasticParsetreeHB(): L (%d) is outside ROOT_S's d band (%d..%d)\n", L, cp9b->hdmin[0][jp_0], cp9b->hdmax[0][jp_0]);
3912 Lp_0 = L - hdmin[0][jp_0];
3913
3914 /* Truncated specific step: sample alignment marginal mode if <preset_mode> == TRMODE_UNKNOWN */
3915 parsetree_mode = preset_mode;
3916 if (preset_mode == TRMODE_UNKNOWN) {
3917 cur_vec_size = 4;
3918 if(cp9b->Jvalid[0]) pA[0] = Jalpha[0][jp_0][Lp_0];
3919 if(cp9b->Lvalid[0]) pA[1] = Lalpha[0][jp_0][Lp_0];
3920 if(cp9b->Rvalid[0]) pA[2] = Ralpha[0][jp_0][Lp_0];
3921 if(cp9b->Tvalid[0]) pA[3] = Talpha[0][jp_0][Lp_0];
3922 /* sample mode */
3923 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetreeHB() no valid alignment modes.");
3924 if (choice == 0) parsetree_mode = TRMODE_J;
3925 else if(choice == 1) parsetree_mode = TRMODE_L;
3926 else if(choice == 2) parsetree_mode = TRMODE_R;
3927 else if(choice == 3) parsetree_mode = TRMODE_T;
3928 /*printf("cm_TrStochasticParsetreeHB() sampled %s (%g %g %g %g)\n", MarginalMode(parsetree_mode), pA[0], pA[1], pA[2], pA[3]);*/
3929 }
3930
3931 /* Create a parse tree structure and initialize it by adding the root state, with appropriate mode */
3932 tr = CreateParsetree(100);
3933 tr->is_std = FALSE; /* lower is_std flag, now we'll know this parsetree was created by a truncated (non-standard) alignment function */
3934 tr->pass_idx = pass_idx;
3935 InsertTraceNodewithMode(tr, -1, TRACE_LEFT_CHILD, 1, L, 0, parsetree_mode); /* init: attach the root S */
3936
3937 /* Stochastically traceback through the TrInside matrix
3938 * this section of code is adapted from cm_dpsmall.c:insideT().
3939 */
3940 i_pda = esl_stack_ICreate();
3941 c_pda = esl_stack_CCreate();
3942 if(i_pda == NULL) goto ERROR;
3943 if(c_pda == NULL) goto ERROR;
3944
3945 v = 0;
3946 j = d = L;
3947 i = 1;
3948 v_mode = parsetree_mode;
3949 jp_v = j - jmin[v];
3950 fsc = 0.;
3951 while (1) {
3952 /* check for super special case in truncated alignment sampling: */
3953 if(d == 0 && v_mode == TRMODE_UNKNOWN && (cm->stid[v] == BEGL_S || cm->stid[v] == BEGR_S)) {
3954 /* If d==0, v_mode is TRMODE_UNKNOWN, v is BEGL_S or BEGR_S
3955 * we've used a special case for a B_st (see that section for
3956 * details), we've emitted the full sequence under either the
3957 * BEGL_S or the BEGR_S and now we're on the other side (v is
3958 * the sister BEGR_S or BEGL_S) that emits nothing (hence d==0),
3959 * we do a truncated end and exit. We may be outside our bands
3960 * on v and/or j, but we allow that for this special case.
3961 */
3962 allow_S_trunc_end = TRUE; /* this sets yoffset to USED_TRUNC_END in the final 'else' of the code block below */
3963 }
3964 else if(cm->sttype[v] != EL_st) {
3965 /* update all-important jp_v (j band-offset index) */
3966 jp_v = j - jmin[v];
3967 allow_S_trunc_end = FALSE;
3968 /* check for errors */
3969 if(j > jmax[v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), j: %d > jmax[%d] (%d)\n", j, v, jmax[v]);
3970 if(j < jmin[v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), j: %d < jmin[%d] (%d)\n", j, v, jmin[v]);
3971 if(d > hdmax[v][jp_v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), d: %d > hdmax[%d] (%d)\n", d, v, hdmax[v][jp_v]);
3972 if(d < hdmin[v][jp_v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), d: %d < hdmin[%d] (%d)\n", d, v, hdmin[v][jp_v]);
3973 if(v_mode == TRMODE_J && (! cp9b->Jvalid[v])) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), mode is TRMODE_J for v: %d but cp9b->Jvalid[v] is FALSE", v);
3974 if(v_mode == TRMODE_L && (! cp9b->Lvalid[v])) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), mode is TRMODE_L for v: %d but cp9b->Lvalid[v] is FALSE", v);
3975 if(v_mode == TRMODE_R && (! cp9b->Rvalid[v])) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), mode is TRMODE_R for v: %d but cp9b->Rvalid[v] is FALSE", v);
3976 if(v_mode == TRMODE_T && (! cp9b->Tvalid[v])) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB(), mode is TRMODE_T for v: %d but cp9b->Tvalid[v] is FALSE", v);
3977 }
3978
3979 if (cm->sttype[v] == B_st) {
3980 y = cm->cfirst[v];
3981 z = cm->cnum[v];
3982 jp_z = j-jmin[z];
3983 k = kp_z + hdmin[z][jp_z]; /* k = offset len of right fragment */
3984
3985 /* Determine valid k values, this is mode-independent. This is
3986 * complex, and uncommented. It was taken from
3987 * cm_dpalign.c:cm_CYKInsideAlignHB(), the B_st case. The code
3988 * there is commented somewhat extensively. I'm pretty sure this
3989 * is the most efficient (or at least close to it) way to find
3990 * the valid cells in the DP matrix we're looking for.
3991 */
3992 jp_v = j - jmin[v];
3993 jp_y = j - jmin[y];
3994 jp_z = j - jmin[z];
3995 if(j < jmin[v] || j > jmax[v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB() B_st v: %d j: %d outside band jmin: %d jmax: %d\n", v, j, jmin[v], jmax[v]);
3996 if(d < hdmin[v][jp_v] || d > hdmax[v][jp_v]) ESL_FAIL(eslFAIL, errbuf, "cm_TrStochasticParsetreeHB() B_st v: %d j: %d d: %d outside band dmin: %d dmax: %d\n", v, j, d, hdmin[v][jp_v], hdmax[v][jp_v]);
3997 kmin = ((j-jmax[y]) > (hdmin[z][jp_z])) ? (j-jmax[y]) : hdmin[z][jp_z];
3998 kmax = ( jp_y < (hdmax[z][jp_z])) ? jp_y : hdmax[z][jp_z];
3999
4000 cur_vec_size = d+3;
4001 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE); /* only valid k's will be reset to a non-IMPOSSIBLE score, d+1 and d+2 store special cases in L and R mode, remain invalid for J and T mode */
4002 esl_vec_ISet(kA, cur_vec_size, -1); /* only valid k's will be reset to a non -1 value */
4003 for(p = 0; p < cur_vec_size; p++) y_modeA[p] = TRMODE_UNKNOWN;
4004 for(p = 0; p < cur_vec_size; p++) z_modeA[p] = TRMODE_UNKNOWN;
4005
4006 /* set pA[] as (float-ized) log odds scores for each valid right fragment length, k, and choose a k */
4007 /* handle each mode separately */
4008 if(v_mode == TRMODE_J) {
4009 /* v is J, y and z must be J mode also */
4010 if(cp9b->Jvalid[y] && cp9b->Jvalid[z]) {
4011 for(k = kmin; k <= kmax; k++) {
4012 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
4013 kp_z = k-hdmin[z][jp_z];
4014 dp_y = d-hdmin[y][jp_y-k];
4015 pA[k] = Jalpha[y][jp_y-k][dp_y-k] + Jalpha[z][jp_z][kp_z];
4016 kA[k] = k;
4017 y_modeA[k] = TRMODE_J;
4018 z_modeA[k] = TRMODE_J;
4019 }
4020 }
4021 }
4022 /* no additional special cases in J mode */
4023 }
4024 else if(v_mode == TRMODE_L) {
4025 /* v is L, y will be J or L, z will be L */
4026 if(filled_L && cp9b->Jvalid[y] && cp9b->Lvalid[z]) {
4027 for(k = kmin; k <= kmax; k++) {
4028 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
4029 kp_z = k-hdmin[z][jp_z];
4030 dp_y = d-hdmin[y][jp_y-k];
4031 pA[k] = Jalpha[y][jp_y-k][dp_y-k] + Lalpha[z][jp_z][kp_z];
4032 kA[k] = k;
4033 y_modeA[k] = TRMODE_J;
4034 z_modeA[k] = TRMODE_L;
4035 }
4036 }
4037 }
4038 /* allow for the two special L cases, if they're valid */
4039 if(j >= jmin[y] && j <= jmax[y]) { /* j is valid in y */
4040 jp_y = j-jmin[y];
4041 if(d >= hdmin[y][jp_y] && d <= hdmax[y][jp_y]) { /* d is valid in j, y */
4042 dp_y = d - hdmin[y][jp_y];
4043 if(cp9b->Jvalid[y]) {
4044 pA[d+1] = Jalpha[y][jp_y][dp_y]; /* entire sequence is on left in J mode, k is 0 */
4045 kA[d+1] = 0;
4046 y_modeA[d+1] = TRMODE_J;
4047 z_modeA[d+1] = TRMODE_UNKNOWN;
4048 }
4049 if(filled_L && cp9b->Lvalid[y]) {
4050 pA[d+2] = Lalpha[y][jp_y][dp_y]; /* entire sequence is on left in L mode, k is 0 */
4051 kA[d+2] = 0;
4052 y_modeA[d+2] = TRMODE_L;
4053 z_modeA[d+2] = TRMODE_UNKNOWN;
4054 }
4055 }
4056 }
4057 }
4058 else if(v_mode == TRMODE_R) {
4059 /* v is R, y will be R, z will be J or R */
4060 if(filled_R && cp9b->Rvalid[y] && cp9b->Jvalid[z]) {
4061 for(k = kmin; k <= kmax; k++) {
4062 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
4063 kp_z = k-hdmin[z][jp_z];
4064 dp_y = d-hdmin[y][jp_y-k];
4065 pA[k] = Ralpha[y][jp_y-k][dp_y-k] + Jalpha[z][jp_z][kp_z];
4066 kA[k] = k;
4067 y_modeA[k] = TRMODE_R;
4068 z_modeA[k] = TRMODE_J;
4069 }
4070 }
4071 }
4072 /* allow for the two special R cases, if they're valid */
4073 if(j >= jmin[z] && j <= jmax[z]) {
4074 jp_z = j-jmin[z];
4075 if(d >= hdmin[z][jp_z] && d <= hdmax[z][jp_z]) {
4076 dp_z = d - hdmin[z][jp_z];
4077 if(cp9b->Jvalid[z]) {
4078 pA[d+1] = Jalpha[z][jp_z][dp_z]; /* entire sequence is on right in J mode, k is d */
4079 kA[d+1] = d;
4080 y_modeA[d+1] = TRMODE_UNKNOWN;
4081 z_modeA[d+1] = TRMODE_J;
4082 }
4083 if(filled_R && cp9b->Rvalid[z]) {
4084 pA[d+2] = Ralpha[z][jp_z][dp_z]; /* entire sequence is on right in J mode, k is d */
4085 kA[d+2] = d;
4086 y_modeA[d+2] = TRMODE_UNKNOWN;
4087 z_modeA[d+2] = TRMODE_R;
4088 }
4089 }
4090 }
4091 }
4092 else if(v_mode == TRMODE_T) {
4093 /* v is T, y will be R, z will be L */
4094 if(filled_R && filled_L && cp9b->Rvalid[y] && cp9b->Lvalid[z]) {
4095 kn = ESL_MAX(kmin, 1);
4096 kx = ESL_MIN(kmax, d);
4097 for(k = kn; k <= kx; k++) {
4098 if((k >= d - hdmax[y][jp_y-k]) && k <= d - hdmin[y][jp_y-k]) {
4099 kp_z = k-hdmin[z][jp_z];
4100 dp_y = d-hdmin[y][jp_y-k];
4101 pA[k] = Ralpha[y][jp_y-k][dp_y-k] + Lalpha[z][jp_z][kp_z];
4102 kA[k] = k;
4103 y_modeA[k] = TRMODE_R;
4104 z_modeA[k] = TRMODE_L;
4105 }
4106 }
4107 }
4108 }
4109
4110 /* sample k */
4111 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetreeHB() number of transitions (B_st) is 0.");
4112 y_mode = y_modeA[choice];
4113 z_mode = z_modeA[choice];
4114 k = kA[choice];
4115 /* kA[choice] will usually be choice, unless its a special case
4116 * and v_mode is L or R mode.
4117 */
4118
4119 /* Store info about the right fragment that we'll retrieve later:
4120 */
4121 if((status = esl_stack_IPush(i_pda, j)) != eslOK) goto ERROR; /* remember the end j */
4122 if((status = esl_stack_IPush(i_pda, k)) != eslOK) goto ERROR; /* remember the subseq length k */
4123 if((status = esl_stack_IPush(i_pda, tr->n-1)) != eslOK) goto ERROR; /* remember the trace index of the parent B state */
4124 if((status = esl_stack_CPush(c_pda, z_mode)) != eslOK) goto ERROR; /* remember the mode of the right fragment */
4125
4126 /* Deal with attaching left start state.
4127 */
4128 j = j-k;
4129 d = d-k;
4130 i = j-d+1;
4131 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y, y_mode);
4132 v = y;
4133 v_mode = y_mode;
4134 }
4135 else if (cm->sttype[v] == E_st || cm->sttype[v] == EL_st) {
4136 /* We don't trace back from an E or EL. Instead, we're done with the
4137 * left branch of the tree, and we try to swing over to the right
4138 * branch by popping a right start off the stack and attaching
4139 * it. If the stack is empty, then we're done with the
4140 * traceback altogether. This is the only way to break the
4141 * while (1) loop.
4142 */
4143 if (esl_stack_IPop(i_pda, &bifparent) == eslEOD) break;
4144 esl_stack_IPop(i_pda, &d);
4145 esl_stack_IPop(i_pda, &j);
4146 esl_stack_CPop(c_pda, &y_mode);
4147 v = tr->state[bifparent]; /* recover state index of B */
4148 y = cm->cnum[v]; /* find state index of right S */
4149 i = j-d+1;
4150 /* attach the S to the right */
4151 InsertTraceNodewithMode(tr, bifparent, TRACE_RIGHT_CHILD, i, j, y, y_mode);
4152 v = y;
4153 v_mode = y_mode;
4154 }
4155 else {
4156 /* v != B_st && v != E_st && v != EL_st */
4157 if (v == 0) { /* ROOT_S, we choose a truncated begin state, irregardless of whether we're in local or global mode */
4158 /* determine which modes we can transition to, we're an S state, so only same-mode transitions are possible */
4159 do_J = (v_mode == TRMODE_J) ? TRUE : FALSE;
4160 do_L = (v_mode == TRMODE_L) ? TRUE : FALSE;
4161 do_R = (v_mode == TRMODE_R) ? TRUE : FALSE;
4162 do_T = (v_mode == TRMODE_T) ? TRUE : FALSE;
4163 /* note: exactly 1 of do_J, do_L, do_R, do_T will be TRUE */
4164
4165 cur_vec_size = cm->M; /* pretend all states are possible to begin into, but they're not as some will remain IMPOSSIBLE */
4166 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
4167 for(y = 0; y < cm->M; y++) {
4168 if(j >= jmin[y] && j <= jmax[y]) { /* j is valid in y */
4169 jp_y = j - jmin[y];
4170 if(d >= hdmin[y][jp_y] && d <= hdmax[y][jp_y]) {
4171 dp_y = d - hdmin[y][jp_y];
4172 trpenalty = (cm->flags & CMH_LOCAL_BEGIN) ? cm->trp->l_ptyAA[pty_idx][y] : cm->trp->g_ptyAA[pty_idx][y];
4173 if(NOT_IMPOSSIBLE(trpenalty)) {
4174 if( do_J && cp9b->Jvalid[y]) pA[y] = trpenalty + Jalpha[y][jp_y][dp_y];
4175 if(filled_L && do_L && cp9b->Lvalid[y]) pA[y] = trpenalty + Lalpha[y][jp_y][dp_y];
4176 if(filled_R && do_R && cp9b->Rvalid[y]) pA[y] = trpenalty + Ralpha[y][jp_y][dp_y];
4177 if(filled_T && do_T && cp9b->Tvalid[y] && cm->sttype[y] == B_st) {
4178 pA[y] = trpenalty + Talpha[y][jp_y][dp_y];
4179 }
4180 }
4181 }
4182 }
4183 }
4184 /* sample b */
4185 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_StochasticParsetree() number of local begins is 0.");
4186 b = choice;
4187 b_mode = v_mode; /* can't change mode out of a S_st */
4188 trpenalty = (cm->flags & CMH_LOCAL_BEGIN) ? cm->trp->l_ptyAA[pty_idx][b] : cm->trp->g_ptyAA[pty_idx][b];
4189 fsc += trpenalty;
4190 yoffset = USED_TRUNC_BEGIN;
4191 /* set the truncation penalty parameter of the parsetree */
4192 tr->trpenalty = trpenalty;
4193 }
4194 else { /* standard case: v != 0 && v != E_st && v != EL_st && v != B_st */
4195 /* add in emission score (or 0.0 if we're a non-emitter) */
4196 fsc += get_femission_score_trunc(cm, dsq, v, i, j, v_mode); /* this is okay even if allow_S_trunc_end is TRUE (b/c then we're a silent S_st and add 0.0) */
4197 /* check for special cases:
4198 * special case 1: allow_S_trunc_end == TRUE (set above if d==0, v_mode is TRMODE_UNKNOWN, v is BEGL_S or BEGR_S)
4199 * special case 2: d==1, v_mode is TRMODE_L, v emits left
4200 * special case 3: d==1, v_mode is TRMODE_R, v emits right
4201 * In all 3 cases, we use a truncated end and don't transition anywhere.
4202 * See comments above where allow_S_trunc_end is set for details on first
4203 * case.
4204 * Second and third cases allow truncated alignments to end at any point
4205 * in the parsetree (as long as full sequence is emitted).
4206 */
4207 if(allow_S_trunc_end) { /* this was set above if d==0, stid = BEGL_S or BEGR_S and v_mode == TRMODE_UNKNOWN */
4208 yoffset = USED_TRUNC_END;
4209 y_mode = TRMODE_UNKNOWN; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
4210 }
4211 else if(d == 1 && v_mode == TRMODE_L && StateLeftDelta(cm->sttype[v]) == 1) { /* special case 1 */
4212 yoffset = USED_TRUNC_END;
4213 y_mode = TRMODE_L; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
4214 }
4215 else if(d == 1 && v_mode == TRMODE_R && StateRightDelta(cm->sttype[v]) == 1) { /* special case 2 */
4216 yoffset = USED_TRUNC_END;
4217 y_mode = TRMODE_R; /* necessary only b/c we check mode below to distinguish USED_TRUNC_END from USED_EL */
4218 }
4219 else { /* usual case, determine where we transition and go there */
4220 /* determine mode-specific state delta values, and which modes we can transition to */
4221 if(v_mode == TRMODE_J) {
4222 vms_sd = StateDelta(cm->sttype[v]);
4223 vms_sdr = StateRightDelta(cm->sttype[v]);
4224 do_J = TRUE;
4225 do_L = FALSE;
4226 do_R = FALSE;
4227 }
4228 else if(v_mode == TRMODE_L) {
4229 vms_sd = StateLeftDelta(cm->sttype[v]);
4230 vms_sdr = 0;
4231 do_J = (StateRightDelta(cm->sttype[v]) == 1) ? TRUE : FALSE; /* can transition from L to J mode only a right emitter */
4232 do_L = TRUE;
4233 do_R = FALSE;
4234 }
4235 else if(v_mode == TRMODE_R) {
4236 vms_sd = StateRightDelta(cm->sttype[v]);
4237 vms_sdr = StateRightDelta(cm->sttype[v]);
4238 do_J = (StateLeftDelta(cm->sttype[v]) == 1) ? TRUE : FALSE; /* can transition from R to J mode only a leftt emitter */
4239 do_L = FALSE;
4240 do_R = TRUE;
4241 }
4242
4243 /* fill JpA, LpA and RpA with log odds scores for each child we can transit to,
4244 * add a local end in J mode (if possible) */
4245 Jntrans = (do_J) ? cm->cnum[v] : 0;
4246 Lntrans = (do_L) ? cm->cnum[v] : 0;
4247 Rntrans = (do_R) ? cm->cnum[v] : 0;
4248 Jel_is_possible = FALSE;
4249 Lel_is_possible = FALSE;
4250 Rel_is_possible = FALSE;
4251 if((cm->flags & CMH_LOCAL_END) && NOT_IMPOSSIBLE(cm->endsc[v])) {
4252 if(do_J && cp9b->Jvalid[cm->M]) { Jel_is_possible = TRUE; Jntrans++; }
4253 if(do_L && cp9b->Lvalid[cm->M]) { Lel_is_possible = TRUE; Lntrans++; }
4254 if(do_R && cp9b->Rvalid[cm->M]) { Rel_is_possible = TRUE; Rntrans++; }
4255 }
4256 /* init JpA, LpA, RpA */
4257 esl_vec_FSet(JpA, MAXCONNECT+1, IMPOSSIBLE);
4258 esl_vec_FSet(LpA, MAXCONNECT+1, IMPOSSIBLE);
4259 esl_vec_FSet(RpA, MAXCONNECT+1, IMPOSSIBLE);
4260 /* fill JpA, LpA, RpA separately */
4261 for(yoffset = 0; yoffset < cm->cnum[v]; yoffset++) {
4262 y = cm->cfirst[v] + yoffset;
4263 if((j-vms_sdr) >= jmin[y] && (j-vms_sdr) <= jmax[y]) { /* j-vms_sdr is valid in y */
4264 jp_y_vms_sdr = j - jmin[y] - vms_sdr;
4265 if((d-vms_sd) >= hdmin[y][jp_y_vms_sdr] && (d-vms_sd) <= hdmax[y][jp_y_vms_sdr]) {
4266 dp_y_vms_sd = d - hdmin[y][jp_y_vms_sdr] - vms_sd;
4267 if( do_J && cp9b->Jvalid[y]) JpA[yoffset] = cm->tsc[v][yoffset] + Jalpha[y][jp_y_vms_sdr][dp_y_vms_sd];
4268 if(filled_L && do_L && cp9b->Lvalid[y]) LpA[yoffset] = cm->tsc[v][yoffset] + Lalpha[y][jp_y_vms_sdr][dp_y_vms_sd];
4269 if(filled_R && do_R && cp9b->Rvalid[y]) RpA[yoffset] = cm->tsc[v][yoffset] + Ralpha[y][jp_y_vms_sdr][dp_y_vms_sd];
4270 }
4271 }
4272 }
4273 if(Jel_is_possible) JpA[Jntrans-1] = cm->endsc[v] + Jalpha[cm->M][j][d]; /* remember EL deck is non-banded */
4274 if(Lel_is_possible) LpA[Lntrans-1] = cm->endsc[v] + Lalpha[cm->M][j][d]; /* remember EL deck is non-banded */
4275 if(Rel_is_possible) RpA[Rntrans-1] = cm->endsc[v] + Ralpha[cm->M][j][d]; /* remember EL deck is non-banded */
4276
4277 /* create one big vector of all possibilities, and for convenience keep track of mode and mode-specific index (q) of each */
4278 cur_vec_size = Jntrans + Lntrans + Rntrans;
4279 esl_vec_FSet(pA, cur_vec_size, IMPOSSIBLE);
4280 p = 0;
4281 for(yoffset = 0; yoffset < Jntrans; yoffset++) { pA[p] = JpA[yoffset]; y_modeA[p] = TRMODE_J; yoffsetA[p] = yoffset; p++; }
4282 for(yoffset = 0; yoffset < Lntrans; yoffset++) { pA[p] = LpA[yoffset]; y_modeA[p] = TRMODE_L; yoffsetA[p] = yoffset; p++; }
4283 for(yoffset = 0; yoffset < Rntrans; yoffset++) { pA[p] = RpA[yoffset]; y_modeA[p] = TRMODE_R; yoffsetA[p] = yoffset; p++; }
4284
4285 /* sample yoffset */
4286 if((status = sample_helper(r, pA, validA, cur_vec_size, &choice)) != eslOK) ESL_FAIL(status, errbuf, "cm_TrStochasticParsetreeHB() number of transitions (non-B_st) is 0.");
4287 y_mode = y_modeA[choice];
4288 yoffset = yoffsetA[choice];
4289 if((y_mode == TRMODE_J && Jel_is_possible && yoffset == (Jntrans-1)) ||
4290 (y_mode == TRMODE_L && Lel_is_possible && yoffset == (Lntrans-1)) ||
4291 (y_mode == TRMODE_R && Rel_is_possible && yoffset == (Rntrans-1))) {
4292 yoffset = USED_EL; /* we chose EL */
4293 fsc += cm->endsc[v] + (cm->el_selfsc * (d - StateDelta(cm->sttype[v]))); /* transition to EL plus score of all EL emissions */
4294 }
4295 else {
4296 fsc += cm->tsc[v][yoffset];
4297 }
4298 }
4299 }
4300
4301 /* adjust i and j appropriately based on state type and mode */
4302 switch (cm->sttype[v]) {
4303 case D_st:
4304 case S_st:
4305 break;
4306 case MP_st:
4307 if ( v_mode == TRMODE_J ) i++;
4308 if ( v_mode == TRMODE_L && d > 0 ) i++;
4309 if ( v_mode == TRMODE_J ) j--;
4310 if ( v_mode == TRMODE_R && d > 0 ) j--;
4311 break;
4312 case ML_st:
4313 if ( v_mode == TRMODE_J ) i++;
4314 if ( v_mode == TRMODE_L && d > 0 ) i++;
4315 break;
4316 case MR_st:
4317 if ( v_mode == TRMODE_J ) j--;
4318 if ( v_mode == TRMODE_R && d > 0 ) j--;
4319 break;
4320 case IL_st:
4321 if ( v_mode == TRMODE_J ) i++;
4322 if ( v_mode == TRMODE_L && d > 0 ) i++;
4323 break;
4324 case IR_st:
4325 if ( v_mode == TRMODE_J ) j--;
4326 if ( v_mode == TRMODE_R && d > 0 ) j--;
4327 break;
4328 default: ESL_FAIL(eslEINVAL, errbuf, "bogus state type %d \n", cm->sttype[v]);
4329 }
4330 d = j-i+1;
4331
4332 if (yoffset == USED_EL || yoffset == USED_TRUNC_END) {
4333 /* a local alignment end or a truncation end */
4334 if(yoffset == USED_EL) {
4335 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, cm->M, y_mode);
4336 }
4337 v = cm->M; /* now we're in EL (if USED_TRUNC_END, we act like we are) */
4338 v_mode = y_mode;
4339 }
4340 else if (yoffset == USED_TRUNC_BEGIN) {
4341 /* truncated begin; can only happen once, from root */
4342 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, b, b_mode);
4343 v = b;
4344 v_mode = b_mode;
4345 }
4346 else {
4347 y = cm->cfirst[v] + yoffset;
4348 InsertTraceNodewithMode(tr, tr->n-1, TRACE_LEFT_CHILD, i, j, y, y_mode);
4349 v = y;
4350 v_mode = y_mode;
4351 }
4352 /* ParsetreeDump(stdout, tr, cm, dsq); */
4353 }
4354 }
4355 if(i_pda != NULL) esl_stack_Destroy(i_pda); /* it should be empty; we could check; naaah. */
4356 if(c_pda != NULL) esl_stack_Destroy(c_pda); /* it should be empty; we could check; naaah. */
4357 if(pA != NULL) free(pA);
4358 if(validA != NULL) free(validA);
4359 if(y_modeA != NULL) free(y_modeA);
4360 if(z_modeA != NULL) free(z_modeA);
4361 if(kA != NULL) free(kA);
4362 if(yoffsetA != NULL) free(yoffsetA);
4363 if(JpA != NULL) free(JpA);
4364 if(LpA != NULL) free(LpA);
4365 if(RpA != NULL) free(RpA);
4366
4367 #if eslDEBUGLEVEL >= 2
4368 /* ParsetreeDump(stdout, tr, cm, dsq); */
4369 float sc;
4370 ParsetreeScore(cm, cm->emap, errbuf, tr, dsq, FALSE, &sc, NULL, NULL, NULL, NULL);
4371 printf("#DEBUG: parsetree score: %f\n", sc);
4372 printf("#DEBUG: fsc: %.4f\n", fsc);
4373 #endif
4374
4375 if(ret_tr != NULL) *ret_tr = tr; else FreeParsetree(tr);
4376 if(ret_mode != NULL) *ret_mode = parsetree_mode;
4377 if(ret_sc != NULL) *ret_sc = fsc;
4378
4379 ESL_DPRINTF1(("#DEBUG: cm_TrStochasticParsetreeHB() return sc: %f\n", fsc));
4380 return eslOK;
4381
4382 ERROR:
4383 if(i_pda != NULL) esl_stack_Destroy(i_pda); /* it should be empty; we could check; naaah. */
4384 if(c_pda != NULL) esl_stack_Destroy(c_pda); /* it should be empty; we could check; naaah. */
4385 if(pA != NULL) free(pA);
4386 if(validA != NULL) free(validA);
4387 if(y_modeA != NULL) free(y_modeA);
4388 if(z_modeA != NULL) free(z_modeA);
4389 if(kA != NULL) free(kA);
4390 if(yoffsetA != NULL) free(yoffsetA);
4391 if(JpA != NULL) free(JpA);
4392 if(LpA != NULL) free(LpA);
4393 if(RpA != NULL) free(RpA);
4394
4395 if(tr != NULL) FreeParsetree(tr);
4396
4397 if(ret_tr != NULL) *ret_tr = NULL;
4398 if(ret_mode != NULL) *ret_mode = TRMODE_UNKNOWN;
4399 if(ret_sc != NULL) *ret_sc = 0.;
4400
4401 ESL_FAIL(status, errbuf, "out of memory");
4402 return status; /* NEVER REACHED */
4403 }
4404
4405
4406 /* Function: cm_parsetree_Doctor()
4407 * Incept: EPN, Mon Apr 23 12:48:32 2012
4408 * SRE, Thu May 21 08:45:46 2009 [p7_trace_Doctor()]
4409 *
4410 * Purpose: CMs with zero basepairs are parameterized similarly to
4411 * Plan 7 HMMs, so we can use the ML p7 HMM with fast HMM
4412 * algorithms and approximate the CM as closely as
4413 * possible. This means we need to disallow MATL_D->MATL_IL
4414 * and MATL_IL->MATL_D transitions, as explained below in
4415 * the notes from p7_trace_Doctor() from hmmer.
4416 *
4417 * We should only enter this function if our CM has zero
4418 * basepairs, in which case we'll only have three types of
4419 * nodes in the CM: MATL nodes, 1 ROOT node and 1 END node.
4420 * The only types of D->I transitions we'll have will be
4421 * MATL_D->MATL_IL. We can have three types of I->D
4422 * transitions, MATL_IL->MATL_D or ROOT_IL->MATL_D or
4423 * ROOT_IR->MATL_D. We only remove the first type
4424 * (MATL_IL->MATL_D). Normally, later on in the build
4425 * process we'll zero out any transitions involving ROOT_IL
4426 * and ROOT_IR states in cm_zero_flanking_insert_counts().
4427 *
4428 * There are three possibilities for the truncation
4429 * modes of the nodes:
4430 * 1. all TRMODE_J nodes ending with an END_nd
4431 * 2. all TRMODE_L nodes not ending with an END_nd
4432 * 3. starts in TRMODE_R and switches to TRMODE_J at some
4433 * point (should be after 2 nodes ROOT_S and then first
4434 * MATL_ML) and stays TRMODE_J until the end, and final
4435 * node is an END_nd.
4436 * Case 3 is rare but happens if the first nt is emitted from
4437 * a IL state, because the implementation of Transmogrify()
4438 * makes it so the transition from ROOT_S is to the MATL_ML
4439 * above the node with the IL in TRMODE_R.
4440 *
4441 * We verify we have one of these 3 cases and fail with an
4442 * error if not.
4443 *
4444 * HMMER's p7_trace_Doctor() notes:
4445 * Plan 7 disallows D->I and I->D "chatter" transitions.
4446 * However, these transitions will be implied by many
4447 * alignments. trace_doctor() arbitrarily collapses I->D or
4448 * D->I into a single M position in the trace.
4449 *
4450 * trace_doctor does not examine any scores when it does
4451 * this. In ambiguous situations (D->I->D) the symbol
4452 * will be pulled arbitrarily to the left, regardless
4453 * of whether that's the best column to put it in or not.
4454 *
4455 * Args: tr - trace to doctor
4456 * opt_ndi - optRETURN: number of DI transitions doctored
4457 * opt_nid - optRETURN: number of ID transitions doctored
4458 *
4459 * Return: <eslOK> on success, and the parsetree <tr> is modified.
4460 *
4461 * Throws: <eslEINVAL> if parsetree has any states other than
4462 * ROOT_S, ROOT_IL, ROOT_IR, END_E, MATL_ML, MATL_IL, MATL_D;
4463 * errbuf filled.
4464 */
4465 int
4466 cm_parsetree_Doctor(CM_t *cm, char *errbuf, Parsetree_t *tr, int *opt_ndi, int *opt_nid)
4467 {
4468 int opos; /* position in old parsetree */
4469 int npos; /* position in new parsetree (<= opos) */
4470 int x; /* position ctr in parsetree */
4471 int ndi, nid; /* number of DI, ID transitions doctored */
4472 int mode; /* truncation mode of the parsetree, it should be either all J or all L */
4473 int final_non_end; /* final parsetree node that is NOT an END_E */
4474 int mode_case; /* 1, 2, or 3, case of truncation modes */
4475 int start_node; /* node to start overwrite at, if mode_case is 1 or 2, this will be 0, else it will be 2 */
4476
4477 /* determine which of the 3 cases we have regarding truncation modes:
4478 * 1. all nodes are TRMODE_J
4479 * 2. all nodes are TRMODE_L
4480 * 3. first two nodes are TRMODE_R, all remaining nodes TRMODE_J
4481 */
4482 /* check for case 1 */
4483 mode_case = 1;
4484 for(x = 0; x < tr->n; x++) {
4485 if(tr->mode[x] != TRMODE_J) {
4486 mode_case = -1;
4487 x = tr->n;
4488 }
4489 }
4490 if(mode_case == -1) {
4491 /* not case 1 */
4492 mode_case = 2;
4493 for(x = 0; x < tr->n; x++) {
4494 if(tr->mode[x] != TRMODE_L) {
4495 mode_case = -1;
4496 x = tr->n;
4497 }
4498 }
4499 }
4500 if(mode_case == -1) {
4501 /* not case 1 or 2 */
4502 mode_case = 3; /* first two nodes are ROOT_S and MATL_ML both in TRMODE_R */
4503 if((tr->mode[0] == TRMODE_R) && (tr->mode[1] == TRMODE_R) && (cm->stid[tr->state[0]] == ROOT_S) && (cm->stid[tr->state[1]] == MATL_ML)) {
4504 /* the rest should be TRMODE_J */
4505 for(x = 2; x < tr->n; x++) {
4506 if(tr->mode[x] != TRMODE_J) {
4507 mode_case = -1;
4508 x = tr->n;
4509 }
4510 }
4511 }
4512 }
4513 if(mode_case == -1) {
4514 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() unable to determine case of truncation mode");
4515 }
4516
4517 if(mode_case == 1) {
4518 mode = TRMODE_J;
4519 start_node = 0;
4520 final_non_end = tr->n-2;
4521 if(cm->stid[tr->state[tr->n-1]] != END_E) {
4522 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() case 1 mode J parsetree doesn't end with an END_E state\n");
4523 }
4524 }
4525 else if(mode_case == 2) {
4526 mode = TRMODE_L;
4527 start_node = 0;
4528 final_non_end = tr->n-1;
4529 if(cm->stid[tr->state[tr->n-1]] == END_E) {
4530 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() case 2 mode L parsetree ends with an END_E state\n");
4531 }
4532 }
4533 else { /* mode_case = 3 */
4534 mode = TRMODE_J;
4535 start_node = 2;
4536 final_non_end = tr->n-2;
4537 if(cm->stid[tr->state[tr->n-1]] != END_E) {
4538 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() case 3 parsetree doesn't end with an END_E state\n");
4539 }
4540 }
4541
4542 /* should start with ROOT_S */
4543 if(cm->stid[tr->state[0]] != ROOT_S) {
4544 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() parsetree doesn't begin with a ROOT_S state\n");
4545 }
4546 /* validate the parsetree, should be ROOT_S->[ROOT_IL]_n->[ROOT_IR]_n->[MATL_{M,I,D}]_n
4547 * further if mode is TRMODE_J, final node should be END_E, otherwise it should NOT be END_E
4548 */
4549 x = 1;
4550 while(cm->stid[tr->state[x]] == ROOT_IL || cm->stid[tr->state[x]] == ROOT_IR) {
4551 x++;
4552 if(x >= tr->n) {
4553 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() parsetree is all ROOT states\n");
4554 }
4555 }
4556 /* all remaining states should be MATL_ML, MATL_IL, or MATL_D states until the END_E (if we have one) */
4557 for(; x <= final_non_end; x++) {
4558 if((cm->stid[tr->state[x]] != MATL_ML) &&
4559 (cm->stid[tr->state[x]] != MATL_IL) &&
4560 (cm->stid[tr->state[x]] != MATL_D)) {
4561 ESL_FAIL(eslEINVAL, errbuf, "cm_parsetree_Doctor() unexpected state id %s at position %d\n", CMStateid(cm->stid[tr->state[x]]), x);
4562 }
4563 }
4564
4565 /* overwrite the trace from left to right */
4566 ndi = nid = 0;
4567 opos = npos = start_node; /* will be '0' if case 1 or 2, '2' if case 3, for case 3, leave first two nodes untouched */
4568 while (opos < tr->n) {
4569 /* first set data that is predetermined since we know we're all MATL nodes:
4570 * mode: always TRMODE_J or TRMODE_L (we already checked), stored in mode from above
4571 * nxtl: always points to next position (except for final node, which we'll fix at end)
4572 * nxtr: always -1
4573 * prv: always npos-1
4574 * emitr: always == tr->emitr[opos] (only right emitters we'll have are ROOT_IRs)
4575 * at next parsetree node.
4576 */
4577 tr->mode[npos] = mode;
4578 tr->nxtl[npos] = npos+1;
4579 tr->nxtr[npos] = -1;
4580 tr->prv[npos] = npos-1; /* even correct for npos == 0 */
4581 tr->emitr[npos] = tr->emitr[opos]; /* this never changes */
4582
4583 /* fix implied D->I transitions; D transforms to M, I pulled in */
4584 if ((opos < (tr->n-1)) && (cm->stid[tr->state[opos]] == MATL_D) && (cm->stid[tr->state[opos+1]] == MATL_IL)) {
4585 tr->state[npos] = tr->state[opos] - 1; /* MATL_D --> MATL_ML */
4586 tr->emitl[npos] = tr->emitl[opos+1]; /* insert char moves back */
4587 opos += 2;
4588 npos += 1;
4589 ndi++;
4590 } /* fix implied I->D transitions; D transforms to M, I is pushed in */
4591 else if ((opos < (tr->n-1)) && (cm->stid[tr->state[opos]] == MATL_IL) && (cm->stid[tr->state[opos+1]] == MATL_D)) {
4592 tr->state[npos] = tr->state[opos+1] - 1; /* MATL_D --> MATL_ML */
4593 tr->emitl[npos] = tr->emitl[opos]; /* insert char moves back */
4594 opos += 2;
4595 npos += 1;
4596 nid++;
4597 } /* else, we just copy state and emitl */
4598 else {
4599 tr->state[npos] = tr->state[opos];
4600 tr->emitl[npos] = tr->emitl[opos];
4601 opos++;
4602 npos++;
4603 }
4604 }
4605 tr->n = npos;
4606 /* fix nxtl and possible emitr for the final node */
4607 tr->nxtl[tr->n-1] = -1;
4608 if((mode_case == 1) || (mode_case == 3)) { /* cases 1 and 3 only case that ends with END_E */
4609 /* emitr for END_E are always -1 */
4610 tr->emitr[tr->n-1] = -1;
4611 }
4612
4613 /* we don't have to worry about changing anything else
4614 * (i.e. is_std, nalloc, memblock, pass_idx, trpenalty)
4615 */
4616
4617 if (opt_ndi != NULL) *opt_ndi = ndi;
4618 if (opt_nid != NULL) *opt_nid = nid;
4619 return eslOK;
4620 }
4621
4622
4623 /* Function: get_femission_score()
4624 * Incept: EPN, Thu Nov 15 16:48:56 2007
4625 *
4626 * Purpose: Given a CM, dsq, state index and coordinates return the float emission
4627 * score.
4628 *
4629 * Args: cm - the model
4630 * dsq - digitized sequence
4631 * v - state index
4632 * i - dsq index for first position of subseq for subtree at v
4633 * j - dsq index for last position of subseq for subtree at v
4634 *
4635 * Return: float emission score, 0 if state is non-emitter.
4636 */
4637 float
4638 get_femission_score(CM_t *cm, ESL_DSQ *dsq, int v, int i, int j)
4639 {
4640 if (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) return cm->oesc[v][dsq[i]];
4641 else if(cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) return cm->oesc[v][dsq[j]];
4642 else if(cm->sttype[v] == MP_st) return cm->oesc[v][dsq[i]*cm->abc->Kp+dsq[j]];
4643 else return 0.;
4644 }
4645
4646 /* Function: get_femission_score_trunc()
4647 * Incept: EPN, Mon Jan 9 09:19:38 2012
4648 *
4649 * Purpose: Given a CM, dsq, state index, alignment mode and
4650 * coordinates return the float emission score.
4651 *
4652 * Args: cm - the model
4653 * dsq - digitized sequence
4654 * v - state index
4655 * i - dsq index for first position of subseq for subtree at v
4656 * j - dsq index for last position of subseq for subtree at v
4657 * mode - marginal mode
4658 *
4659 * Return: float emission score, 0 if state is non-emitter.
4660 */
4661 float
4662 get_femission_score_trunc(CM_t *cm, ESL_DSQ *dsq, int v, int i, int j, char mode)
4663 {
4664 switch(cm->sttype[v]) {
4665 case ML_st:
4666 case IL_st:
4667 if(ModeEmitsLeft(mode)) return cm->oesc[v][dsq[i]];
4668 else return 0.;
4669 break;
4670 case MR_st:
4671 case IR_st:
4672 if(ModeEmitsRight(mode)) return cm->oesc[v][dsq[j]];
4673 else return 0.;
4674 break;
4675 case MP_st:
4676 if (ModeEmitsLeft(mode) && ModeEmitsRight(mode)) return cm->oesc[v][dsq[i]*cm->abc->Kp+dsq[j]];
4677 else if(ModeEmitsLeft(mode)) return cm->lmesc[v][dsq[i]];
4678 else if(ModeEmitsRight(mode)) return cm->rmesc[v][dsq[j]];
4679 break;
4680 default:
4681 return 0.;
4682 }
4683 return 0.; /* never reached */
4684 }
4685
4686 /* Function: sample_helper()
4687 * Incept: EPN, Sat Jan 14 17:17:52 2012
4688 *
4689 * Purpose: Given a non-normalized log_2 probability vector, convert it
4690 * to probabilities, normalize it and make a choice. Return
4691 * the choice in <*ret_choice>.
4692 *
4693 * Args: r - source of randomness
4694 * pA - [0..i..n-1] non-normalized, log_2 prob vector
4695 * validA - [0..i..n-1] pre'alloced vector for storing validity of i
4696 * n - size of pA, validA
4697 * ret_choice - RETURN: chosen i from pA, 0..n-1, pA[i] is ! IMPOSSIBLE
4698 *
4699 * Return: eslOK on success.
4700 * eslEINVAL if all n elements of pA are IMPOSSIBLE
4701 */
4702 float
4703 sample_helper(ESL_RANDOMNESS *r, float *pA, int *validA, int n, int *ret_choice)
4704 {
4705 int i;
4706 int seen_valid;
4707 float maxsc;
4708
4709 /* determine which elements in pA are valid by checking if they're IMPOSSIBLE */
4710 esl_vec_ISet(validA, n, FALSE);
4711 for(i = 0; i < n; i++) { if(NOT_IMPOSSIBLE(pA[i])) validA[i] = TRUE; }
4712 /* make sure we have at least one valid choice */
4713 seen_valid = FALSE;
4714 for(i = 0; i < n; i++) { if(validA[i] == TRUE) { seen_valid = TRUE; break; } }
4715 if(! seen_valid) return eslEINVAL;
4716
4717 /* normalize and make the choice
4718 * note: pA likely has log-odds scores, but we can treat them as log
4719 * probs,because the log probability of the null model is the same
4720 * for each, so essentially we've divided each score by the same
4721 * constant, so the *relative* proportion of the log odds scores is
4722 * the same as the relative proportion of the log probabilities (seq
4723 * | model)
4724 */
4725 maxsc = esl_vec_FMax (pA, n);
4726 esl_vec_FIncrement (pA, n, (-1. * maxsc));
4727 esl_vec_FScale (pA, n, log(2.));
4728 esl_vec_FLogNorm (pA, n);
4729 do { i = esl_rnd_FChoose (r, pA, n); } while(validA[i] == FALSE);
4730
4731 *ret_choice = i;
4732 return eslOK;
4733 }