Debian Codegraph @

src/cm_modelmaker.c

raw symbols SCIP
1 /* cm_modelmaker.c
2 * SRE, 28 Feb 2000
3 *
4 * Construct a model from an alignment.
5 *
6 * Outline of the process:
7 * 1. construct a "guide" tree (gtr) for the alignment,
8 * specifying which columns are match vs. insert and
9 * how the model tree branches.
10 * 2. The guide tree is converted to a CM by cm_from_guide().
11 * 3. Individual tracebacks are constructed from individual
12 * aligned sequences by transmogrify().
13 * 4. The individual tracebacks are counted into a new model
14 * with ParsetreeCount().
15 *
16 * The CM containing counts is returned. The caller has to assign a
17 * prior to it, and convert it to probabilities; then assign a null
18 * model to it and convert to log-odds scores.
19 *
20 * The "guide tree" is a special use of a Parsetree_t structure.
21 * - tr->state contains a node type (e.g. MATP_nd), not a state index.
22 * - The numbering of the guide tree is a preorder traverse, identical to
23 * the numbering in the final CM.
24 * - emitl and emitr are relative to the alignment columns, not individual
25 * sequence positions.
26 */
27
28 #include <esl_config.h>
29 #include <p7_config.h>
30 #include "config.h"
31
32 #include <stdlib.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <ctype.h>
36
37 #include "easel.h"
38 #include "esl_msa.h"
39 #include "esl_stack.h"
40 #include "esl_vectorops.h"
41 #include "esl_wuss.h"
42
43 #include "hmmer.h"
44
45 #include "infernal.h"
46
47 static int check_for_pknots(char *cs, int alen);
48 static int check_for_el(const ESL_DSQ *ax, const ESL_ALPHABET *abc, const int *used_el, const int *nxt_mi, const int *nxt_el, int i0, int j0, int *ret_goto_el, int *ret_i, int *ret_j);
49 static int trunc_mode_for_trace_node(int emitl, int emitr, int spos, int epos);
50
51 /* Function: HandModelmaker()
52 * Incept: SRE 29 Feb 2000 [Seattle]; from COVE 2.0 code
53 *
54 * Purpose: The customer always knows best.
55 *
56 * Construct a model given a stated structure. The structure
57 * is provided via a "ss_cons" (consensus structure) line, as would
58 * occur in an annotated SELEX or Stockholm file. Only > and < characters
59 * in this line are interpreted (as base pairs). Pseudoknots,
60 * if annotated, are ignored.
61 *
62 * Match vs. insert can be determined one of three ways,
63 * depending on the values of <use_rf> and <use_wts>.
64 * 1. <use_rf> == FALSE and <use_wts> == TRUE:
65 * Default. The assignment is made by <gapthresh>; for
66 * columns with fractional occurence of gaps (considering
67 * sequence weights) is greater than this, the column is
68 * assigned to insert.
69 * 2. <use_rf> == FALSE and <use_wts> == FALSE:
70 * Same as 1, but sequence weights are not considered in
71 * fractional occurence of gaps. (This was default in
72 * Infernal up through version 1.0.2).
73 * 3. <use_rf> == TRUE and <use_wts> == FALSE:
74 * case): Match positions are defined as all non-gap
75 * positions in the msa->rf annotation.
76 * 4. <use_rf> == TRUE and <use_wts> == TRUE:
77 * Not allowed. Contract violation.
78 *
79 * Both rf and cs are provided in the msa structure.
80 *
81 * If <use_el> is TRUE, we consider models with '~' in
82 * msa->rf as local end (EL) emission columns. These are not
83 * insert columns, nor match columns but get modeled with
84 * the EL state. As of now, <use_el> should only be TRUE if
85 * called internally using a Infernal constructed
86 * <msa>. That is, we do not expect it to be called during
87 * cmbuild's build procedure. So we expect the use of EL
88 * columns in the MSA to always be valid.
89 *
90 * Args: msa - multiple alignment to build model from
91 * errbuf - for error messages
92 * use_rf - TRUE to use RF annotation to determine match/insert
93 * use_el - TRUE to model RF '~' columns with the E state
94 * use_wts - TRUE to consider sequence weights from msa when determining match/insert
95 * symfrac - nucleotide occupancy thresh for defining a match column (if use_rf=FALSE)
96 * ret_cm - RETURN: new model (maybe NULL)
97 * ret_gtr - RETURN: guide tree for alignment (maybe NULL)
98 *
99 * Return: eslOK on success;
100 *
101 * Throws: eslEINCOMPAT on contract violation, ret_cm and ret_gtr set to NULL.
102 * eslEINVAL on invalid input, ret_cm and ret_gtr set to NULL.
103 */
104 int
105 HandModelmaker(ESL_MSA *msa, char *errbuf, int use_rf, int use_el, int use_wts, float symfrac, CM_t **ret_cm, Parsetree_t **ret_gtr)
106 {
107 int status;
108 CM_t *cm = NULL; /* new covariance model */
109 Parsetree_t *gtr = NULL; /* guide tree for alignment */
110 ESL_STACK *pda = NULL; /* pushdown stack used in building gtr */
111 int *matassign = NULL; /* 1..alen array; 0=insert col, 1=match col */
112 int *elassign = NULL; /* 1..alen array; 0=match/ins col, 1=EL col */
113 int *ct = NULL; /* 0..alen-1 base pair partners array */
114 int apos; /* counter over columns of alignment */
115 int v; /* index of current node */
116 int i,j,k; /* subsequence indices */
117 int type; /* type of node we're working on */
118 int diff, bestdiff, bestk; /* used while finding optimal split points */
119 int nnodes; /* number of nodes in CM */
120 int nstates; /* number of states in CM */
121 int clen; /* consensus length of the model */
122 int *c2a_map = NULL; /* [1..clen] map from consensus (match) positions to alignment positions */
123 int *a2c_map = NULL; /* [1..msa->alen] map from alignment positions to consensus (match) positions,
124 * insert alignment positions = 0 */
125 int cpos; /* consensus position counter */
126 int k_cpos, i_cpos, j_cpos; /* consensus position that k, i, j (alignment positions) correspond to */
127 int kp; /* k prime, closest alignment position that is consensus to the right of k (that is kp >= k) */
128 int el_i, el_j; /* i and j, before accounting for ELs */
129
130 /* Contract check */
131 if (msa->ss_cons == NULL) ESL_XFAIL(eslEINCOMPAT, errbuf, "HandModelmaker(): No consensus structure annotation available for the alignment.");
132 if (! (msa->flags & eslMSA_DIGITAL)) ESL_XFAIL(eslEINCOMPAT, errbuf, "HandModelmaker(): MSA is not digitized.");
133 if ( use_rf && msa->rf == NULL) ESL_XFAIL(eslEINCOMPAT, errbuf, "HandModelmaker(): No reference annotation available for the alignment.");
134 if (! use_rf && msa->wgt == NULL) ESL_XFAIL(eslEINCOMPAT, errbuf, "HandModelmaker(): use_rf is FALSE, and msa->wgt is NULL.");
135 if ( use_rf && use_wts) ESL_XFAIL(eslEINCOMPAT, errbuf, "HandModelmaker(): use_rf is TRUE and use_wts is TRUE, if use_rf is TRUE, use_wts must be FALSE.");
136
137 /* 1. Determine match/insert assignments
138 * matassign is 1..alen. Values are 1 if a match column, 0 if insert column.
139 */
140 AssignMatchColumnsForMsa(msa, errbuf, use_rf, use_wts, symfrac, &matassign);
141
142 /* 2. Determine EL assignments, if necessary.
143 * elassign is 1..alen. Values are 1 if a EL column, 0 if match or insert column.
144 * If <use_el> is FALSE, we set all values to FALSE. The contract enforced
145 * that if <use_el> is TRUE, <use_rf> must also be TRUE. Since RF '~' columns
146 * are defined as inserts if <use_rf> is TRUE, we're guaranteed that no
147 * RF '~' column will have matassign == TRUE at this point.
148 */
149
150 ESL_ALLOC(elassign, sizeof(int) * (msa->alen+1));
151 if (use_el) {
152 elassign[0] = FALSE; /* out of bounds */
153 for (apos = 1; apos <= msa->alen; apos++)
154 elassign[apos] = (esl_abc_CIsMissing(msa->abc, msa->rf[apos-1])) ? TRUE : FALSE;
155 /* sanity check */
156 for (apos = 1; apos <= msa->alen; apos++)
157 if(matassign[apos] && elassign[apos]) ESL_XFAIL(eslEINVAL, errbuf, "HandModelmaker(): position %d assigned as match and EL", apos);
158 }
159 else {
160 esl_vec_ISet(elassign, msa->alen+1, FALSE);
161 }
162
163 /* 3. Determine a "ct" array, base-pairing partners for each position.
164 * Disallow/ignore pseudoknots by removing them prior to making the ct array.
165 * ct[] values give the index of a base pairing partner, or 0 for unpaired positions.
166 * Even though msa->ss_cons is in the 0..alen-1 coord system of msa, ct[]
167 * comes back in the 1..alen coord system of dsq.
168 */
169 esl_wuss_nopseudo(msa->ss_cons, msa->ss_cons); /* remove pknots in place */
170 ESL_ALLOC(ct, (msa->alen+1) * sizeof(int));
171 if (esl_wuss2ct(msa->ss_cons, msa->alen, ct) == eslESYNTAX) ESL_XFAIL(eslEINVAL, errbuf, "HandModelMaker(): consensus structure string is inconsistent");
172 else if ((status = esl_wuss2ct(msa->ss_cons, msa->alen, ct)) != eslOK) goto ERROR;
173
174 /* 4. Make sure the consensus structure "ct" is consistent with the match assignments.
175 * Wipe out all structure in insert columns; including the base-paired
176 * partner of insert-assigned columns. Also create a map from consensus positions
177 * to alignment positions (c2a_map) and vice versa (a2c_map), we'll use this
178 * to choose optimal k for bifurcations below.
179 */
180 clen = 1;
181 for (apos = 1; apos <= msa->alen; apos++) {
182 if (! matassign[apos]) {
183 if (ct[apos] != 0) ct[ct[apos]] = 0;
184 ct[apos] = 0;
185 }
186 else clen++;
187 }
188 /* build c2a_map and a2c_map, we need clen before we can allocate c2a_map, hence the second apos=1..alen loop */
189 ESL_ALLOC(c2a_map, sizeof(int) * (clen+1));
190 ESL_ALLOC(a2c_map, sizeof(int) * (msa->alen+1));
191 c2a_map[0] = 0; /* invalid */
192 a2c_map[0] = 0; /* invalid */
193 cpos = 1;
194 for (apos = 1; apos <= msa->alen; apos++) {
195 if(matassign[apos]) {
196 a2c_map[apos] = cpos;
197 c2a_map[cpos] = apos;
198 cpos++;
199 }
200 else a2c_map[apos] = 0;
201 }
202
203 /* 5. Construct a guide tree.
204 * This code is borrowed from yarn's KHS2Trace().
205 *
206 * We also keep track of how many states we'll need in the final CM,
207 * so we'll know how much to allocate -- and the number of nodes,
208 * for informational purposes.
209 */
210 nstates = nnodes = 0;
211 if ((gtr = CreateParsetree(25)) == NULL) { status = eslEMEM; goto ERROR; } /* the parse tree we'll grow */
212 if ((pda = esl_stack_ICreate()) == NULL) { status = eslEMEM; goto ERROR; } /* a pushdown stack for our indices */
213 clen = 0;
214
215 /* Construction strategy has to make sure we number the nodes in
216 * preorder traversal: for bifurcations, we can't attach the right
217 * child until we've fully traversed the left side. Therefore, we have
218 * to push what we intend to attach, and pop it later. And since we
219 * don't know an index for the node until we attach it, we have no
220 * place to put the node's data except the stack -- so we have to
221 * push several numbers onto the stack: what type of node, what
222 * subseq it's responsible for (emitl...emitr), and what node
223 * index it attaches to.
224 */
225 if ((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* what node it's attached to */
226 if ((status = esl_stack_IPush(pda, 1)) != eslOK) goto ERROR; /* emitl */
227 if ((status = esl_stack_IPush(pda, msa->alen)) != eslOK) goto ERROR; /* emitr */
228 if ((status = esl_stack_IPush(pda, ROOT_nd)) != eslOK) goto ERROR; /* "state" (e.g. node type) */
229
230 while (esl_stack_IPop(pda, &type) != eslEOD) /* pop a node type to attach */
231 {
232 esl_stack_IPop(pda, &j);
233 esl_stack_IPop(pda, &i); /* i..j == subseq we're responsible for */
234 esl_stack_IPop(pda, &v); /* v = index of parent node in gtr */
235
236 /* We'll skip EL columns but need to remember what i and j would
237 * be if we didn't: <el_i> and <el_j>. Then, we can set emitr
238 * for MATL and emitl for MATR as <el_j> and <el_i> respectively.
239 * If <use_el> is FALSE, i == el_i and j == el_j.
240 */
241 if(use_el) {
242 el_i = i;
243 el_j = j;
244 while(i <= msa->alen && elassign[i]) i++;
245 while(j >= 1 && elassign[j]) j--;
246 if(i > (msa->alen+1)) ESL_XFAIL(eslEINVAL, errbuf, "HandModelmaker(): problem with local ends (RF='~') during model construction");
247 if(j < 0) ESL_XFAIL(eslEINVAL, errbuf, "HandModelmaker(): problem with local ends (RF='~') during model construction");
248 }
249 else {
250 el_i = i;
251 el_j = j;
252 }
253
254 /* This node accounts for i..j, but we usually don't know how yet.
255 * Six possibilities:
256 * i > j; this is an END state; do nothing.
257 * this is already assigned as a BEGIN; push i,j
258 * i is unpaired; this is a MATL state; push i+1, j
259 * j is unpaired; this is a MATR state; push i,j-1
260 * i,j pair to each other; this is a MATP state; push i+1,j-1
261 * i,j pair but not to each other; this is a BIFURC state;
262 * pick mid ip <= mid < jp; push BEGIN i,mid and working i,mid,
263 * and push BEGIN mid+1,j and working mid+1,j
264 */
265 if (i > j) {
266 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, END_nd);
267 nstates += 1; /* END_nd -> E_st */
268 nnodes++;
269 }
270
271 else if (type == ROOT_nd) { /* try to push i,j; but deal with INSL and INSR */
272 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, ROOT_nd);
273 for (; i <= j; i++) if (matassign[i] || elassign[i]) break;
274 for (; j >= i; j--) if (matassign[j] || elassign[j]) break;
275 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR; /* here v==0 always. */
276 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
277 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
278 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
279 nstates += 3; /* ROOT_nd -> S_st, IL_st, IR_st */
280 nnodes++;
281 }
282
283 else if (type == BEGL_nd) { /* no inserts */
284 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, BEGL_nd);
285 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
286 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
287 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
288 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
289 nstates += 1; /* BEGL_nd -> S_st */
290 nnodes++;
291 }
292
293 else if (type == BEGR_nd) { /* look for INSL */
294 v = InsertTraceNode(gtr, v, TRACE_RIGHT_CHILD, i, j, BEGR_nd);
295 for (; i <= j; i++) if (matassign[i] || elassign[i]) break;
296 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
297 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
298 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
299 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
300 nstates += 2; /* BEGR_nd -> S_st IL_st */
301 nnodes++;
302 }
303
304 else if (ct[i] == 0) {
305 /* i unpaired. This is a MATL node; allow INSL */
306 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, el_j, MATL_nd);
307 for (i = i+1; i <= j; i++) if (matassign[i] || elassign[i]) break;
308 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
309 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
310 if((status = esl_stack_IPush(pda, el_j)) != eslOK) goto ERROR;
311 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
312 nstates += 3; /* MATL_nd -> ML_st, D_st, IL_st */
313 nnodes++;
314 clen += 1;
315 }
316
317 else if (ct[j] == 0) { /* j unpaired. MATR node. Deal with INSR */
318 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, el_i, j, MATR_nd);
319 for (j = j-1; j >= i; j--) if (matassign[j] || elassign[j]) break;
320 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
321 if((status = esl_stack_IPush(pda, el_i)) != eslOK) goto ERROR;
322 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
323 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
324 nstates += 3; /* MATR_nd -> MR_st, D_st, IL_st */
325 nnodes++;
326 clen += 1;
327 }
328
329 else if (ct[i] == j) { /* i,j paired to each other. MATP. deal with INSL, INSR */
330 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, MATP_nd);
331 for (i = i+1; i <= j; i++) if (matassign[i] || elassign[i]) break;
332 for (j = j-1; j >= i; j--) if (matassign[j] || elassign[j]) break;
333 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
334 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
335 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
336 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
337 nstates += 6; /* MATP_nd -> MP_st, ML_st, MR_st, D_st, IL_st, IR_st */
338 nnodes++;
339 clen += 2;
340 }
341
342 else /* i,j paired but not to each other. BIFURC. no INS. */
343 {
344 /* Here's the first of two places where we can optimize the topology
345 * of a CM. (The other comes from choosing a state traversal order when
346 * building the CM.) Imagine a multifurcation of four domains:
347 * [1]..[2]..[3]..[4]
348 * The "default leftwise" rule means that BEGL/INSL generates the
349 * intervening sequences, so we must model the four stems as:
350 * [1], ..[2], ..[3], ..[4]
351 * but we have a choice of how we bifurcate:
352 * (1,2)(3,4) 1,(2,(3,4)) ((1,2),3),4
353 * Our choice affects the time and memory requirements of a divide
354 * conquer alignment algorithm. (1,(2,(3,4)) is most efficient for
355 * memory; (1,2)(3,4) is most efficient for time.
356 *
357 * So we may want to choose carefully from several possible split
358 * points k (3, in the above example). A priori we only know one
359 * possible midpoint precisely: ct[i]+1, the next base after closing
360 * domain 1. We can find the others by scanning for them, and we can
361 * be reasonably efficient about scanning by using ct[] to instantly
362 * skip subdomains.
363 */
364 /* One possible rule: optimize by finding most balanced split.
365 * Each stop of the following loop gives a possible midpoint k, which is
366 * then evaluated, keeping track of the best split so far.
367 */
368 /* EPN, Tue Sep 9 07:41:28 2008
369 * Revised this code block to pick optimal choice of k based
370 * on split lengths of consensus (match) positions instead
371 * of alignment positions, this actually yields most
372 * 'balanced' split as described above because DP operates
373 * on consensus positions, not alignment positions (which
374 * are affected by inserts in the input msa). Motivation for
375 * this revision was to allow merging of two alignments
376 * created by two runs cmalign to the same CM, which is done
377 * by converting both alignments to guidetrees, then each
378 * aligned seq to a parsetree then converting all parsetrees
379 * from both alignments to a single msa. Prior to the
380 * revision the specific guidetree built from an alignment
381 * was subject to the number of inserts in the msas, so we
382 * couldn't guarantee that both msas would yield the same
383 * guidetree, which was problematic. In other words, prior
384 * to this the SS_cons and RF annotation didn't determine
385 * the guidetree, but rather the SS_cons *and* the number
386 * and spacing of the inserts determined the guidetree; now
387 * the SS_cons and RF annotation completely determine the
388 * guidetree.
389 */
390 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, BIF_nd);
391
392 i_cpos = a2c_map[i];
393 j_cpos = a2c_map[j];
394 bestk = ct[i]+1;
395 bestdiff = msa->alen+1; /* effectively infinity, difference in left/right subtree lengths can never exceed this */
396 for (k = ct[i] + 1; k <= ct[j]; k = ct[k] + 1)
397 {
398 /* set kp as the closest consensus position to k to the
399 * right (right side was chosen (over left) arbitrarily,
400 * practically it won't matter, as long as we always
401 * look the same way (right or left)) b/c what we really want
402 * is this choice to be deterministic based on SS_cons alone,
403 * that is a specific SS_cons yields same guide tree always,
404 * regardless of length and placement of inserts.
405 */
406 kp = k;
407 while(a2c_map[kp] == 0) kp++; /* increment kp until it's a consensus position */
408 k_cpos = a2c_map[kp];
409 diff = abs((k_cpos-i_cpos) - (j_cpos-k_cpos+1));
410 /* diff = abs(cons length modeled by left child minus cons length modeled by right child),
411 * Note that left child is i_cpos..k_cpos-1, right child is k_cpos..j_cpos
412 */
413
414 if (diff < bestdiff) {
415 bestdiff = diff;
416 bestk = k;
417 }
418 while (ct[k] == 0) k++; /* at end of this while, k will be a paired, (and therefore consensus) position */
419 }
420 /* push the right BEGIN node first */
421 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
422 if((status = esl_stack_IPush(pda, bestk)) != eslOK) goto ERROR;
423 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
424 if((status = esl_stack_IPush(pda, BEGR_nd)) != eslOK) goto ERROR;
425 /* then push the left BEGIN node */
426 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
427 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
428 if((status = esl_stack_IPush(pda, bestk-1)) != eslOK) goto ERROR;
429 if((status = esl_stack_IPush(pda, BEGL_nd)) != eslOK) goto ERROR;
430 nstates += 1; /* BIF_nd -> B_st */
431 nnodes++;
432 }
433 } /* while something's on the stack */
434 esl_stack_Destroy(pda);
435 free(ct);
436
437 /* Ok, we've converted ct into gtr -- gtr is a tree structure
438 * telling us the arrangement of consensus nodes. Now do the drill
439 * for constructing a full model using this guide tree. We only have
440 * to do this step if we're returning a CM though. (Sometimes caller
441 * may only want gtr.)
442 */
443 if(ret_cm != NULL) {
444 cm = CreateCM(nnodes, nstates, clen, msa->abc);
445 if((status = cm_from_guide(cm, errbuf, gtr, FALSE)) != eslOK) return status; /* FALSE says, we're not building a sub CM that will never be localized */
446 CMZero(cm);
447 cm->clen = clen;
448
449 /* new in v1.1: fill cm->map (always) and fill cm->rf (if use_rf) */
450 /* cm->map is identical to c2a_map, copy it */
451 if(cm->map != NULL) free(cm->map); /* this is paranoid, it will be NULL */
452 ESL_ALLOC(cm->map, sizeof(int) * (cm->clen+1));
453 esl_vec_ICopy(c2a_map, (cm->clen+1), cm->map);
454 cm->flags |= CMH_MAP;
455
456 /* if <use_rf> == TRUE, msa->rf is transferred to cm->rf, from consensus positions */
457 if(use_rf == TRUE) { /* if use_rf is TRUE, msa->rf is non-NULL */
458 if(cm->rf != NULL) free(cm->rf); /* this is paranoid, it will be NULL */
459 ESL_ALLOC(cm->rf, sizeof(char) * (cm->clen+2));
460 cm->rf[0] = ' ';
461 for(cpos = 1; cpos <= cm->clen; cpos++)
462 cm->rf[cpos] = msa->rf[c2a_map[cpos]-1]; /* watch off-by-one in msa's rf */
463 cm->rf[cm->clen+1] = '\0';
464 cm->flags |= CMH_RF;
465 }
466 }
467
468 free(matassign);
469 free(elassign);
470 free(c2a_map);
471 free(a2c_map);
472 if (ret_cm) *ret_cm = cm; else FreeCM(cm);
473 if (ret_gtr) *ret_gtr = gtr; else FreeParsetree(gtr);
474 return eslOK;
475
476 ERROR:
477 free(matassign);
478 free(elassign);
479 free(c2a_map);
480 free(a2c_map);
481 FreeCM(cm);
482 FreeParsetree(gtr);
483 if (ret_cm) *ret_cm = NULL;
484 if (ret_gtr) *ret_gtr = NULL;
485 if (status == eslEMEM) ESL_FAIL(eslEMEM, errbuf, "HandModelmaker(): memory allocation error.");
486 return status; /* never reached */
487 }
488
489 /* Function: AssignMatchColumnsForMsa()
490 * Date: EPN, Tue Mar 7 13:17:14 2023
491 *
492 * Purpose: Given an MSA, determine which positions will be 'match' (consensus)
493 * positions and which will be insert. Reference annotation (msa->rf)
494 * if used if <use_rf> is TRUE, else any column for which the fraction of
495 * sequences (weighted by msa->wgt if <use_wts>) is at least <symfrac>
496 * is defined as a match column and all other columns are inserts.
497 * Assignments returned in <ret_matassign>.
498 *
499 * Args: msa - the multiple alignment
500 * errbuf - for error messages
501 * use_rf - TRUE to use RF annotation to determine match/insert
502 * use_wts - TRUE to consider sequence weights from msa when determining match/insert
503 * symfrac - nucleotide occupancy thresh for defining a match column (if use_rf=FALSE)
504 * ret_matassign - RETURN: [1..i..msa->alen] 1 if i is match column, 0 if not
505 *
506 * Return: eslOK on success;
507 * eslEMEM if we run out of memory, ret_matassign set to NULL
508 * eslEINCOMPAT on contract violation, ret_matassign set to NULL
509 */
510 int
511 AssignMatchColumnsForMsa(ESL_MSA *msa, char *errbuf, int use_rf, int use_wts, float symfrac, int **ret_matassign)
512 {
513 int status; /* return status */
514 int apos; /* counter over columns of alignment */
515 int idx; /* counter over sequences in the alignment */
516 float r; /* weighted residue count */
517 float totwgt; /* weighted residue+gap count */
518 float wgt; /* weight of a sequence */
519 int *matassign = NULL; /* 1..alen array; 0=insert col, 1=match col */
520
521 /* Contract check */
522 if (! (msa->flags & eslMSA_DIGITAL)) ESL_XFAIL(eslEINCOMPAT, errbuf, "AssignMatchColumnsForMsa(): MSA is not digitized.");
523 if ( use_rf && msa->rf == NULL) ESL_XFAIL(eslEINCOMPAT, errbuf, "AssignMatchColumnsForMsa(): No reference annotation available for the alignment.");
524 if (! use_rf && msa->wgt == NULL) ESL_XFAIL(eslEINCOMPAT, errbuf, "AssignMatchColumnsForMsa(): use_rf is FALSE, and msa->wgt is NULL.");
525
526 ESL_ALLOC(matassign, sizeof(int) * (msa->alen+1));
527 matassign[0] = 0; /* irrelevant, matassign is 1..alen */
528
529 /* Watch for off-by-one. rf is [0..alen-1]; matassign is [1..alen] */
530 if (use_rf) {
531 /* Define match based on RF char, if gap or missing ('-_.~')
532 * then insert, else match.
533 *
534 * It's impt we don't count '~' as a match column b/c we don't
535 * want a match column to have RF == '~' in a cmalign output
536 * alignment as that would screw the merging of subalignments in
537 * cmalign, which assumes '~' RF columns are EL inserts.
538 */
539 for (apos = 1; apos <= msa->alen; apos++)
540 matassign[apos] = ((esl_abc_CIsGap (msa->abc, msa->rf[apos-1])) || /* CIsGap returns true for '.', '_' and '-' only (they're equivalent, see create_rna() in esl_alphabet.c()) */
541 (esl_abc_CIsMissing(msa->abc, msa->rf[apos-1]))) /* CIsMissing returns true for '~' only */
542 ? FALSE : TRUE;
543 }
544 else {
545 for (apos = 1; apos <= msa->alen; apos++) {
546 r = totwgt = 0.;
547 for (idx = 0; idx < msa->nseq; idx++) {
548 wgt = (use_wts) ? msa->wgt[idx] : 1.0;
549 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos])) { r += wgt; totwgt += wgt; }
550 else if (esl_abc_XIsGap(msa->abc, msa->ax[idx][apos])) { totwgt += wgt; }
551 else if (esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos])) continue;
552 }
553 if (r > 0. && r / totwgt >= symfrac) matassign[apos] = TRUE;
554 else matassign[apos] = FALSE;
555 }
556 }
557
558 *ret_matassign = matassign;
559 return eslOK;
560
561 ERROR:
562 if(matassign != NULL) free(matassign);
563 *ret_matassign = NULL;
564 if(status == eslEMEM) ESL_FAIL(eslEMEM, errbuf, "AssignMatchColumnsForMsa(): memory allocation error.");
565 return status; /* never reached */
566 }
567
568 /* Function: cm_from_guide()
569 * Date: SRE, Sat Jul 29 09:25:49 2000 [St. Louis]
570 *
571 * Purpose: given a guide tree and an allocated CM,
572 * fill in all the structural information of the CM.
573 *
574 * Args: cm - allocated cm to construct
575 * errbuf - for error messages
576 * gtr - guide tree
577 * will_never_localize- TRUE if we're building a sub CM that we will never localize.
578 * This is only relevant b/c we can allow 'invalid' CMs in this case.
579 * An invalid CM is one that, if localized, could not generate all
580 * possible sequences (see comments in code below).
581 * We allow sub CMs to be invalid b/c we don't want cmalign to die
582 * when a target seq results in a sub CM that is invalid in the middle
583 * of a run. This is a pure hack and relies UNSAFELY on the assumption
584 * that the sub CM will never be localized (though in the current
585 * implementation sub CMs are only used by cmalign in global mode, thus
586 * they never are localized). Still, we don't raise a flag in the
587 * CM to prevent downstream localization, which is dangerous - if the
588 * implementation changes to allow sub CMs to become localized. Even then
589 * though the risk is small b/c an invalid CM only is a problem if we
590 * try to align a single residue sequence to it (again, see comments below
591 * for more explanation).
592 *
593 * Returns: eslOK on success;
594 */
595 int
596 cm_from_guide(CM_t *cm, char *errbuf, Parsetree_t *gtr, int will_never_localize)
597 {
598 int status;
599 ESL_STACK *pda; /* pushdown stack used for traversing gtr */
600 int v; /* what node we're working on (in gtr index system)*/
601 int node; /* what node (preorder traversal numbering of CM) */
602 int state; /* what state (preorder traversal numbering of CM) */
603 int clen; /* current count of consensus length */
604 int nxtnodetype; /* type of a child node (e.g. MATP_nd) */
605 int prvnodetype; /* type of a parent node (e.g. MATP_nd) */
606
607 /* Some CM structural configuration info:
608 * child_count[] gives how many states are connectable in a child node.
609 * parent_count[] gives how many states are connectable in a parent node.
610 */
611 /* BIF, MATP, MATL, MATR, BEGL, BEGR, ROOT, END */
612 int child_count[] = { 1, 4, 2, 2, 1, 1, 0, 1};
613 int parent_count[] = { 1, 6, 3, 3, 1, 2, 3, 0};
614
615 node = state = clen = 0;
616 pda = esl_stack_ICreate();
617 if((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR; /* push ROOT_nd onto the stack */
618 while (esl_stack_IPop(pda, &v) != eslEOD)
619 {
620
621 if (gtr->state[v] == BIF_nd) {
622 prvnodetype = gtr->state[gtr->prv[v]];
623
624 cm->nodemap[node] = state;
625 cm->ndtype[node ] = BIF_nd;
626
627 cm->sttype[state] = B_st;
628 cm->ndidx[state] = node;
629 cm->stid[state] = BIF_B;
630 cm->cfirst[state] = state+1;
631 cm->cnum[state] = -1; /* we fill this in later, when we see the BEGR... */
632 if((status = esl_stack_IPush(pda, state)) != eslOK) goto ERROR; /* ... the trick we use to remember the connection */
633 cm->plast[state] = state-1;
634 cm->pnum[state] = parent_count[prvnodetype];
635 state++;
636
637 node++;
638 if((status = esl_stack_IPush(pda, gtr->nxtr[v])) != eslOK) goto ERROR;
639 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
640 }
641
642 else if (gtr->state[v] == MATP_nd) {
643 nxtnodetype = gtr->state[gtr->nxtl[v]];
644 prvnodetype = gtr->state[gtr->prv[v]];
645
646 cm->nodemap[node] = state;
647 cm->ndtype[node ] = MATP_nd;
648 clen += 2;
649
650 cm->sttype[state] = MP_st;
651 cm->ndidx[state] = node;
652 cm->stid[state] = MATP_MP;
653 cm->cfirst[state] = state+4;
654 cm->cnum[state] = 2 + child_count[nxtnodetype];
655 cm->plast[state] = state-1;
656 cm->pnum[state] = parent_count[prvnodetype];
657 state++;
658
659 cm->sttype[state] = ML_st;
660 cm->ndidx[state] = node;
661 cm->stid[state] = MATP_ML;
662 cm->cfirst[state] = state+3;
663 cm->cnum[state] = 2 + child_count[nxtnodetype];
664 cm->plast[state] = state-2;
665 cm->pnum[state] = parent_count[prvnodetype];
666 state++;
667
668 cm->sttype[state] = MR_st;
669 cm->ndidx[state] = node;
670 cm->stid[state] = MATP_MR;
671 cm->cfirst[state] = state+2;
672 cm->cnum[state] = 2 + child_count[nxtnodetype];
673 cm->plast[state] = state-3;
674 cm->pnum[state] = parent_count[prvnodetype];
675 state++;
676
677 cm->sttype[state] = D_st;
678 cm->ndidx[state] = node;
679 cm->stid[state] = MATP_D;
680 cm->cfirst[state] = state+1;
681 cm->cnum[state] = 2 + child_count[nxtnodetype];
682 cm->plast[state] = state-4;
683 cm->pnum[state] = parent_count[prvnodetype];
684 state++;
685
686 cm->sttype[state] = IL_st;
687 cm->ndidx[state] = node;
688 cm->stid[state] = MATP_IL;
689 cm->cfirst[state] = state;
690 cm->cnum[state] = 2 + child_count[nxtnodetype];
691 cm->plast[state] = state;
692 cm->pnum[state] = 5;
693 state++;
694
695 cm->sttype[state] = IR_st;
696 cm->ndidx[state] = node;
697 cm->stid[state] = MATP_IR;
698 cm->cfirst[state] = state;
699 cm->cnum[state] = 1 + child_count[nxtnodetype];
700 cm->plast[state] = state;
701 cm->pnum[state] = 6;
702 state++;
703
704 node++;
705 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
706 }
707
708 else if (gtr->state[v] == MATL_nd) {
709 nxtnodetype = gtr->state[gtr->nxtl[v]];
710 prvnodetype = gtr->state[gtr->prv[v]];
711
712 cm->nodemap[node] = state;
713 cm->ndtype[node ] = MATL_nd;
714 clen += 1;
715
716 cm->sttype[state] = ML_st;
717 cm->ndidx[state] = node;
718 cm->stid[state] = MATL_ML;
719 cm->cfirst[state] = state+2;
720 cm->cnum[state] = 1 + child_count[nxtnodetype];
721 cm->plast[state] = state-1;
722 cm->pnum[state] = parent_count[prvnodetype];
723 state++;
724
725 cm->sttype[state] = D_st;
726 cm->ndidx[state] = node;
727 cm->stid[state] = MATL_D;
728 cm->cfirst[state] = state+1;
729 cm->cnum[state] = 1 + child_count[nxtnodetype];
730 cm->plast[state] = state-2;
731 cm->pnum[state] = parent_count[prvnodetype];
732 state++;
733
734 cm->sttype[state] = IL_st;
735 cm->ndidx[state] = node;
736 cm->stid[state] = MATL_IL;
737 cm->cfirst[state] = state;
738 cm->cnum[state] = 1 + child_count[nxtnodetype];
739 cm->plast[state] = state;
740 cm->pnum[state] = 3;
741 state++;
742
743 node++;
744 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
745 }
746
747 else if (gtr->state[v] == MATR_nd) {
748 nxtnodetype = gtr->state[gtr->nxtl[v]];
749 prvnodetype = gtr->state[gtr->prv[v]];
750
751 cm->nodemap[node] = state;
752 cm->ndtype[node ] = MATR_nd;
753 clen += 1;
754
755 cm->sttype[state] = MR_st;
756 cm->ndidx[state] = node;
757 cm->stid[state] = MATR_MR;
758 cm->cfirst[state] = state+2;
759 cm->cnum[state] = 1 + child_count[nxtnodetype];
760 cm->plast[state] = state-1;
761 cm->pnum[state] = parent_count[prvnodetype];
762 state++;
763
764 cm->sttype[state] = D_st;
765 cm->ndidx[state] = node;
766 cm->stid[state] = MATR_D;
767 cm->cfirst[state] = state+1;
768 cm->cnum[state] = 1 + child_count[nxtnodetype];
769 cm->plast[state] = state-2;
770 cm->pnum[state] = parent_count[prvnodetype];
771 state++;
772
773 cm->sttype[state] = IR_st;
774 cm->ndidx[state] = node;
775 cm->stid[state] = MATR_IR;
776 cm->cfirst[state] = state;
777 cm->cnum[state] = 1 + child_count[nxtnodetype];
778 cm->plast[state] = state;
779 cm->pnum[state] = 3;
780 state++;
781
782 node++;
783 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
784 }
785
786 else if (gtr->state[v] == BEGL_nd) {
787 nxtnodetype = gtr->state[gtr->nxtl[v]];
788
789 cm->nodemap[node] = state;
790 cm->ndtype[node] = BEGL_nd;
791
792 cm->sttype[state] = S_st;
793 cm->ndidx[state] = node;
794 cm->stid[state] = BEGL_S;
795 cm->cfirst[state] = state+1;
796 cm->cnum[state] = child_count[nxtnodetype];
797 cm->plast[state] = state-1;
798 cm->pnum[state] = 1;
799 state++;
800
801 node++;
802 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
803 }
804
805 else if (gtr->state[v] == BEGR_nd) {
806 int bifparent;
807
808 nxtnodetype = gtr->state[gtr->nxtl[v]];
809
810 cm->nodemap[node] = state;
811 cm->ndtype[node] = BEGR_nd;
812
813 /* A trick: we need to attach this start state to the previous
814 * bifurcation. We stored the bif state index by pushing it onto
815 * the pda -- retrieve it now.
816 */
817 esl_stack_IPop(pda, &bifparent);
818 cm->cnum[bifparent] = state; /* remember, cnum overloaded for bif: idx of right child */
819
820 cm->sttype[state] = S_st;
821 cm->ndidx[state] = node;
822 cm->stid[state] = BEGR_S;
823 cm->cfirst[state] = state+1;
824 cm->cnum[state] = 1 + child_count[nxtnodetype];
825 cm->plast[state] = bifparent;
826 cm->pnum[state] = 1;
827 state++;
828
829 cm->sttype[state] = IL_st;
830 cm->ndidx[state] = node;
831 cm->stid[state] = BEGR_IL;
832 cm->cfirst[state] = state;
833 cm->cnum[state] = 1 + child_count[nxtnodetype];
834 cm->plast[state] = state;
835 cm->pnum[state] = 2;
836 state++;
837
838 node++;
839 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
840 }
841
842 else if (gtr->state[v] == ROOT_nd) {
843 nxtnodetype = gtr->state[gtr->nxtl[v]];
844
845 cm->nodemap[node] = state;
846 cm->ndtype[node] = ROOT_nd;
847
848 cm->sttype[state] = S_st;
849 cm->ndidx[state] = node;
850 cm->stid[state] = ROOT_S;
851 cm->cfirst[state] = state+1;
852 cm->cnum[state] = 2 + child_count[nxtnodetype];
853 cm->plast[state] = -1;
854 cm->pnum[state] = 0;
855 state++;
856
857 cm->sttype[state] = IL_st;
858 cm->ndidx[state] = node;
859 cm->stid[state] = ROOT_IL;
860 cm->cfirst[state] = state;
861 cm->cnum[state] = 2 + child_count[nxtnodetype];
862 cm->plast[state] = state;
863 cm->pnum[state] = 2;
864 state++;
865
866 cm->sttype[state] = IR_st;
867 cm->ndidx[state] = node;
868 cm->stid[state] = ROOT_IR;
869 cm->cfirst[state] = state;
870 cm->cnum[state] = 1 + child_count[nxtnodetype];
871 cm->plast[state] = state;
872 cm->pnum[state] = 3;
873 state++;
874
875 node++;
876 if((status = esl_stack_IPush(pda, gtr->nxtl[v])) != eslOK) goto ERROR;
877 }
878
879 else if (gtr->state[v] == END_nd) {
880 prvnodetype = gtr->state[gtr->prv[v]];
881
882 cm->nodemap[node] = state;
883 cm->ndtype[node] = END_nd;
884
885 cm->sttype[state] = E_st;
886 cm->ndidx[state] = node;
887 cm->stid[state] = END_E;
888 cm->cfirst[state] = -1;
889 cm->cnum[state] = 0;
890 cm->plast[state] = state-1;
891 cm->pnum[state] = parent_count[prvnodetype];
892 state++;
893
894 node++;
895 }
896 }
897 esl_stack_Destroy(pda);
898 cm->M = state;
899 cm->nodes = node;
900 cm->clen = clen;
901
902 if(!will_never_localize) { /* input arg tells us we may localize this CM, check it's valid,
903 * if we won't localize it, then we don't check */
904 /* A couple of checks to make sure our CM is valid for local alignment/search.
905 * The following is invalid:
906 * 1. CMs with exactly 3 nodes. This must be either {ROOT, MATL, END} or
907 * {ROOT, MATP, END}. Either way a local end is impossible b/c local ends
908 * from nodes adjacent to end states are impossible. This is bad. Even
909 * worse is a {ROOT, MATL, END} model can't emit/align more than a single
910 * residue in local mode (ROOT_IL, ROOT_IR are unreachable, and so is MATL_IL,
911 * b/c it was detached to remove an ambiguity with ROOT_IR).
912 * 2. CMs with 0 MATL, MATR and BIF nodes. The reason is because such a CM only has
913 * a ROOT, a bunch of MATPs and an END, and it is impossible to align a single
914 * residue to such a model when it's in local mode.
915 */
916 if(cm->nodes == 3) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_from_guide(), it's illegal to construct a CM of only 3 nodes.");
917 if((CMCountNodetype(cm, MATL_nd) == 0) && (CMCountNodetype(cm, MATR_nd) == 0) && (CMCountNodetype(cm,BIF_nd) == 0)) ESL_FAIL(eslEINCOMPAT, errbuf, "cm_from_guide(), it's illegal to construct a CM with 0 MATL, MATR and BIF nodes.");
918 }
919 return eslOK;
920
921 ERROR:
922 ESL_FAIL(eslEMEM, errbuf, "cm_from_guide(): memory allocation error.");
923 return eslEMEM; /* NEVERREACHED */
924 }
925
926
927 /* Function: Transmogrify()
928 * Date: SRE, Mon Jul 31 14:30:58 2000 [St. Louis]
929 *
930 * Purpose: Construct a "fake" parsetree for a given aligned sequence (ax),
931 * given a new CM structure (cm) and a guide tree (gtr).
932 *
933 * Local alignment is only partially handled. EL emissions
934 * are handled by transiting to EL and emitted the required
935 * number of residues. <used_el> allows us to determine when
936 * this is necessary. Silent EL visits are never used
937 * however since it is (currently) impossible to distinguish
938 * them from a string of deletes. Local begins are not
939 * handled since there is no way to distinguish these from a
940 * string of deletes either (although we could if we
941 * annotated <ax> with '~' before and after the first and
942 * final emitted residues). Finally, truncated alignments
943 * are not handled, although, presumably we could, again
944 * with '~' in <ax>. If this function is revisited to add
945 * support for local begins and truncated begins/ends, refer
946 * to the Transmogrify() function in version 1.0.2, which
947 * partially implemented local begins using '~'.
948 *
949 * Note, if <used_el> contains any TRUE values (i.e. any
950 * columns of the MSA are represented by EL) then the
951 * guide tree <gtr> should have been built by calling
952 * HandModelmaker() with <use_el> == TRUE. The caller
953 * must ensure this (we don't do it here). If not,
954 * we'll likely encounter an error in this function due
955 * to invalid input that is inconsistent with <gtr>.
956 *
957 * Args: cm - the new covariance model
958 * errbuf - buffer for error messages
959 * gtr - guide tree
960 * ax - a digitized aligned sequence [1..L]
961 * used_el - used_el[x] = 1, if alnment position x is an alignment
962 * column for EL (local end) emissions. Can be NULL
963 * if no positions are EL positions.
964 * alen - length of the alignment
965 * ret_tr - parsetree, created here
966 *
967 * Returns: eslOK on success.
968 *
969 * Throws: eslEMEM if out of memory; errbuf filled, *ret_tr set to NULL.
970 * eslEINVAL on invalid input; errbuf filled, *ret_tr set to NULL.
971 */
972 int
973 Transmogrify(CM_t *cm, char *errbuf, Parsetree_t *gtr, ESL_DSQ *ax, int *used_el, int alen, Parsetree_t **ret_tr)
974 {
975 int status;
976 Parsetree_t *tr = NULL;
977 int node; /* index of the node in *gtr* we're currently working on */
978 int state; /* index of a state in the *CM* */
979 int type; /* a unique statetype */
980 ESL_STACK *pda = NULL; /* pushdown automaton for positions in tr */
981 int tidx; /* index *in the parsetree tr* of the state we're supposed to attach to next */
982 int i,j; /* coords in aseq */
983 int ended; /* TRUE if we've transited to EL and ended */
984 int *nxt_mi = NULL; /* [1..apos..alen] nxt_mi[apos] is next alignment position > apos that
985 * includes a residue emitted from a match or insert state (not from the
986 * EL position).
987 */
988 int *nxt_el = NULL; /* [1..apos..alen] nxt_el[apos] is next alignment position > apos that
989 * includes a residue emitted from the EL state (not from a match or insert
990 * state).
991 */
992 int apos, apos2, prv_mi, prv_el; /* helpers for filling nxt_emit_mi, nxt_emit_el */
993 int goto_el; /* TRUE if we should transit to EL, FALSE if not */
994
995 /* variables related to dealing with truncated alignments */
996 int do_trunc; /* TRUE if we have any missing nt due to truncations */
997 int spos, epos; /* first/final non-missing positions for ax for purposes of dealing with truncations
998 * 1..spos-1, and epos+1..alen are missing data, so if spos==1 and epos==alen there is no missing data in ax
999 */
1000 int trunc_5p; /* TRUE if seqeuence is truncated on 5' end, else FALSE */
1001 int trunc_3p; /* TRUE if seqeuence is truncated on 5' end, else TRUE */
1002 int trunc_begin_node;/* if do_trunc, this is the first node we will visit after the ROOT_nd,
1003 * the final node with a subtree that spans full sequence */
1004 int trunc_mode; /* if do_trunc: truncation mode of trunc_begin_node */
1005 int *used_A = NULL; /* [0..n..cm->nodes-1] TRUE if node n used in this parsetree, FALSE if not,
1006 * necessary to determine if BEGL_S or BEGR_S nodes need to be visited, they
1007 * only are if their BIF_B parent is.
1008 */
1009
1010 tr = CreateParsetree(25);
1011 pda = esl_stack_ICreate();
1012
1013 ended = FALSE;
1014
1015 /* We preprocess the aligned seq ax so we can deal with truncated alignments */
1016 spos = 1;
1017 epos = alen;
1018 for (apos = 1; apos <= alen; apos++) {
1019 if(! esl_abc_XIsMissing(cm->abc, ax[apos])) break;
1020 spos++;
1021 }
1022 for (apos = alen; apos >= 1; apos--) {
1023 if(! esl_abc_XIsMissing(cm->abc, ax[apos])) break;
1024 epos--;
1025 }
1026 if((spos > alen) || (epos < 1)) {
1027 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify(): entire aligned sequence is missing data");
1028 }
1029 /* if spos > 1: 1..spos-1 are ~ (missing), truncated alignment starts at spos */
1030 /* if epos < alen: epos+1..alen are ~ (missing), truncated alignment ends at epos */
1031 trunc_5p = (spos > 1) ? TRUE : FALSE;
1032 trunc_3p = (epos < alen) ? TRUE : FALSE;
1033 do_trunc = (trunc_5p || trunc_3p) ? TRUE : FALSE;
1034
1035 /* If used_el is non-NULL then we need to fill <nxt_mi> with the next match/insert
1036 * emission and next EL emission <nxt_el> so we can identify transitions to EL
1037 * when necessary.
1038 */
1039 if(used_el != NULL) {
1040 ESL_ALLOC(nxt_mi, sizeof(int) * (alen+1));
1041 ESL_ALLOC(nxt_el, sizeof(int) * (alen+1));
1042 esl_vec_ISet(nxt_mi, (alen+1), alen+1);
1043 esl_vec_ISet(nxt_el, (alen+1), alen+1);
1044 prv_mi = 0;
1045 prv_el = 0;
1046 for (apos = 1; apos <= alen; apos++) {
1047 if(! esl_abc_XIsGap(cm->abc, ax[apos])) {
1048 if(used_el[apos]) { /* an EL emission */
1049 for(apos2 = prv_el; apos2 < apos; apos2++) nxt_el[apos2] = apos;
1050 prv_el = apos;
1051 }
1052 else { /* an emit but not from an EL */
1053 for(apos2 = prv_mi; apos2 < apos; apos2++) nxt_mi[apos2] = apos;
1054 prv_mi = apos;
1055 }
1056 }
1057 }
1058 /* don't worry about final consecutive string of gaps/ELs for nxt_mi/nxt_el, these were initialized to alen+1, which is correct */
1059 }
1060
1061 trunc_begin_node = -1;
1062 trunc_mode = TRMODE_J;
1063 if(do_trunc) {
1064 tr->is_std = FALSE; /* set is_std to FALSE */
1065 /* Set pass_idx for this truncated parsetree, inferred based on trunc_5p and trunc_3p which
1066 * themselves are defined based on presence of ~ before/after first/final residue above.
1067 * Possible values are restricted to PLI_PASS_5P_AND_3P_FORCE, PLI_PASS_5P_ONLY_FORCE or PLI_PASS_3P_ONLY_FORCE
1068 * even though if this parsetree is for a pipeline hit, it could have been found
1069 * in a different pipeline pass (e.g. PLI_PASS_5P_AND_3P_ANY). Also some hits
1070 * with ~ on 5' end but not 3' may have been found in PLI_PASS_5P_AND_3P_FORCE.
1071 * So we are kind of overloading tr->pass_idx for convenience here to use downstream
1072 * in Parsetrees2Alignment() to add ~ at 5' and/or 3' end.
1073 */
1074 if(trunc_5p) {
1075 tr->pass_idx = (trunc_3p) ? PLI_PASS_5P_AND_3P_FORCE : PLI_PASS_5P_ONLY_FORCE;
1076 }
1077 else { /* do_trunc is only true if trunc_5p or trunc_3p, so if !trunc_5p then trunc_3p == TRUE */
1078 tr->pass_idx = PLI_PASS_3P_ONLY_FORCE;
1079 }
1080
1081 /* initialize used_A we'll need in the main preorder traversal below */
1082 ESL_ALLOC(used_A, sizeof(int) * cm->nodes);
1083 esl_vec_ISet(used_A, cm->nodes, FALSE);
1084
1085 /* if we're truncated, do a preorder traversal to determine the first node we will use after the ROOT,
1086 * this is the final node with a subtree that spans the spos..epos (the entire sequence) */
1087 for (node = 0; node < cm->nodes; node++) {
1088 trunc_mode = trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos);
1089 if((gtr->emitl[node] <= spos) &&
1090 (gtr->emitr[node] >= epos)) { /* the full sequence is emitted from this nodes subtree */
1091 trunc_begin_node = node;
1092 }
1093 }
1094 if(trunc_begin_node == -1) {
1095 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() do_trunc TRUE, no node's subtree spans spos..epos");
1096 }
1097 /* save mode of first trace node, the ROOT_S state will have this mode too and we can't infer it from the ROOT's subtree */
1098 trunc_mode = trunc_mode_for_trace_node(gtr->emitl[trunc_begin_node], gtr->emitr[trunc_begin_node], spos, epos);
1099 }
1100
1101 /* Main loop to build the parsetree.
1102 * Because the gtr is already indexed in a preorder traversal,
1103 * we can preorder traverse it easily w/ a for loop...
1104 */
1105 tidx = -1; /* first state to attach to; -1 is special case for attaching root */
1106 for (node = 0; node < cm->nodes; node++) {
1107 if(do_trunc) {
1108 /* do_trunc is TRUE, determine if we should skip this node,
1109 * 4 reasons to skip:
1110 * - this node is prior to first node we'll use (trunc_begin_node) determined above
1111 * - BEGL/BEGR node for which parent BIF was not used
1112 * - END node outside spos..epos
1113 * - non BEGL/BEGR/END with entire subtree lpos..epos outside of spos..epos
1114 */
1115 if(node != 0 && node < trunc_begin_node) {
1116 continue; /* skip early nodes prior to first node determined above */
1117 }
1118 else if(gtr->state[node] == BEGL_nd || gtr->state[node] == BEGR_nd) {
1119 if(! used_A[gtr->prv[node]]) {
1120 /* parent BIF_B not used, so don't use this BEGL or BEGR node either */
1121 continue;
1122 }
1123 }
1124 else if(gtr->state[node] == END_nd) {
1125 if(spos > gtr->emitr[node] || epos < gtr->emitr[node]) {
1126 /* END_E subtree is outside spos..epos, ignore emitl because emitl[node] = emitr[node]+1 */
1127 continue;
1128 }
1129 }
1130 else { /* not BEGL,BEGR,END */
1131 if((spos > gtr->emitl[node] && spos > gtr->emitr[node]) ||
1132 (epos < gtr->emitl[node] && epos < gtr->emitr[node])) {
1133 /* entire subtree has 0 emits due to truncation */
1134 continue; /* skip nodes not visited due to truncation */
1135 }
1136 }
1137 /* if we get here, this node will be in the parsetree, keep track for potential children BEGL/BEGR */
1138 used_A[node] = TRUE;
1139 }
1140 /* A (big) switch on node type.
1141 */
1142 switch (gtr->state[node]) { /* e.g. switch on node type: */
1143 /* The root node.
1144 * Assume ROOT_S=0, ROOT_IL=1, ROOT_IR=2.
1145 * ended is always FALSE when we get here.
1146 */
1147 case ROOT_nd:
1148 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], 0,
1149 (do_trunc ? trunc_mode : TRMODE_J)); /* if do_trunc: use mode of first node */
1150 for (i = gtr->emitl[node]; i < gtr->emitl[gtr->nxtl[node]]; i++) {
1151 if ((! esl_abc_XIsGap(cm->abc, ax[i])) && (! esl_abc_XIsMissing(cm->abc, ax[i])) && (used_el == NULL || (! used_el[i]))) {
1152 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, gtr->emitr[node], 1,
1153 (do_trunc ? trunc_mode_for_trace_node(i, gtr->emitr[node], spos, epos) : TRMODE_J));
1154 }
1155 }
1156 for (j = gtr->emitr[node]; j > gtr->emitr[gtr->nxtl[node]]; j--) {
1157 if ((! esl_abc_XIsGap(cm->abc, ax[j])) && (! esl_abc_XIsMissing(cm->abc, ax[j])) && (used_el == NULL || (! used_el[j]))) {
1158 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, 2,
1159 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1160 }
1161 }
1162 break;
1163
1164 /* A bifurcation node.
1165 * Assume that we'll process the BEGL node next; push info
1166 * for BEGR onto the PDA.
1167 * If we ended above here, the B doesn't go into the parsetree.
1168 */
1169 case BIF_nd:
1170 if (ended) break;
1171 state = CalculateStateIndex(cm, node, BIF_B);
1172 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1173 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1174 if((status = esl_stack_IPush(pda, ended)) != eslOK) goto ERROR; /* remember our ending status */
1175 if((status = esl_stack_IPush(pda, tidx)) != eslOK) goto ERROR; /* remember index in tr; we pop in BEGR */
1176 break;
1177
1178 /* A MATP node.
1179 * If we see '-','-' in the seq and we ended already,
1180 * then we did an EL above here, just skip the node.
1181 * Else, this is a real state: emission or deletion.
1182 * If we thought we ended, that's invalid input.
1183 * Else, attach this guy.
1184 */
1185 case MATP_nd:
1186 if (esl_abc_XIsGap(cm->abc, ax[gtr->emitl[node]])) {
1187 if (esl_abc_XIsGap(cm->abc, ax[gtr->emitr[node]])) type = MATP_D;
1188 else type = MATP_MR;
1189 } else {
1190 if (esl_abc_XIsGap(cm->abc, ax[gtr->emitr[node]])) type = MATP_ML;
1191 else type = MATP_MP;
1192 }
1193 if (type == MATP_D && ended) break; /* used an EL above here, skip the node */
1194 if (ended) ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify(): MATP_nd we've ended but see an emission, ELs probably incorrectly handled");
1195
1196 state = CalculateStateIndex(cm, node, type);
1197 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1198 (do_trunc) ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J);
1199
1200 if(type == MATP_MP && used_el != NULL && cm->ndtype[node+1] != END_nd) {
1201 /* Check if we should use an EL. */
1202 if((status = check_for_el(ax, cm->abc, used_el, nxt_mi, nxt_el, gtr->emitl[node]+1, gtr->emitr[node]-1, &goto_el, &i, &j)) != eslOK) {
1203 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() MATP_nd ELs incorrectly handled");
1204 }
1205 if(goto_el) {
1206 state = cm->M;
1207 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1208 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1209 ended = TRUE;
1210 }
1211 }
1212 if(ended) break;
1213
1214 state = CalculateStateIndex(cm, node, MATP_IL);
1215 for (i = gtr->emitl[node]+1; i < gtr->emitl[gtr->nxtl[node]]; i++) {
1216 if ((! esl_abc_XIsGap(cm->abc, ax[i])) && (! esl_abc_XIsMissing(cm->abc, ax[i])) && (used_el == NULL || (! used_el[i]))) {
1217 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, gtr->emitr[node]-1, state,
1218 (do_trunc ? trunc_mode_for_trace_node(i, gtr->emitr[node]-1, spos, epos) : TRMODE_J));
1219 }
1220 }
1221
1222 state = CalculateStateIndex(cm, node, MATP_IR);
1223 for (j = gtr->emitr[node]-1; j > gtr->emitr[gtr->nxtl[node]]; j--) {
1224 if ((! esl_abc_XIsGap(cm->abc, ax[j])) && (! esl_abc_XIsMissing(cm->abc, ax[j])) && (used_el == NULL || (! used_el[j]))) {
1225 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1226 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1227 }
1228 }
1229 break;
1230
1231 /* A MATL node.
1232 * If we see '-','-' in the seq and we ended already,
1233 * then we did an EL above here, just skip the node.
1234 * Else, this is a real state (emission or deletion).
1235 * If we thought we ended, this is invalid input.
1236 * Else, attach this guy.
1237 */
1238 case MATL_nd:
1239 if (esl_abc_XIsGap(cm->abc, ax[gtr->emitl[node]])) type = MATL_D;
1240 else type = MATL_ML;
1241 if (type == MATL_D && ended) break; /* used an EL above here, skip this node */
1242 if (ended) ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify(): MATL_nd we've ended but see an emission, ELs probably incorrectly handled");
1243
1244 state = CalculateStateIndex(cm, node, type);
1245 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1246 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1247 if(type == MATL_ML && used_el != NULL && cm->ndtype[node+1] != END_nd) {
1248 /* Check if we should use an EL. */
1249 if((status = check_for_el(ax, cm->abc, used_el, nxt_mi, nxt_el, gtr->emitl[node]+1, gtr->emitr[node], &goto_el, &i, &j)) != eslOK) {
1250 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() MATL_nd ELs incorrectly handled");
1251 }
1252 if(goto_el) {
1253 state = cm->M;
1254 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1255 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1256 ended = TRUE;
1257 }
1258 }
1259 if(ended) break;
1260
1261 state = CalculateStateIndex(cm, node, MATL_IL);
1262 for (i = gtr->emitl[node]+1; i < gtr->emitl[gtr->nxtl[node]]; i++) {
1263 if ((! esl_abc_XIsGap(cm->abc, ax[i])) && (! esl_abc_XIsMissing(cm->abc, ax[i])) && (used_el == NULL || (! used_el[i]))) {
1264 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, gtr->emitr[node], state,
1265 (do_trunc ? trunc_mode_for_trace_node(i, gtr->emitr[node], spos, epos) : TRMODE_J));
1266 }
1267 }
1268 break;
1269
1270 /* MATR node.
1271 * Similar logic as MATL above.
1272 */
1273 case MATR_nd:
1274 if (esl_abc_XIsGap(cm->abc, ax[gtr->emitr[node]])) type = MATR_D;
1275 else type = MATR_MR;
1276 if (type == MATR_D && ended) break; /* used an EL above here, skip this node */
1277 if (ended) ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify(): MATR_nd we've ended but see an emission, ELs probably incorrectly handled");
1278
1279 state = CalculateStateIndex(cm, node, type);
1280 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1281 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1282 if(type == MATR_MR && used_el != NULL && cm->ndtype[node+1] != END_nd) {
1283 /* Check if we should use an EL */
1284 if((status = check_for_el(ax, cm->abc, used_el, nxt_mi, nxt_el, gtr->emitl[node], gtr->emitr[node]-1, &goto_el, &i, &j)) != eslOK) {
1285 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() MATR_nd ELs incorrectly handled");
1286 }
1287 if(goto_el) {
1288 state = cm->M;
1289 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1290 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1291 ended = TRUE;
1292 }
1293 }
1294 if(ended) break;
1295
1296 state = CalculateStateIndex(cm, node, MATR_IR);
1297 for (j = gtr->emitr[node]-1; j > gtr->emitr[gtr->nxtl[node]]; j--) {
1298 if ((! esl_abc_XIsGap(cm->abc, ax[j])) && (! esl_abc_XIsMissing(cm->abc, ax[j])) && (used_el == NULL || (! used_el[j]))) {
1299 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], j, state,
1300 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], j, spos, epos) : TRMODE_J));
1301 }
1302 }
1303 break;
1304
1305 /* BEGL_nd.
1306 * If ended, skip node.
1307 * Else, attach it.
1308 */
1309 case BEGL_nd:
1310 if (ended) break;
1311 state = CalculateStateIndex(cm, node, BEGL_S);
1312 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1313 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1314
1315 if(cm->ndtype[node+1] != END_nd && used_el != NULL) {
1316 /* Check if we should use an EL. Same rule as above for MATP, MATL, MATR */
1317 if((status = check_for_el(ax, cm->abc, used_el, nxt_mi, nxt_el, gtr->emitl[node], gtr->emitr[node], &goto_el, &i, &j)) != eslOK) {
1318 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() MATR_nd ELs incorrectly handled");
1319 }
1320 if(goto_el) {
1321 state = cm->M;
1322 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1323 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1324 ended = TRUE;
1325 }
1326 }
1327 break;
1328
1329 /* BEGR_nd.
1330 * Pop off info on whether we ended above this node in the CM.
1331 * If ended, skip node.
1332 * Logic different than BEGL above, because BEGR is dealing
1333 * with an insert left state. For the insert, if we think
1334 * we've ended already, that's an invalid input.
1335 */
1336 case BEGR_nd:
1337 esl_stack_IPop(pda, &tidx); /* recover parent bifurcation's index in trace */
1338 esl_stack_IPop(pda, &ended); /* did we end above here? */
1339
1340 if(ended) break;
1341 state = CalculateStateIndex(cm, node, BEGR_S);
1342 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_RIGHT_CHILD, gtr->emitl[node], gtr->emitr[node], state,
1343 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1344
1345 if(cm->ndtype[node+1] != END_nd && used_el != NULL) {
1346 /* Check if we should use an EL. Same rule as above for MATP, MATL, MATR, BEGL */
1347 if((status = check_for_el(ax, cm->abc, used_el, nxt_mi, nxt_el, gtr->emitl[node], gtr->emitr[node], &goto_el, &i, &j)) != eslOK) {
1348 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify() MATR_nd ELs incorrectly handled");
1349 }
1350 if(goto_el) {
1351 state = cm->M;
1352 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, j, state,
1353 (do_trunc ? trunc_mode_for_trace_node(i, j, spos, epos) : TRMODE_J));
1354 ended = TRUE;
1355 }
1356 }
1357 if(ended) break;
1358
1359 state = CalculateStateIndex(cm, node, BEGR_IL);
1360 for (i = gtr->emitl[node]; i < gtr->emitl[gtr->nxtl[node]]; i++) {
1361 if ((! esl_abc_XIsGap(cm->abc, ax[i])) && (! esl_abc_XIsMissing(cm->abc, ax[i])) && (used_el == NULL || (! used_el[i]))) {
1362 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, i, gtr->emitr[node], state,
1363 (do_trunc ? trunc_mode_for_trace_node(i, gtr->emitr[node], spos, epos) : TRMODE_J));
1364 }
1365 }
1366 break;
1367
1368 /* An END node.
1369 * If we've already ended (on EL), skip.
1370 */
1371 case END_nd:
1372 if (! ended) {
1373 state = CalculateStateIndex(cm, node, END_E);
1374 tidx = InsertTraceNodewithMode(tr, tidx, TRACE_LEFT_CHILD, -1, -1, state,
1375 (do_trunc ? trunc_mode_for_trace_node(gtr->emitl[node], gtr->emitr[node], spos, epos) : TRMODE_J));
1376 }
1377 break;
1378
1379 default:
1380 ESL_XFAIL(eslEINVAL, errbuf, "Transmogrify(): bogus node type");
1381 }
1382 }
1383 if(pda != NULL) esl_stack_Destroy(pda);
1384 if(nxt_mi != NULL) free(nxt_mi);
1385 if(nxt_el != NULL) free(nxt_el);
1386 if(used_A != NULL) free(used_A);
1387
1388 *ret_tr = tr;
1389 return eslOK;
1390
1391 ERROR:
1392 if(pda != NULL) esl_stack_Destroy(pda);
1393 if(nxt_mi != NULL) free(nxt_mi);
1394 if(nxt_el != NULL) free(nxt_el);
1395 if(used_A != NULL) free(used_A);
1396 if(tr != NULL) FreeParsetree(tr);
1397 *ret_tr = NULL;
1398 if(status == eslEMEM) ESL_FAIL(status, errbuf, "Out of memory");
1399 /* if status != eslEMEM, we've already filled errbuf, so we just return */
1400 return status;
1401 }
1402
1403 /* Function: check_for_el
1404 * Date: EPN, Fri May 25 13:48:01 2012
1405 *
1406 * Purpose: Helper function for Transmogrify(). Check if the
1407 * aligned sequence in <ax> from <i0> to <j0> implies
1408 * we should transition to an EL state and emit
1409 * all residues between <i0> and <j0>.
1410 *
1411 * The rule is that we should go to an EL if i0..j0 are all
1412 * gaps OR EL columns, with at least 1 EL emission AND all
1413 * EL columns in that stretch are contiguous. If all of
1414 * these are true we should transit to an EL, else we
1415 * shouldn't.
1416 *
1417 * Caller should have made sure we're called only from
1418 * states from which a legal EL is possible, and set <i0>
1419 * and <j0> appropriately.
1420 *
1421 * See definitions/comments in Transmogrify() for
1422 * meaning of arguments.
1423 *
1424 * Returns: eslOK on success. <ret_goto_el> is set to TRUE
1425 * if we should transit to EL and <ret_i> and
1426 * <ret_j> are set to boundaries of EL emissions
1427 * in ax. If we should not transit to EL,
1428 * <ret_goto_el> is set to FALSE, and <ret_i>
1429 * <ret_j> are set to 0.
1430 *
1431 * Throws: eslEINVAL if somethings wrong with the input,
1432 * <ret_goto_el> is set to FALSE, <ret_i> and <ret_j>
1433 * are set to FALSE.
1434 */
1435 static int
1436 check_for_el(const ESL_DSQ *ax, const ESL_ALPHABET *abc, const int *used_el, const int *nxt_mi, const int *nxt_el, int i0, int j0, int *ret_goto_el, int *ret_i, int *ret_j)
1437 {
1438 int i, j, i2;
1439 int goto_el = FALSE;
1440
1441 if(nxt_mi[i0-1] > nxt_el[i0-1] && nxt_mi[i0-1] > j0 && nxt_el[i0-1] <= j0) {
1442 /* gaps or ELs w/at least 1 EL emission stretch from i0..j0 => probably use an EL */
1443 /* determine first (i) and final (j) EL emission positions */
1444 i = i0;
1445 j = j0;
1446 while(esl_abc_XIsGap(abc, ax[i]) && i <= j0) i++;
1447 while(esl_abc_XIsGap(abc, ax[j]) && j >= i0) j--;
1448 if(i > j0 || (! used_el[i])) goto ERROR;
1449 if(j < i0 || (! used_el[j])) goto ERROR;
1450 /* final check: use EL if i..j are all EL positions, else don't.
1451 * we may have two discontiguous EL blocks implying two ELs further down.
1452 */
1453 for(i2 = i; i2 <= j; i2++) if(! used_el[i2]) break;
1454 if(i2 == j+1) goto_el = TRUE;
1455
1456 }
1457
1458 *ret_goto_el = goto_el;
1459 if(goto_el) *ret_i = i;
1460 else *ret_i = 0;
1461 if(goto_el) *ret_j = j;
1462 else *ret_j = 0;
1463
1464 return eslOK;
1465
1466 ERROR:
1467 *ret_goto_el = FALSE;
1468 *ret_i = 0;
1469 *ret_j = 0;
1470 return eslEINVAL;
1471 }
1472
1473 /* Function: trunc_mode_for_trace_node
1474 * Date: EPN, Thu Oct 20 11:32:46 2022
1475 *
1476 * Purpose: Helper function for Transmogrify(). Determine the
1477 * truncation mode for a trace node based on the
1478 * left and right emit positions (emitl and emitr)
1479 * and the first position that is not missing data due
1480 * to truncation at 5' end (spos) and final position
1481 * that is not missing data due to truncation at 3' end.
1482 *
1483 * Returns: TRMODE_J, TRMODE_L, TRMODE_R or TRMODE_T
1484 *
1485 */
1486 static int
1487 trunc_mode_for_trace_node(int emitl, int emitr, int spos, int epos)
1488 {
1489 if(emitl >= spos && emitr <= epos) return TRMODE_J;
1490 if(emitl >= spos && emitr > epos) return TRMODE_L;
1491 if(emitl < spos && emitr <= epos) return TRMODE_R;
1492 if(emitl < spos && emitr > epos) return TRMODE_T;
1493 return TRMODE_UNKNOWN; /* never reached */
1494 }
1495
1496 /* Function: ConsensusModelmaker()
1497 * EPN 08.29.06 based closely on HandModelmaker:
1498 * SRE 29 Feb 2000 [Seattle]; from COVE 2.0 code
1499 *
1500 * Purpose: Construct a model given a stated structure. The structure
1501 * is provided via a "ss_cons" (consensus structure) line, as would
1502 * occur in an annotated SELEX or Stockholm file. Only > and < characters
1503 * in this line are interpreted (as base pairs). Pseudoknots,
1504 * if annotated, are ignored.
1505 *
1506 * All positions/columns of the given structure are considered
1507 * consensus, and this is the difference b/t this function and
1508 * HandModelmaker. Also, this function does not take in a MSA
1509 * data structure. It was originally written for building a
1510 * new CM (a sub CM) that models a contiguous subset of columns
1511 * of it's template (mother) CM.
1512 *
1513 * Args: abc - the alphabet
1514 * errbuf - for error messages
1515 * ss_cons - input consensus structure string
1516 * clen - length of ss_cons, number of consensus columns
1517 * building_sub_model - TRUE if building a sub CM (usually TRUE)
1518 * ret_cm - RETURN: new model (maybe NULL)
1519 * ret_gtr - RETURN: guide tree for alignment (maybe NULL)
1520 *
1521 * Return: eslOK on success;
1522 * eslEINCOMPAT on contract violation
1523 */
1524 int
1525 ConsensusModelmaker(const ESL_ALPHABET *abc, char *errbuf, char *ss_cons, int clen, int building_sub_model, CM_t **ret_cm, Parsetree_t **ret_gtr)
1526 {
1527 int status;
1528 CM_t *cm = NULL; /* new covariance model */
1529 Parsetree_t *gtr = NULL; /* guide tree for alignment */
1530 ESL_STACK *pda = NULL; /* pushdown stack used in building gtr */
1531 int *ct = NULL; /* 0..alen-1 base pair partners array */
1532 int v; /* index of current node */
1533 int i,j,k; /* subsequence indices */
1534 int type; /* type of node we're working on */
1535 int diff, bestdiff, bestk; /* used while finding optimal split points */
1536 int nnodes; /* number of nodes in CM */
1537 int nstates; /* number of states in CM */
1538 int obs_clen; /* observed (MATL+MATR+2*MATP) consensus len */
1539
1540 if (ss_cons == NULL) ESL_FAIL(eslEINCOMPAT, errbuf, "No consensus structure annotation available in ConsensusModelmaker().");
1541
1542 /* 1. Determine a "ct" array, base-pairing partners for each position.
1543 * Disallow/ignore pseudoknots by removing them prior to making the ct array.
1544 * ct[] values give the index of a base pairing partner, or 0 for unpaired positions.
1545 * Even though ss_cons is in the 0..clen-1 coord system of msa, ct[]
1546 * comes back in the 1..alen coord system of the sequence.
1547 */
1548 esl_wuss_nopseudo(ss_cons, ss_cons); /* remove pknots in place */
1549 ESL_ALLOC(ct, (clen+1) * sizeof(int));
1550 if ((status = esl_wuss2ct(ss_cons, clen, ct)) != eslOK) ESL_FAIL(status, errbuf, "Consensus string is inconsistent in ConsensusModelMaker().");
1551
1552 /* 2. Construct a guide tree.
1553 * This codes is borrowed from HandModelmaker(), where it
1554 * was originally borrowed from yarn's KHS2Trace().
1555 *
1556 * We also keep track of how many states we'll need in the final CM,
1557 * so we'll know how much to allocate -- and the number of nodes,
1558 * for informational purposes.
1559 */
1560 nstates = nnodes = 0;
1561 gtr = CreateParsetree(25); /* the parse tree we'll grow */
1562 pda = esl_stack_ICreate(); /* a pushdown stack for our indices */
1563 obs_clen = 0;
1564
1565 /* Construction strategy has to make sure we number the nodes in
1566 * preorder traversal: for bifurcations, we can't attach the right
1567 * child until we've fully traversed the left side. Therefore, we have
1568 * to push what we intend to attach, and pop it later. And since we
1569 * don't know an index for the node until we attach it, we have no
1570 * place to put the node's data except the stack -- so we have to
1571 * push several numbers onto the stack: what type of node, what
1572 * subseq it's responsible for (emitl...emitr), and what node
1573 * index it attaches to.
1574 *
1575 * Note that we have to deal with the fact that ct is off-by-one
1576 * in both indices and values: e.g. the base pairing partner
1577 * j of residue i is ct[i-1]-1.
1578 */
1579 if((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; /* what node it's attached to */
1580 if((status = esl_stack_IPush(pda, 1)) != eslOK) goto ERROR; /* emitl */
1581 if((status = esl_stack_IPush(pda, clen)) != eslOK) goto ERROR; /* emitr */
1582 if((status = esl_stack_IPush(pda, ROOT_nd)) != eslOK) goto ERROR; /* "state" (e.g. node type) */
1583
1584 while (esl_stack_IPop(pda, &type) != eslEOD) /* pop a node type to attach */
1585 {
1586 esl_stack_IPop(pda, &j);
1587 esl_stack_IPop(pda, &i); /* i..j == subseq we're responsible for */
1588 esl_stack_IPop(pda, &v); /* v = index of parent node in gtr */
1589
1590 /* This node accounts for i..j, but we usually don't know how yet.
1591 * Six possibilities:
1592 * i > j; this is an END state; do nothing.
1593 * this is already assigned as a BEGIN; push i,j
1594 * i is unpaired; this is a MATL state; push i+1, j
1595 * j is unpaired; this is a MATR state; push i,j-1
1596 * i,j pair to each other; this is a MATP state; push i+1,j-1
1597 * i,j pair but not to each other; this is a BIFURC state;
1598 * pick mid ip <= mid < jp; push BEGIN i,mid and working i,mid,
1599 * and push BEGIN mid+1,j and working mid+1,j
1600 */
1601 if (i > j) {
1602 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, END_nd);
1603 nstates += 1; /* END_nd -> E_st */
1604 nnodes++;
1605 }
1606
1607 else if (type == ROOT_nd) { /* try to push i,j; but deal with INSL and INSR */
1608 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, ROOT_nd);
1609 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR; /* here v==0 always. */
1610 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1611 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1612 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1613 nstates += 3; /* ROOT_nd -> S_st, IL_st, IR_st */
1614 nnodes++;
1615 }
1616
1617 else if (type == BEGL_nd) { /* no inserts */
1618 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, BEGL_nd);
1619 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1620 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1621 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1622 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1623 nstates += 1; /* BEGL_nd -> S_st */
1624 nnodes++;
1625 }
1626
1627 else if (type == BEGR_nd) { /* look for INSL */
1628 v = InsertTraceNode(gtr, v, TRACE_RIGHT_CHILD, i, j, BEGR_nd);
1629 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1630 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1631 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1632 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1633 nstates += 2; /* BEGR_nd -> S_st IL_st */
1634 nnodes++;
1635 }
1636
1637 else if (ct[i] == 0) {
1638 /* i unpaired. This is a MATL node; allow INSL */
1639 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, MATL_nd);
1640 i++;
1641 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1642 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1643 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1644 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1645 nstates += 3; /* MATL_nd -> ML_st, D_st, IL_st */
1646 nnodes++;
1647 obs_clen++;
1648 }
1649
1650 else if (ct[j] == 0) { /* j unpaired. MATR node. Deal with INSR */
1651 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, MATR_nd);
1652 j--;
1653 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1654 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1655 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1656 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1657 nstates += 3; /* MATR_nd -> MR_st, D_st, IL_st */
1658 nnodes++;
1659 obs_clen++;
1660 }
1661
1662 else if (ct[i] == j) { /* i,j paired to each other. MATP. deal with INSL, INSR */
1663 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, MATP_nd);
1664 i++;
1665 j--;
1666 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1667 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1668 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1669 if((status = esl_stack_IPush(pda, DUMMY_nd)) != eslOK) goto ERROR; /* we don't know yet what the next node will be */
1670 nstates += 6; /* MATP_nd -> MP_st, ML_st, MR_st, D_st, IL_st, IR_st */
1671 nnodes++;
1672 obs_clen += 2;
1673 }
1674
1675 else /* i,j paired but not to each other. BIFURC. no INS. */
1676 {
1677 /* Here's the first of two places where we can optimize the topology
1678 * of a CM. (The other comes from choosing a state traversal order when
1679 * building the CM.) Imagine a multifurcation of four domains:
1680 * [1]..[2]..[3]..[4]
1681 * The "default leftwise" rule means that BEGL/INSL generates the
1682 * intervening sequences, so we must model the four stems as:
1683 * [1], ..[2], ..[3], ..[4]
1684 * but we have a choice of how we bifurcate:
1685 * (1,2)(3,4) 1,(2,(3,4)) ((1,2),3),4
1686 * Our choice affects the time and memory requirements of a divide
1687 * conquer alignment algorithm. (1,(2,(3,4)) is most efficient for
1688 * memory; (1,2)(3,4) is most efficient for time.
1689 *
1690 * So we may want to choose carefully from several possible split
1691 * points k (3, in the above example). A priori we only know one
1692 * possible midpoint precisely: ct[i]+1, the next base after closing
1693 * domain 1. We can find the others by scanning for them, and we can
1694 * be reasonably efficient about scanning by using ct[] to instantly
1695 * skip subdomains.
1696 */
1697 /* One possible rule: optimize by finding most balanced split.
1698 * Each stop of the following loop gives a possible midpoint k, which is
1699 * then evaluated, keeping track of the best split so far.
1700 */
1701 /* EPN, Tue Sep 9 07:41:28 2008
1702 * Note: HandModelmaker() was revised at precisely this point to chose
1703 * k based on split lengths of consensus positions (instead of alignment
1704 * positions), but we don't need that revision here b/c all positions
1705 * are consensus so this code was already doing what the revised HandModelmaker()
1706 * code now does. This is why this code block in Hand*() is more complex
1707 * than the one here.
1708 */
1709 v = InsertTraceNode(gtr, v, TRACE_LEFT_CHILD, i, j, BIF_nd);
1710
1711 bestk = ct[i]+1;
1712 bestdiff = clen+1; /* effectively infinity, difference in left/right subtree lengths can never exceed this */
1713 for (k = ct[i] + 1; k <= ct[j]; k = ct[k] + 1)
1714 {
1715 diff = abs((k-i) - (j-k+1));
1716 /* diff = abs(cons length modeled by left child minus cons length modeled by right child),
1717 * Note that left child is i..k-1, right child is k..j
1718 */
1719 if (diff < bestdiff) {
1720 bestdiff = diff;
1721 bestk = k;
1722 }
1723 while (ct[k] == 0) k++;
1724 }
1725 /* push the right BEGIN node first */
1726 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1727 if((status = esl_stack_IPush(pda, bestk)) != eslOK) goto ERROR;
1728 if((status = esl_stack_IPush(pda, j)) != eslOK) goto ERROR;
1729 if((status = esl_stack_IPush(pda, BEGR_nd)) != eslOK) goto ERROR;
1730 /* then push the left BEGIN node */
1731 if((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
1732 if((status = esl_stack_IPush(pda, i)) != eslOK) goto ERROR;
1733 if((status = esl_stack_IPush(pda, bestk-1)) != eslOK) goto ERROR;
1734 if((status = esl_stack_IPush(pda, BEGL_nd)) != eslOK) goto ERROR;
1735 nstates += 1; /* BIF_nd -> B_st */
1736 nnodes++;
1737 }
1738 } /* while something's on the stack */
1739 if(obs_clen != clen) cm_Fail("ConsensusModelMaker(): obs_clen: %d != passed in clen: %d\n", obs_clen, clen);
1740 esl_stack_Destroy(pda);
1741 free(ct);
1742
1743 /* OK, we've converted ct into gtr -- gtr is a tree structure
1744 * telling us the arrangement of consensus nodes. Now do the drill
1745 * for constructing a full model using this guide tree. We only have
1746 * to do this step if we're returning a CM though. (Sometimes caller
1747 * may only want gtr.)
1748 */
1749 if(ret_cm != NULL) {
1750 cm = CreateCM(nnodes, nstates, clen, abc);
1751 if((status = cm_from_guide(cm, errbuf, gtr, building_sub_model)) != eslOK) return status;
1752 CMZero(cm);
1753 cm->clen = clen;
1754 /* note map and rf stay NULL (invalid) we could copy them from their mother,
1755 * but not in this function (because we don't have the mother CM here) */
1756 }
1757
1758 if (ret_cm != NULL) *ret_cm = cm; else if(cm != NULL) FreeCM(cm);
1759 if (ret_gtr != NULL) *ret_gtr = gtr; else if(gtr != NULL) FreeParsetree(gtr);
1760 return eslOK;
1761
1762 ERROR:
1763 ESL_FAIL(eslEMEM, errbuf, "ConsensusModelMaker(): memory allocation error.");
1764 return eslEMEM; /* never reached */
1765
1766 }
1767
1768 /**************************************************************************
1769 * EPN 09.25.06 [Parkway Hotel St. Louis, MO]
1770 * cm_find_and_detach_dual_inserts()
1771 *
1772 * Given a CM (potentially in counts form), find cases where two
1773 * insert states insert at the same position (due to an ambiguity in the
1774 * CM architecture). We know from the way CMs are constructed in
1775 * HandModelmaker() that one of these states must be an IL or IR state
1776 * immediately prior to an END_E state, and by the way counts are
1777 * collected in ParseTreeCount() that this END_E-1 state will
1778 * not be filled with any counts from the input seed sequences.
1779 * However, to be safe, there's an option to this function
1780 * to check to make sure both of these guarantees hold.
1781 *
1782 * Usually if this option is enabled with do_check=TRUE, the
1783 * CM is in counts form so its possible to check to make sure
1784 * the END_E-1 has 0 counts. Also, in this case the other option,
1785 * do_detach is set to FALSE to tell the function not to detach
1786 * the insert quite yet, we want to wait until the model has
1787 * been priorified - and once it has we revisit this function
1788 * with the do_check option as FALSE and do_detach as TRUE.
1789 * With do_detach == TRUE, we 'detach' the END_E-1 state by
1790 * setting all transitions into it as 0.0, making it impossible
1791 * to reach.
1792 *
1793 * There should be exactly 1 dual insert for every END_E state.
1794 *
1795 * Args:
1796 * CM_t cm,
1797 * int do_check; TRUE to check the
1798 * Returns: TRUE on success if all dual inserts are found and detached.
1799 */
1800 int
1801 cm_find_and_detach_dual_inserts(CM_t *cm, int do_check, int do_detach)
1802 {
1803
1804 int status;
1805 CMEmitMap_t *emap; /* consensus emit map for the cm */
1806 int *cc2lins_map;
1807 int *cc2rins_map;
1808 int cc;
1809 int nd;
1810 int end_e_ct;
1811 int detach_ct;
1812 int v;
1813
1814 end_e_ct = 0;
1815 detach_ct = 0;
1816
1817 /* Determine the number of END_E states in the model, this
1818 * will be the number of inserts we want to detach.
1819 */
1820 for(v = 0; v <= cm->M; v++)
1821 if(cm->sttype[v] == E_st)
1822 end_e_ct++;
1823
1824 emap = CreateEmitMap(cm);
1825 /*DumpEmitMap(stdout, emap, cm);*/
1826
1827 /* Based on the emitmap, make map of which nodes have an insert state that
1828 * inserts AFTER (in case of *lmap) and BEFORE (in case of *rmap)
1829 * each consensus node.
1830 * cc2lins_map[cc] = v, where cm state v is an IL_st that
1831 * emits after consensus column cc.
1832 * cc2rins_map[cc] = v, where cm state v is an IR_st that
1833 * emits after consensus column cc.
1834 * if no such state exists the value will be -1.
1835 */
1836
1837 /* Allocate and initialize */
1838 ESL_ALLOC(cc2lins_map, sizeof(int) * (emap->clen + 1));
1839 ESL_ALLOC(cc2rins_map, sizeof(int) * (emap->clen + 1));
1840 for(cc = 0; cc <= emap->clen; cc++)
1841 {
1842 cc2lins_map[cc] = -1;
1843 cc2rins_map[cc] = -1;
1844 }
1845 /* fill in the map */
1846 /* ROOT is special */
1847 cc2lins_map[0] = 1; /* ROOT_IL */
1848 cc2rins_map[emap->clen] = 2; /* ROOT_IR */
1849 for(nd = 0; nd < cm->nodes; nd++)
1850 {
1851 switch (cm->ndtype[nd]) {
1852 case MATP_nd:
1853 cc2lins_map[emap->lpos[nd]] = cm->nodemap[nd] + 4; /* MATP_IL */
1854 cc2rins_map[emap->rpos[nd] - 1] = cm->nodemap[nd] + 5; /* MATP_IR */
1855 break;
1856
1857 case MATL_nd:
1858 cc2lins_map[emap->lpos[nd]] = cm->nodemap[nd] + 2; /* MATL_IL */
1859 break;
1860
1861 case MATR_nd:
1862 cc2rins_map[emap->rpos[nd] - 1] = cm->nodemap[nd] + 2; /* MATR_IR */
1863 break;
1864
1865 case BEGR_nd:
1866 cc2lins_map[emap->lpos[nd]] = cm->nodemap[nd] + 1; /* BEGR_IL */
1867 break;
1868
1869 default: {} /*do nothing*/
1870 }
1871 }
1872
1873 for(cc = 0; cc <= emap->clen; cc++)
1874 {
1875 if(cc2lins_map[cc] != -1 && cc2rins_map[cc] != -1)
1876 {
1877 detach_ct++;
1878 /* Found a dual insert. */
1879 if(do_check)
1880 {
1881 if(!(cm_check_before_detaching(cm, cc2lins_map[cc], cc2rins_map[cc])))
1882 cm_Fail("ERROR cm_check_before_detaching() returned false\n");
1883 }
1884 if(do_detach)
1885 if(!(cm_detach_state(cm, cc2lins_map[cc], cc2rins_map[cc])))
1886 cm_Fail("ERROR cm_detach_state() returned false\n");
1887 }
1888 }
1889
1890 FreeEmitMap(emap);
1891 free(cc2lins_map);
1892 free(cc2rins_map);
1893
1894 if(detach_ct != end_e_ct)
1895 return FALSE;
1896 else
1897 return TRUE;
1898
1899 ERROR:
1900 cm_Fail("Memory allocation error.");
1901 return FALSE; /* never reached */
1902 }
1903
1904 /**************************************************************************
1905 * EPN 09.18.06
1906 * cm_detach_state()
1907 *
1908 * Given two insert states that map to the same state in the original,
1909 * template CM, detach one of the them from the rest of the model by
1910 * setting all transitions into it to 0.0. We choose the state to detach
1911 * as the state that is immediately prior to an END_E in the sub_cm.
1912 * This will always be the case because the sole source of alignment
1913 * ambiguity in the CM architecture always involves 1 insert state
1914 * immediately before an END_E.
1915 *
1916 * Args:
1917 * CM_t cm,
1918 * int insert1;
1919 * int insert2;
1920 * Returns: TRUE on success if insert1 or insert2 is a state immediately
1921 * before an END_E, and we've detached it.
1922 * FALSE otherwise
1923 */
1924 int
1925 cm_detach_state(CM_t *cm, int insert1, int insert2)
1926 {
1927 /*printf("\t**in cm_detach_state: insert1: %d | insert2: %d\n", insert1, insert2);*/
1928
1929 int ret_val;
1930 int x, y;
1931 int to_detach;
1932 int x_offset;
1933
1934 ret_val = FALSE;
1935
1936 if(insert1 == insert2)
1937 cm_Fail("ERROR in cm_detach_state: insert1==insert2:%d\n", insert1);
1938
1939 if(cm->sttype[insert1+1] == E_st)
1940 {
1941 ret_val = TRUE;
1942 to_detach = insert1;
1943 }
1944 else
1945 {
1946 if(cm->sttype[insert2+1] != E_st)
1947 cm_Fail("ERROR: in cm_detach_state insert1: %d and insert2: %d neither map to END_E-1 states.\n", insert1, insert2);
1948 if(ret_val)
1949 cm_Fail("ERROR: in cm_detach_state insert1: %d and insert2: %d both map to END_E-1 states.\n", insert1, insert2);
1950 ret_val = TRUE;
1951 to_detach = insert2;
1952 }
1953 if(ret_val)
1954 {
1955 /* Determine if we're detaching an IL_st, or the rare case of a MATP_IR st */
1956 if(cm->sttype[to_detach] == IL_st)
1957 x_offset = 0;
1958 else
1959 {
1960 if(cm->stid[to_detach] != MATP_IR)
1961 cm_Fail("ERROR: in cm_detach_state trying to detach a non-IL, non-MATP_IR state!\n");
1962 x_offset = 1; /* MATP_* -> MATP_IR is second possible transition for MATP_*,
1963 * unless * == MATP_IR, but we don't get there in for loop below. */
1964 }
1965 for (y = cm->pnum[to_detach]-1; y >= 1; y--)
1966 /* y >= 1 means we never get to
1967 * to_detach->to_detach prob, which is irrelevant. */
1968 {
1969 x = cm->plast[to_detach] - y;
1970 cm->t[x][x_offset] = 0.0; /* x is a split set state in same node
1971 * as insert1, we're setting transition
1972 * from x -> to_detach as impossible.
1973 */
1974 /* Renormalize transitions out of x */
1975 esl_vec_FNorm(cm->t[x], cm->cnum[x]);
1976 /*printf("****setting transition probabilitity of x: %d to to_detach: %d cm->t[x][%d] as 0.0\n", x, to_detach, x_offset);*/
1977 }
1978 }
1979 return ret_val;
1980 }
1981
1982 /**************************************************************************
1983 * EPN 09.25.06
1984 * cm_check_before_detaching()
1985 *
1986 * Given two insert states that map to the same state in a CM, and
1987 * given the CM in counts form (after being filled with counts from
1988 * the parses implicit in the seed alignment), check the following
1989 * two guarantees are met:
1990 * (a) exactly one of the two inserts is immediately prior to an END_E
1991 * state (END_E - 1).
1992 * (b) the END_E - 1 state has been parameterized with 0 counts from
1993 * the input alignment.
1994 *
1995 * NOTE: A special case is when insert1 is the MATP_IL and insert2 the
1996 * MATP_IR of the same MATP node. This is the only case where
1997 * the insert state to be detached is not an IL state, but rather
1998 * the MATP_IR (but the guarantees still hold, the MATP_IR is
1999 * END_E - 1, and always gets 0 counts)
2000 *
2001 * Args:
2002 * CM_t cm,
2003 * int insert1;
2004 * int insert2;
2005 * Returns: TRUE on success if insert1 or insert2 follow the guarantees
2006 * FALSE otherwise
2007 */
2008 int
2009 cm_check_before_detaching(CM_t *cm, int insert1, int insert2)
2010 {
2011 int ret_val;
2012 int i, yoffset;
2013 int to_detach;
2014 /*int to_keep;*/
2015 float diff;
2016
2017 ret_val = FALSE;
2018
2019 if(insert1 == insert2)
2020 cm_Fail("ERROR in cm_check_before_detaching(), insert1==insert2 (%d)\n", insert1);
2021
2022 if(cm->sttype[insert1+1] == E_st)
2023 {
2024 ret_val = TRUE;
2025 to_detach = insert1;
2026 /*to_keep = insert2;*/
2027 }
2028 if(cm->sttype[insert2+1] == E_st)
2029 {
2030 if(ret_val)
2031 cm_Fail("ERROR: in cm_check_before_detaching() insert1: %d and insert2: %d both map to END_E-1 states.\n", insert1, insert2);
2032 ret_val = TRUE;
2033 to_detach = insert2;
2034 /*to_keep = insert1;*/
2035 }
2036
2037 /* check to make sure we have 0.0 counts in to_detach */
2038 if(ret_val)
2039 {
2040 for(i = 0; i < cm->abc->K; i++)
2041 {
2042 if(cm->e[to_detach][i] >= 0.)
2043 diff = cm->e[to_detach][i] - 0.;
2044 else
2045 diff = 0. - cm->e[to_detach][i];
2046 if(diff > 0.000001)
2047 cm_Fail("ERROR, to_detach state: %d e->[%d] is non-zero but rather %f\n", to_detach, i, cm->e[to_detach][i]);
2048 }
2049 for(yoffset = 0; yoffset < cm->cnum[to_detach]; yoffset++)
2050 {
2051 /*printf("to_detach t[%d] cts: %f\n", yoffset, cm->t[to_detach][yoffset]);*/
2052 if(cm->t[to_detach][yoffset] >= 0.)
2053 diff = cm->t[to_detach][yoffset] - 0.;
2054 else
2055 diff = 0. - cm->t[to_detach][yoffset];
2056 if(diff > 0.000001)
2057 cm_Fail("ERROR, to_detach state: %d t->[%d] is non-zero but rather %f\n", to_detach, yoffset, cm->t[to_detach][yoffset]);
2058 }
2059 }
2060 return ret_val;
2061 }
2062
2063 /* Functions: clean_cs()
2064 * Date: SRE, Fri May 17 14:52:42 2002 [St. Louis]
2065 *
2066 * Purpose: Verify and (if needed) clean the consensus structure annotation.
2067 */
2068 int
2069 clean_cs(char *cs, int alen, int be_quiet)
2070 {
2071 int status;
2072 int i;
2073 int *ct;
2074 //int nright = 0;
2075 //int nleft = 0;
2076 int nbad = 0;
2077 char example;
2078 int first;
2079 int has_pseudoknots = FALSE;
2080
2081 /* 1. Check if we have a good CS line with >= 0 pseudoknotted
2082 * base pairs.
2083 */
2084 ESL_ALLOC(ct, (alen+1) * sizeof(int));
2085 if (esl_wuss2ct(cs, alen, ct) != eslOK)
2086 cm_Fail("Consensus structure string is inconsistent");
2087 free(ct);
2088
2089 /* 2. CS line is good, check for and remove pseudoknots
2090 * if necessary. */
2091 if (check_for_pknots(cs, alen)) {
2092 has_pseudoknots = TRUE;
2093 if(!be_quiet) printf(" [Consensus structure has annotated pseudoknots that will be ignored.]\n");
2094 fflush(stdout);
2095 }
2096 else return TRUE; /* we're good, no need to clean it, there's no
2097 * pseudoknots */
2098
2099 /* 3. Delete everything we don't recognize.
2100 */
2101 for (i = 0; i < alen; i++)
2102 {
2103 if (strchr("{[(<", cs[i]) != NULL) ; //nleft++;
2104 else if (strchr(">)]}", cs[i]) != NULL) ; //nright++;
2105 else if (strchr(":_-,.~", cs[i]) != NULL) ;
2106 else if (has_pseudoknots && isalpha((int) cs[i])) cs[i] = '.';
2107 else { /* count bad chars; remember first one; replace w/gap */
2108 if (nbad == 0) { example = cs[i]; first = i; }
2109 nbad++;
2110 cs[i] = '.';
2111 }
2112 }
2113 if (nbad > 0) {
2114 if(!be_quiet) printf(" [Removed %d bad chars from consensus line. Example: a %c at position %d.]\n",
2115 nbad, example, first);
2116 fflush(stdout);
2117 }
2118
2119 /* Check it again.
2120 */
2121 ESL_ALLOC(ct, (alen+1) * sizeof(int));
2122 status = esl_wuss2ct(cs, alen, ct);
2123 free(ct);
2124 if(status == eslOK)
2125 return TRUE;
2126 printf(" [Failed to parse the consensus structure line.]\n");
2127 return FALSE;
2128
2129 ERROR:
2130 cm_Fail("Memory allocation error.");
2131 return FALSE; /* never reached */
2132 }
2133
2134 /* Functions: check_for_pknots()
2135 * Date: EPN, Mon Aug 6 14:46:24 2007
2136 *
2137 * Purpose: Simple check for pseudoknots in a consensus structure annotation.
2138 * ASSUMES: CS has already been checked for consistency.
2139 */
2140 static int
2141 check_for_pknots(char *cs, int alen)
2142 {
2143 int i;
2144 for (i = 0; i < alen; i++)
2145 {
2146 if (isalpha((int) cs[i]))
2147 return TRUE; /* assumes we know the CS is consistent */
2148 }
2149 return FALSE;
2150 }
2151
2152
2153 /* Function: cm_zero_flanking_insert_counts()
2154 * Synopsis: Zero transition counts involved with ROOT_IL and ROOT_IR.
2155 * Incept: EPN, Tue Apr 3 14:16:46 2012
2156 *
2157 * Purpose: Given a CM in counts form (in the process of being built)
2158 * zero the transitions into and out of the ROOT_IL and
2159 * ROOT_IR emissions. Currently only called by cmbuild.
2160 * Goal is to ignore any residues in the input MSA that
2161 * occur before the first or after the last consensus
2162 * column. That is, after this function is finished the CM
2163 * should be identical to one in counts form that was built
2164 * from an identical MSA with zero residues before the first
2165 * consensus position and after the last.
2166 *
2167 * Returns: eslOK on success;
2168 * Throws: eslFAIL if CM does not seem to be in counts form, errbuf filled.
2169 */
2170 int
2171 cm_zero_flanking_insert_counts(CM_t *cm, char *errbuf)
2172 {
2173 int status;
2174
2175 /* verify model is not yet configured */
2176 if((status = cm_nonconfigured_Verify(cm, errbuf)) != eslOK) return status;
2177
2178 /* There are four possible node types for node 1 (node following the
2179 * ROOT node), BIF, MATP, MATL and MATR. We add the counts from ROOT_IL
2180 * and ROOT_IR into each non-insert state in node 1 to the count from
2181 * ROOT_S into that non-insert state. After doing this, the counts
2182 * will be as if the ROOT_IL and ROOT_IR emissions did not exist
2183 * in the input MSA the counts were collected from.
2184 */
2185
2186 /* For all cases, first set counts from ROOT_S -> ROOT_IL and
2187 * ROOT_S -> ROOT_IR to zero
2188 */
2189 cm->t[0][0] = 0.; /* ROOT_S -> ROOT_IL */
2190 cm->t[0][1] = 0.; /* ROOT_S -> ROOT_IR */
2191
2192 if(cm->ndtype[1] == BIF_nd) {
2193 cm->t[0][2] += cm->t[1][2]; /* ROOT_S->BIF_B += ROOT_IL->BIF_B */
2194 cm->t[0][2] += cm->t[2][1]; /* ROOT_S->BIF_B += ROOT_IR->BIF_B */
2195 }
2196 else if(cm->ndtype[1] == MATP_nd) {
2197 cm->t[0][2] += cm->t[1][2]; /* ROOT_S->MATP_MP += ROOT_IL->MATP_MP */
2198 cm->t[0][2] += cm->t[2][1]; /* ROOT_S->MATP_MP += ROOT_IR->MATP_MP */
2199
2200 cm->t[0][3] += cm->t[1][3]; /* ROOT_S->MATP_ML += ROOT_IL->MATP_ML */
2201 cm->t[0][3] += cm->t[2][2]; /* ROOT_S->MATP_ML += ROOT_IR->MATP_ML */
2202
2203 cm->t[0][4] += cm->t[1][4]; /* ROOT_S->MATP_MR += ROOT_IL->MATP_MR */
2204 cm->t[0][4] += cm->t[2][3]; /* ROOT_S->MATP_MR += ROOT_IR->MATP_MR */
2205
2206 cm->t[0][5] += cm->t[1][5]; /* ROOT_S->MATP_D += ROOT_IL->MATP_D */
2207 cm->t[0][5] += cm->t[2][4]; /* ROOT_S->MATP_D += ROOT_IR->MATP_D */
2208 }
2209 else { /* MATL_nd or MATR_nd */
2210 cm->t[0][2] += cm->t[1][2]; /* ROOT_S->MAT{L,R}_M{L,R} += ROOT_IL->MAT{L,R}_M{L,R} */
2211 cm->t[0][2] += cm->t[2][1]; /* ROOT_S->MAT{L,R}_M{L,R} += ROOT_IR->MAT{L,R}_M{L,R} */
2212
2213 cm->t[0][3] += cm->t[1][3]; /* ROOT_S->MAT{L,R}_D += ROOT_IL->MAT{L,R}_D */
2214 cm->t[0][3] += cm->t[2][2]; /* ROOT_S->MAT{L,R}_D += ROOT_IR->MAT{L,R}_D */
2215 }
2216
2217 /* Final step: zero transition counts out of ROOT_IL and ROOT_IR.
2218 * These will be completely determined by the prior. We have to
2219 * do this as a final step because we needed these counts
2220 * above.
2221 */
2222 esl_vec_FSet(cm->t[1], MAXCONNECT, 0.);
2223 esl_vec_FSet(cm->t[2], MAXCONNECT, 0.);
2224
2225 return eslOK;
2226 }
2227