Debian Codegraph @

src/display.c

raw symbols SCIP
1 /* display.c
2 * SRE, Thu May 23 08:18:05 2002 [St. Louis]
3 *
4 * Routines for formatting and displaying parse trees
5 * for output.
6 */
7
8 #include <esl_config.h>
9 #include <p7_config.h>
10 #include "config.h"
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <ctype.h>
16 #include <math.h>
17 #include <time.h>
18
19 #include "easel.h"
20 #include "esl_getopts.h"
21 #include "esl_stack.h"
22 #include "esl_vectorops.h"
23
24 #include "hmmer.h"
25
26 #include "infernal.h"
27
28 static int *createMultifurcationOrderChart(CM_t *cm);
29 static int bp_is_canonical(char lseq, char rseq);
30 static void createFaceCharts(CM_t *cm, int **ret_inface, int **ret_outface);
31
32 /* Function: CreateFancyAli()
33 * Incept: SRE, Thu May 23 13:46:09 2002 [St. Louis]
34 *
35 * Purpose: Given a trace (and the model and sequence it corresponds
36 * to), create a pairwise alignment for display; return in a Fancyali_t
37 * structure.
38 *
39 * Args: abc - alphabet to create alignment with (often cm->abc)
40 * tr - parsetree for cm aligned to dsq
41 * cm - model
42 * cons - consensus information for cm; see CreateCMConsensus()
43 * dsq - digitized sequence
44 * do_noncanonical - mark half-bps and negative scoring bps that are non-canonicals in top line with 'v'
45 * (by default, all negative scoring and half-bps are marked with 'x')
46 * pcode - posterior code
47 *
48 *
49 * Returns: fancy alignment structure.
50 * Caller frees, with FreeFancyAli(ali).
51 *
52 * Xref: STL6 p.58
53 */
54 Fancyali_t *
55 CreateFancyAli(const ESL_ALPHABET *abc, Parsetree_t *tr, CM_t *cm, CMConsensus_t *cons, ESL_DSQ *dsq, int do_noncanonical, char *pcode)
56 {
57 int status;
58 Fancyali_t *ali; /* alignment structure we're building */
59 ESL_STACK *pda; /* pushdown automaton used to traverse trace */
60 int type; /* type of pda move: PDA_RESIDUE, PDA_STATE */
61 int v; /* state index */
62 int nd; /* node index */
63 int ti; /* position in trace */
64 int qinset, tinset; /* # consensus nt skipped by an EL, or in an EL */
65 int ninset; /* max # nt in an EL */
66 int pos; /* position in growing ali */
67 int lc, rc; /* indices for left, right pos in consensus */
68 int symi, symj;
69 int d;
70 char mode;
71 int lrf, rrf; /* chars in reference line; left, right */
72 int lstr, rstr; /* chars in structure line; left, right */
73 int lcons, rcons; /* chars in consensus line; left, right */
74 int lmid, rmid; /* chars in ali quality line; left, right */
75 int ltop, rtop; /* chars in optional noncompensatory line; left, right */
76 int lnegnc, rnegnc; /* chars in optional noncanonical line; left, right */
77 int lseq, rseq; /* chars in aligned target line; left, right */
78 int lpost, rpost; /* chars in aligned posteriors, left, right */
79 int do_left, do_right;/* flags to generate left, right */
80 int cpos_l, cpos_r; /* positions in consensus (1..clen) */
81 int spos_l, spos_r; /* positions in dsq (1..L) */
82 int have_pcodes;
83 int nw; /* number of chars written by snprintf, checked to avoid compiler warnings */
84
85 /* Contract check. We allow the caller to specify the alphabet they want the
86 * resulting MSA in, but it has to make sense (see next few lines). */
87 if(cm->abc->type == eslRNA)
88 {
89 if(abc->type != eslRNA && abc->type != eslDNA)
90 cm_Fail("ERROR in CreateFancyAli(), cm alphabet is RNA, but requested output alphabet is neither DNA nor RNA.");
91 }
92 else if(cm->abc->K != abc->K)
93 cm_Fail("ERROR in CreateFancyAli(), cm alphabet size is %d, but requested output alphabet size is %d.", cm->abc->K, abc->K);
94
95 ESL_ALLOC(ali, sizeof(Fancyali_t));
96 have_pcodes = (pcode != NULL) ? TRUE : FALSE;
97
98 /* Calculate length of the alignment display.
99 * MATP node : +2
100 * MATL, MATR node : +1
101 * IL, IR state : +1
102 * EL: : 4 + width of length display : "*[nn]*"
103 * anything else : 0.
104 */
105 ali->len = 0;
106 for (ti = 0; ti < tr->n; ti++)
107 {
108 v = tr->state[ti];
109 if (v == cm->M) { /* special case: local exit into EL */
110 nd = cm->ndidx[tr->state[ti-1]]; /* calculate node that EL replaced */
111 qinset = cons->rpos[nd] - cons->lpos[nd] + 1;
112 tinset = tr->emitr[ti] - tr->emitl[ti] + 1;
113 ninset = ESL_MAX(qinset,tinset);
114 ali->len += 4;
115 do { ali->len++; ninset/=10; } while (ninset); /* poor man's (int)log_10(ninset)+1 */
116 continue;
117 } else {
118 nd = cm->ndidx[v];
119 if (cm->sttype[v] == IL_st || cm->sttype[v] == IR_st)
120 ali->len += 1;
121 else if (cm->ndtype[nd] == MATL_nd || cm->ndtype[nd] == MATR_nd)
122 ali->len += 1;
123 else if (cm->ndtype[nd] == MATP_nd)
124 ali->len += 2;
125 }
126 /* Catch marginal-type local ends and treat them like EL for output */
127 if ((tr->nxtl[ti] == -1) && (cm->sttype[v] != E_st)) {
128 nd = cm->ndidx[tr->state[ti]];
129 qinset = cons->rpos[nd] - cons->lpos[nd] + 1;
130 tinset = tr->emitr[ti] - tr->emitl[ti] + 1;
131 if (tinset > 0) tinset--;
132 ninset = ESL_MAX(qinset,tinset);
133 ali->len += 4;
134 do { ali->len++; ninset/=10; } while (ninset); /* poor man's (int)log_10(ninset)+1 */
135 }
136 }
137
138 /* Allocate and initialize.
139 * Blank the reference lines (memset calls) - only needed
140 * because of the way we deal w/ EL.
141 */
142 if (cm->rf != NULL )
143 ESL_ALLOC(ali->rf, sizeof(char) * (ali->len+1));
144 else
145 ali->rf = NULL;
146 ESL_ALLOC(ali->cstr, sizeof(char) * (ali->len+1));
147 ESL_ALLOC(ali->cseq, sizeof(char) * (ali->len+1));
148 ESL_ALLOC(ali->mid, sizeof(char) * (ali->len+1));
149 ESL_ALLOC(ali->top, sizeof(char) * (ali->len+1));
150 ESL_ALLOC(ali->aseq, sizeof(char) * (ali->len+1));
151 if(have_pcodes) {
152 ESL_ALLOC(ali->pcode, sizeof(char) * (ali->len+1));
153 }
154 else {
155 ali->pcode = NULL;
156 }
157 ESL_ALLOC(ali->scoord, sizeof(int) * ali->len);
158 ESL_ALLOC(ali->ccoord, sizeof(int) * ali->len);
159
160 if (cm->rf != NULL) memset(ali->rf, ' ', ali->len);
161 memset(ali->cstr, ' ', ali->len);
162 memset(ali->cseq, ' ', ali->len);
163 memset(ali->mid, ' ', ali->len);
164 memset(ali->top, ' ', ali->len);
165 memset(ali->aseq, ' ', ali->len);
166 if(have_pcodes) {
167 memset(ali->pcode, ' ', ali->len);
168 }
169 for (pos = 0; pos < ali->len; pos++)
170 ali->ccoord[pos] = ali->scoord[pos] = 0;
171
172 /* Fill in the lines: traverse the traceback.
173 */
174 pos = 0;
175 if((pda = esl_stack_ICreate()) == NULL) goto ERROR;
176 if((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR;
177 if((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
178
179 while (esl_stack_IPop(pda, &type) != eslEOD)
180 {
181 if (type == PDA_RESIDUE) {
182 if (cm->rf != NULL) {
183 esl_stack_IPop(pda, &rrf);
184 ali->rf[pos] = rrf;
185 }
186 esl_stack_IPop(pda, &rstr); ali->cstr[pos] = rstr;
187 esl_stack_IPop(pda, &rcons); ali->cseq[pos] = rcons;
188 esl_stack_IPop(pda, &rmid); ali->mid[pos] = rmid;
189 esl_stack_IPop(pda, &rtop); ali->top[pos] = rtop;
190 esl_stack_IPop(pda, &rseq); ali->aseq[pos] = rseq;
191 if(have_pcodes) {
192 esl_stack_IPop(pda, &rpost); ali->pcode[pos] = rpost;
193 }
194 esl_stack_IPop(pda, &cpos_r); ali->ccoord[pos] = cpos_r;
195 esl_stack_IPop(pda, &spos_r); ali->scoord[pos] = spos_r;
196 pos++;
197 continue;
198 }
199
200 /* Else, we're PDA_STATE - e.g. dealing with a trace node.
201 */
202 esl_stack_IPop(pda, &ti);
203 v = tr->state[ti];
204
205 /* Deal with EL (local ends, state M) as a special case.
206 * We get away with only writing into aseq because we've
207 * memset() the display strings to blank.
208 */
209 if (v == cm->M) {
210 int numwidth; /* number of chars to leave for displaying width numbers */
211
212 nd = 1 + cm->ndidx[tr->state[ti-1]]; /* calculate node that EL replaced */
213 qinset = cons->rpos[nd] - cons->lpos[nd] + 1;
214 tinset = tr->emitr[ti] - tr->emitl[ti] + 1;
215 ninset = ESL_MAX(qinset,tinset);
216 numwidth = 0; do { numwidth++; ninset/=10; } while (ninset); /* poor man's (int)log_10(ninset)+1 */
217 memset(ali->cstr+pos, '~', numwidth+4);
218 if((nw = snprintf(ali->cseq+pos, numwidth+5, "*[%*d]*", numwidth, qinset)) != (numwidth+4)) goto ERROR; /* +5 is length of "*[" + "]*" + 1 for null terminating char */
219 if((nw = snprintf(ali->aseq+pos, numwidth+5, "*[%*d]*", numwidth, tinset)) != (numwidth+4)) goto ERROR; /* +5 is length of "*[" + "]*" + 1 for null terminating char */
220 /* do nothing for posteriors here, they'll stay as they were init'ed, as ' ' */
221 pos += 4 + numwidth;
222 continue;
223 }
224
225 /* Fetch some info into tmp variables, for "clarity"
226 */
227 nd = cm->ndidx[v]; /* what CM node we're in */
228 lc = cons->lpos[nd]; /* where CM node aligns to in consensus */
229 rc = cons->rpos[nd];
230 symi = dsq[tr->emitl[ti]]; /* residue indices that node is aligned to */
231 symj = dsq[tr->emitr[ti]];
232 if(have_pcodes) { /* posterior codes are indexed 0..alen-1, off-by-one w.r.t dsq */
233 lpost = '.'; /* init to gap, if it corresponds to a residue, we'll reset it below */
234 rpost = '.'; /* init to gap, if it corresponds to a residue, we'll reset it below */
235 }
236 d = tr->emitr[ti] - tr->emitl[ti] + 1;
237 mode = tr->mode[ti];
238
239 /* Calculate four of the five lines: rf, str, cons, and seq.
240 */
241 do_left = do_right = FALSE;
242 if (cm->sttype[v] == IL_st) {
243 do_left = TRUE;
244 if (cm->rf != NULL) lrf = '.';
245 lstr = '.';
246 lcons = '.';
247 if (mode == TRMODE_J || mode == TRMODE_L) lseq = tolower((int) abc->sym[symi]);
248 else lseq = '~';
249 cpos_l = 0;
250 spos_l = tr->emitl[ti];
251 if(pcode != NULL) { lpost = pcode[tr->emitl[ti]-1]; } /* watch off-by-one w.r.t. dsq */
252 } else if (cm->sttype[v] == IR_st) {
253 do_right = TRUE;
254 if (cm->rf != NULL) rrf = '.';
255 rstr = '.';
256 rcons = '.';
257 if (mode == TRMODE_J || TRMODE_R) rseq = tolower((int) abc->sym[symj]);
258 else rseq = '~';
259 cpos_r = 0;
260 spos_r = tr->emitr[ti];
261 if(pcode != NULL) { rpost = pcode[tr->emitr[ti]-1]; } /* watch off-by-one w.r.t. dsq */
262 } else {
263 if (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) {
264 do_left = TRUE;
265 if (cm->rf != NULL) lrf = cm->rf[lc];
266 lstr = cons->cstr[lc];
267 lcons = cons->cseq[lc];
268 cpos_l = lc+1;
269 if (cm->sttype[v] == MP_st || cm->sttype[v] == ML_st) {
270 if (mode == TRMODE_J) lseq = abc->sym[symi];
271 else if (mode == TRMODE_L && d>0 ) lseq = abc->sym[symi];
272 else lseq = '~';
273 spos_l = tr->emitl[ti];
274 if(pcode != NULL) { lpost = pcode[tr->emitl[ti]-1]; } /* watch off-by-one w.r.t. dsq */
275 } else {
276 if (mode == TRMODE_J || mode == TRMODE_L) lseq = '-';
277 else lseq = '~';
278 spos_l = 0;
279 /* lpost remains as it was init'ed as a gap '.' */
280 }
281 }
282 if (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) {
283 do_right = TRUE;
284 if (cm->rf != NULL) rrf = cm->rf[rc];
285 rstr = cons->cstr[rc];
286 rcons = cons->cseq[rc];
287 cpos_r = rc+1;
288 if (cm->sttype[v] == MP_st || cm->sttype[v] == MR_st) {
289 if (mode == TRMODE_J) rseq = abc->sym[symj];
290 else if (TRMODE_R && d>0 ) rseq = abc->sym[symj];
291 else rseq = '~';
292 spos_r = tr->emitr[ti];
293 if(pcode != NULL) { rpost = pcode[tr->emitr[ti]-1]; } /* watch off-by-one w.r.t. dsq */
294 } else {
295 if (mode == TRMODE_J || TRMODE_R) rseq = '-';
296 else rseq = '~';
297 spos_r = 0;
298 /* rpost remains as it was init'ed as a gap '.' */
299 }
300 }
301 }
302
303 /* Use emission p and score to set lmid, rmid line for emitting states.
304 */
305 lmid = rmid = ' ';
306 ltop = rtop = ' ';
307 lnegnc = rnegnc = ' ';
308 if (cm->sttype[v] == MP_st) {
309 if (lseq == toupper(lcons) && rseq == toupper(rcons))
310 {
311 lmid = lseq;
312 rmid = rseq;
313 }
314 else if (mode != 3)
315 {
316 if (mode == TRMODE_L && lseq == toupper(lcons)) lmid = lseq;
317 if (TRMODE_R && rseq == toupper(rcons)) rmid = rseq;
318 }
319 else if (DegeneratePairScore(cm->abc, cm->esc[v], symi, symj) >= 0)
320 lmid = rmid = ':';
321
322 /* determine ltop, rtop for optional noncompensatory annotation, they are 'x' if lmid, rmid are ' ', and ' ' otherwise */
323 if (lmid == ' ' && rmid == ' ')
324 ltop = rtop = 'x';
325
326 /* determine lnegnc, rnegnc for optional negative scoring non-canonical annotation, they are 'v' if lseq and rseq are a negative scoring non-canonical (not a AU,UA,GC,CG,GU,UG) pair */
327 if ((mode == TRMODE_J) && (DegeneratePairScore(cm->abc, cm->esc[v], symi, symj) < 0) && (! bp_is_canonical(lseq, rseq))) {
328 lnegnc = rnegnc = 'v';
329 }
330 } else if (cm->sttype[v] == ML_st || cm->sttype[v] == IL_st) {
331 if (lseq == toupper(lcons))
332 lmid = lseq;
333 else if ( (mode != 3) && (mode != 2) )
334 ;
335 else if(esl_abc_FAvgScore(cm->abc, symi, cm->esc[v]) > 0)
336 lmid = '+';
337 } else if (cm->sttype[v] == MR_st || cm->sttype[v] == IR_st) {
338 if (rseq == toupper(rcons))
339 rmid = rseq;
340 else if ( (mode != 3) && (mode != 1) )
341 ;
342 else if(esl_abc_FAvgScore(cm->abc, symj, cm->esc[v]) > 0)
343 rmid = '+';
344 }
345 if(cm->stid[v] == MATP_ML || cm->stid[v] == MATP_MR) {
346 if(mode == TRMODE_J) {
347 ltop = rtop = 'x'; /* mark non-truncated half base-pairs (MATP_ML or MATP_MR) with 'x' */
348 lnegnc = rnegnc = 'v'; /* mark non-truncated half base-pairs (MATP_ML or MATP_MR) with 'v' */
349 }
350 }
351 /* If we're storing a residue leftwise - just do it.
352 * If rightwise - push it onto stack.
353 */
354 if (do_left) {
355 if (cm->rf != NULL) ali->rf[pos] = lrf;
356 ali->cstr[pos] = lstr;
357 ali->cseq[pos] = lcons;
358 ali->mid[pos] = lmid;
359 ali->top[pos] = (do_noncanonical) ? lnegnc : ltop;
360 ali->aseq[pos] = lseq;
361 if(have_pcodes) {
362 ali->pcode[pos] = lpost;
363 }
364 ali->ccoord[pos] = cpos_l;
365 ali->scoord[pos] = spos_l;
366 pos++;
367 }
368 if (do_right) {
369 if ((status = esl_stack_IPush(pda, spos_r)) != eslOK) goto ERROR;
370 if ((status = esl_stack_IPush(pda, cpos_r)) != eslOK) goto ERROR;
371 if(have_pcodes) {
372 if ((status = esl_stack_IPush(pda, (int) rpost)) != eslOK) goto ERROR;
373 }
374 if ((status = esl_stack_IPush(pda, (int) rseq)) != eslOK) goto ERROR;
375 if (do_noncanonical) { if ((status = esl_stack_IPush(pda, (int) rnegnc)) != eslOK) goto ERROR; }
376 else { if ((status = esl_stack_IPush(pda, (int) rtop)) != eslOK) goto ERROR; }
377 if ((status = esl_stack_IPush(pda, (int) rmid)) != eslOK) goto ERROR;
378 if ((status = esl_stack_IPush(pda, (int) rcons)) != eslOK) goto ERROR;
379 if ((status = esl_stack_IPush(pda, (int) rstr)) != eslOK) goto ERROR;
380 if (cm->rf != NULL) if ((status = esl_stack_IPush(pda, (int) rrf)) != eslOK) goto ERROR;
381 if ((status = esl_stack_IPush(pda, PDA_RESIDUE)) != eslOK) goto ERROR;
382 }
383
384 /* Push the child trace nodes onto the PDA;
385 * right first, so it pops last.
386 */
387 if (tr->nxtr[ti] != -1) {
388 if ((status = esl_stack_IPush(pda, tr->nxtr[ti])) != eslOK) goto ERROR;
389 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
390 }
391 if (tr->nxtl[ti] != -1) {
392 if ((status = esl_stack_IPush(pda, tr->nxtl[ti])) != eslOK) goto ERROR;
393 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
394 }
395 else if (cm->sttype[v] != E_st) {
396 /* Catch marginal-type local ends, treat like EL for output */
397 int numwidth; /* number of chars to leave for displaying width numbers */
398
399 nd = 1 + cm->ndidx[tr->state[ti]]; /* calculate node that EL replaced */
400 qinset = cons->rpos[nd] - cons->lpos[nd] + 1;
401 tinset = tr->emitr[ti] - tr->emitl[ti] + 1;
402 if (tinset > 0) tinset--;
403 ninset = ESL_MAX(qinset,tinset);
404 numwidth = 0; do { numwidth++; ninset/=10; } while (ninset); /* poor man's (int)log_10(ninset)+1 */
405 memset(ali->cstr+pos, '~', numwidth+4);
406 if((nw = snprintf(ali->cseq+pos, numwidth+5, "*[%*d]*", numwidth, qinset)) != (numwidth+4)) goto ERROR; /* +5 is length of "*[" + "]*" + 1 for null terminating char */
407 if((nw = snprintf(ali->aseq+pos, numwidth+5, "*[%*d]*", numwidth, tinset)) != (numwidth+4)) goto ERROR; /* +5 is length of "*[" + "]*" + 1 for null terminating char */
408 /* do nothing for posteriors here, they'll stay as they were init'ed, as ' ' */
409 pos += 4 + numwidth;
410 }
411 } /* end loop over the PDA; PDA now empty */
412
413 if (cm->rf != NULL) ali->rf[ali->len] = '\0';
414 ali->cstr[ali->len] = '\0';
415 ali->cseq[ali->len] = '\0';
416 ali->mid[ali->len] = '\0';
417 ali->top[ali->len] = '\0';
418 ali->aseq[ali->len] = '\0';
419 if(have_pcodes) {
420 ali->pcode[ali->len] = '\0';
421 }
422 /* Laboriously determine the maximum bounds.
423 */
424 ali->sqfrom = 0;
425 for (pos = 0; pos < ali->len; pos++)
426 if (ali->scoord[pos] != 0) {
427 ali->sqfrom = ali->scoord[pos];
428 break;
429 }
430 ali->sqto = 0;
431 for (pos = 0; pos < ali->len; pos++)
432 if (ali->scoord[pos] != 0) ali->sqto = ali->scoord[pos];
433 ali->cfrom = 0;
434 for (pos = 0; pos < ali->len; pos++)
435 if (ali->ccoord[pos] != 0) {
436 ali->cfrom = ali->ccoord[pos];
437 break;
438 }
439 ali->cto = 0;
440 for (pos = 0; pos < ali->len; pos++)
441 if (ali->ccoord[pos] != 0) ali->cto = ali->ccoord[pos];
442
443 esl_stack_Destroy(pda);
444 return ali;
445
446 ERROR:
447 cm_Fail("Memory allocation error.\n");
448 return NULL; /* not reached */
449 }
450
451 /* Function: PrintFancyAli()
452 * Date: SRE, Thu Jun 13 02:23:18 2002 [Aula Magna, Stockholm]
453 *
454 * Purpose: Write a CM/sequence alignment to a stream, from a
455 * Fancyali_t structure. Line length currently hardcoded
456 * but this could be changed. Modeled on HMMER's
457 * eponymous function.
458 *
459 * Put at least <min_aliwidth> alignment characters per
460 * line; try to make lines no longer than <linewidth>
461 * characters, including name, coords, and spacing. The
462 * width of lines may exceed <linewidth>, if that's what it
463 * takes to put a name, coords, and <min_aliwidth>
464 * characters of alignment on a line.
465 *
466 * As a special case, if <linewidth> is negative or 0, then
467 * alignments are formatted in a single block of unlimited
468 * line length.
469 *
470 *
471 * Args: fp - where to print it (stdout or open FILE)
472 * ali - alignment structure to print.
473 * offset - number of residues to add to target seq index,
474 * to ease MPI search, all target hits start at posn 1
475 * in_revcomp - TRUE if hit we're printing an alignment for a
476 * cmsearch hit on reverse complement strand.
477 * do_top - TRUE to turn on optional 'top-line' annotation.
478 * This was set in CreateFancyAli() as marking either:
479 * negative scoring (non-compensatories) and half-bps:
480 * negative scoring *non-canonical* bps and half bps
481 * (in this 2nd case negative scoring canonicals are unmarked)
482 * min_aliwidth - min length for alignment block (see Purpose above)
483 * linewidth - preferred line length (see Purpose above)
484 * show_accessions - TRUE to print seq/query accessions (if avail.), not names
485 * Returns: (void)
486 */
487 void
488 PrintFancyAli(FILE *fp, Fancyali_t *ali, int64_t offset, int in_revcomp, int do_top, int linewidth)
489 {
490 int status;
491 char *buf;
492 int pos;
493 int ci, cj; /* positions in CM consensus 1..clen */
494 int sqi, sqj; /* positions in target seq 1..L */
495 int i;
496 int i2print, j2print; /* i,j indices we'll print, used to deal with case of reverse complement */
497 int have_pcodes; /* TRUE if posterior codes are valid */
498
499 printf("in PrintFancyAli sqfrom..sqto %d..%d in_revcomp: %d offset: %" PRId64 "\n", ali->sqfrom, ali->sqto, in_revcomp, offset);
500
501 have_pcodes = (ali->pcode != NULL) ? TRUE : FALSE;
502
503 ESL_ALLOC(buf, sizeof(char) * (linewidth + 1));
504 buf[linewidth] = '\0';
505 for (pos = 0; pos < ali->len; pos += linewidth)
506 {
507 /* Laboriously determine our coord bounds on dsq
508 * and consensus line for this alignment section.
509 */
510 sqi = 0;
511 for (i = pos; ali->aseq[i] != '\0' && i < pos + linewidth; i++) {
512 if (ali->scoord[i] != 0) {
513 sqi = ali->scoord[i];
514 break;
515 }
516 }
517 sqj = 0;
518 for (i = pos; ali->aseq[i] != '\0' && i < pos + linewidth; i++) {
519 if (ali->scoord[i] != 0) sqj = ali->scoord[i];
520 }
521 ci = 0;
522 for (i = pos; ali->aseq[i] != '\0' && i < pos + linewidth; i++) {
523 if (ali->ccoord[i] != 0) {
524 ci = ali->ccoord[i];
525 break;
526 }
527 }
528 cj = 0;
529 for (i = pos; ali->aseq[i] != '\0' && i < pos + linewidth; i++) {
530 if (ali->ccoord[i] != 0) cj = ali->ccoord[i];
531 }
532
533 /* Formats and print the alignment section.
534 */
535 if (ali->rf != NULL) {
536 strncpy(buf, ali->rf+pos, linewidth);
537 fprintf(fp, " %8s %s\n", " ", buf);
538 }
539 if (do_top && ali->top != NULL) {
540 strncpy(buf, ali->top+pos, linewidth);
541 fprintf(fp, " %8s %s\n", " ", buf);
542 }
543 if (ali->cstr != NULL) {
544 strncpy(buf, ali->cstr+pos, linewidth);
545 fprintf(fp, " %8s %s\n", " ", buf);
546 }
547 if (ali->cseq != NULL) {
548 strncpy(buf, ali->cseq+pos, linewidth);
549 if (ci && cj)
550 fprintf(fp, " %8d %s %-8d\n", ci, buf, cj);
551 else
552 fprintf(fp, " %8s %s %-8s\n", "-", buf, "-");
553 }
554 if (ali->mid != NULL) {
555 strncpy(buf, ali->mid+pos, linewidth);
556 fprintf(fp, " %8s %s\n", " ", buf);
557 }
558 if (ali->aseq != NULL) {
559 strncpy(buf, ali->aseq+pos, linewidth);
560 if (sqj && sqi) {
561 if(in_revcomp) {
562 i2print = offset - (sqi-1) + 1;
563 j2print = i2print - (sqj-sqi);
564 }
565 else {
566 i2print = sqi + offset;
567 j2print = sqj + offset;
568 }
569 fprintf(fp, " %8d %s %-8d\n", i2print, buf, j2print);
570 }
571 else {
572 fprintf(fp, " %8s %s %-8s\n", "-", buf, "-");
573 }
574 }
575 if (have_pcodes && ali->pcode != NULL) {
576 strncpy(buf, ali->pcode+pos, linewidth);
577 fprintf(fp, " %8s %s\n", "PP", buf);
578 }
579 fprintf(fp, "\n");
580 }
581 free(buf);
582 fflush(fp);
583 return;
584
585 ERROR:
586 cm_Fail("Memory allocation error.\n");
587 }
588
589
590 /* Function: FreeFancyAli()
591 * Incept: SRE, Fri May 24 15:37:30 2002 [St. Louis]
592 */
593 void
594 FreeFancyAli(Fancyali_t *ali)
595 {
596 if (ali->rf != NULL) free(ali->rf);
597 if (ali->cstr != NULL) free(ali->cstr);
598 if (ali->cseq != NULL) free(ali->cseq);
599 if (ali->mid != NULL) free(ali->mid);
600 if (ali->top != NULL) free(ali->top);
601 if (ali->aseq != NULL) free(ali->aseq);
602 if (ali->pcode != NULL) free(ali->pcode);
603 if (ali->ccoord != NULL) free(ali->ccoord);
604 if (ali->scoord != NULL) free(ali->scoord);
605 free(ali);
606 }
607
608
609 /* Function: CreateCMConsensus()
610 * Incept: SRE, Thu May 23 10:39:39 2002 [St. Louis]
611 *
612 * Purpose: Create displayable strings for consensus sequence
613 * and consensus structure; also create map of
614 * nodes -> right and left consensus positions.
615 *
616 * Consensus sequence shows maximum scoring residue(s)
617 * for each emitting node. If score < pthresh (for pairs)
618 * or < sthresh (for singlets), the residue is shown
619 * in lower case. (That is, "strong" consensus residues
620 * are in upper case.)
621 *
622 * Currently, pthresh is hard-coded as 3.0 and sthresh as
623 * 1.0 (previously v1.0.2 and earlier had these passed in,
624 * but they were always set as 3.0/1.0 so I modified the
625 * function prototype - feel free to change it back if you
626 * want different values, or want to let caller (user) set
627 * them)).
628 *
629 * Consensus structure annotates
630 * base pairs according to "multifurcation order" (how
631 * many multifurcation loops are beneath this pair).
632 * terminal stems: <>
633 * order 1: ()
634 * order 2: []
635 * order >2: {}
636 * Singlets are annotated : if external, _ if hairpin,
637 * - if bulge or interior loop, and , for multifurcation loop.
638 *
639 * Example:
640 * ::(((,,<<<__>>>,<<<__>>->,,)))::
641 * AAGGGAACCCTTGGGTGGGTTCCACAACCCAA
642 *
643 * Args: cm - the model
644 * abc - alphabet to create con->cseq with (often cm->abc)
645 *
646 * Returns: Newly created CMConsensus_t.
647 * Caller frees w/ FreeCMConsensus().
648 * Returns NULL on any error.
649 *
650 * Xref: STL6 p.58.
651 */
652 CMConsensus_t *
653 CreateCMConsensus(CM_t *cm, const ESL_ALPHABET *abc)
654 {
655 int status;
656 CMConsensus_t *con = NULL; /* growing consensus info */
657 char *cseq = NULL; /* growing consensus sequence display string */
658 char *cstr = NULL; /* growing consensus structure display string */
659 int *ct = NULL; /* growing ct Zuker pairing partnet string */
660 int *lpos = NULL; /* maps node->left consensus position, [0..nodes-1] */
661 int *rpos = NULL; /* maps node->right consensus position, [0..nodes-1] */
662 int cpos; /* current position in cseq, cstr */
663 int nalloc; /* current allocated length of cseq, cstr */
664 ESL_STACK *pda; /* pushdown automaton used to traverse model */
665 int *multiorder; /* "height" of each node (multifurcation order), [0..nodes-1] */
666 int *inface; /* face count for each node, inside */
667 int *outface; /* face count for each node, outside */
668 int v, nd;
669 int type;
670 char lchar, rchar;
671 char lstruc, rstruc;
672 int x;
673 int pairpartner; /* coord of left pairing partner of a right base */
674 void *tmp; /* for ESL_RALLOC */
675 /* bit score thresholds for base pairs (pthresh) and singlets
676 * (sthresh) to be lowercased. These are hard-coded. If you want
677 * to change them, consider changing the function prototype so they're
678 * chosen by caller and passed in.
679 */
680 float pthresh = 3.0;
681 float sthresh = 1.0;
682
683 /* Contract check. CM must have log odds scores. Alphabet must make sense. */
684 if(! (cm->flags & CMH_BITS)) return NULL;
685 if(cm->abc->type == eslRNA) {
686 if(abc->type != eslRNA && abc->type != eslDNA) return NULL;
687 }
688 else if(cm->abc->K != abc->K) return NULL;
689
690 ESL_ALLOC(lpos, sizeof(int) * cm->nodes);
691 ESL_ALLOC(rpos, sizeof(int) * cm->nodes);
692 ESL_ALLOC(cseq, sizeof(char) * 100);
693 ESL_ALLOC(cstr, sizeof(char) * 100);
694 ESL_ALLOC(ct, sizeof(int) * 100);
695 nalloc = 100;
696 cpos = 0;
697
698 for (nd = 0; nd < cm->nodes; nd++)
699 lpos[nd] = rpos[nd] = -1;
700
701 multiorder = createMultifurcationOrderChart(cm);
702 createFaceCharts(cm, &inface, &outface);
703
704 if((pda = esl_stack_ICreate()) == NULL) goto ERROR;
705 if ((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR;
706 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
707 while (esl_stack_IPop(pda, &type) != eslEOD) {
708 if (type == PDA_RESIDUE)
709 {
710 esl_stack_IPop(pda, &x); rchar = (char) x;
711 esl_stack_IPop(pda, &x); rstruc = (char) x;
712 esl_stack_IPop(pda, &pairpartner);
713 esl_stack_IPop(pda, &nd);
714 rpos[nd] = cpos;
715 cseq[cpos] = rchar;
716 cstr[cpos] = rstruc;
717 ct[cpos] = pairpartner;
718 if (pairpartner != -1) ct[pairpartner] = cpos;
719 cpos++;
720 }
721 else if (type == PDA_MARKER)
722 {
723 esl_stack_IPop(pda, &nd);
724 rpos[nd] = cpos-1;
725 }
726 else if (type == PDA_STATE)
727 {
728 esl_stack_IPop(pda, &v);
729 nd = cm->ndidx[v];
730 lchar = rchar = lstruc = rstruc = 0;
731
732 /* Determine what we emit:
733 * MATP, MATL, MATR consensus states only.
734 */
735 if (cm->stid[v] == MATP_MP)
736 {
737 x = esl_vec_FArgMax(cm->esc[v], abc->K*abc->K);
738 lchar = abc->sym[x / abc->K];
739 rchar = abc->sym[x % abc->K];
740 if (cm->esc[v][x] < pthresh) {
741 lchar = tolower((int) lchar);
742 rchar = tolower((int) rchar);
743 }
744 switch (multiorder[nd]) {
745 case 0: lstruc = '<'; rstruc = '>'; break;
746 case 1: lstruc = '('; rstruc = ')'; break;
747 case 2: lstruc = '['; rstruc = ']'; break;
748 default: lstruc = '{'; rstruc = '}'; break;
749 }
750 } else if (cm->stid[v] == MATL_ML) {
751 x = esl_vec_FArgMax(cm->esc[v], cm->abc->K);
752 lchar = abc->sym[x];
753 if (cm->esc[v][x] < sthresh) lchar = tolower((int) lchar);
754 if (outface[nd] == 0) lstruc = ':'; /* external ss */
755 else if (inface[nd] == 0 && outface[nd] == 1) lstruc = '_'; /* hairpin loop */
756 else if (inface[nd] == 1 && outface[nd] == 1) lstruc = '-'; /* bulge/interior */
757 else lstruc = ','; /* multiloop */
758 rstruc = ' ';
759 } else if (cm->stid[v] == MATR_MR) {
760 x = esl_vec_FArgMax(cm->esc[v], cm->abc->K);
761 rchar = abc->sym[x];
762 if (cm->esc[v][x] < sthresh) rchar = tolower((int) rchar);
763 if (outface[nd] == 0) rstruc = ':'; /* external ss */
764 else if (inface[nd] == 0 && outface[nd] == 1) rstruc = '?'; /* doesn't happen */
765 else if (inface[nd] == 1 && outface[nd] == 1) rstruc = '-'; /* bulge/interior */
766 else rstruc = ','; /* multiloop */
767 lstruc = ' ';
768 }
769
770 /* Emit. A left base, we can do now;
771 * a right base, we defer onto PDA.
772 */
773 lpos[nd] = cpos; /* we always set lpos, rpos even for nonemitters */
774 if (lchar) {
775 cseq[cpos] = lchar;
776 cstr[cpos] = lstruc;
777 ct[cpos] = -1; /* will be overwritten, if needed, when right guy is processed */
778 cpos++;
779 }
780 if (rchar) {
781 if ((status = esl_stack_IPush(pda, nd)) != eslOK) goto ERROR;
782 if (lchar) { if ((status = esl_stack_IPush(pda, cpos-1)) != eslOK) goto ERROR; }
783 else { if ((status = esl_stack_IPush(pda, -1)) != eslOK) goto ERROR; }
784 if ((status = esl_stack_IPush(pda, rstruc)) != eslOK) goto ERROR;
785 if ((status = esl_stack_IPush(pda, rchar)) != eslOK) goto ERROR;
786 if ((status = esl_stack_IPush(pda, PDA_RESIDUE)) != eslOK) goto ERROR;
787 } else {
788 if ((status = esl_stack_IPush(pda, nd)) != eslOK) goto ERROR;
789 if ((status = esl_stack_IPush(pda, PDA_MARKER)) != eslOK) goto ERROR;
790 }
791
792 /* Transit - to consensus states only.
793 * The obfuscated idiom finds the index of the next consensus
794 * state without making assumptions about numbering or connectivity.
795 */
796 if (cm->sttype[v] == B_st) {
797 if ((status = esl_stack_IPush(pda, cm->cnum[v])) != eslOK) goto ERROR; /* right S */
798 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
799 if ((status = esl_stack_IPush(pda, cm->cfirst[v])) != eslOK) goto ERROR; /* left S */
800 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
801 } else if (cm->sttype[v] != E_st) {
802 v = cm->nodemap[cm->ndidx[cm->cfirst[v] + cm->cnum[v] - 1]];
803 if ((status = esl_stack_IPush(pda, v)) != eslOK) goto ERROR;
804 if ((status = esl_stack_IPush(pda, PDA_STATE)) != eslOK) goto ERROR;
805 }
806 } /*end PDA_STATE block*/
807
808 if (cpos == nalloc) {
809 nalloc += 100;
810 ESL_RALLOC(cseq, tmp, sizeof(char) * nalloc);
811 ESL_RALLOC(cstr, tmp, sizeof(char) * nalloc);
812 ESL_RALLOC(ct, tmp, sizeof(int) * nalloc);
813 }
814 }/* PDA now empty... done generating cseq, cstr, and node->consensus residue map */
815 cseq[cpos] = '\0';
816 cstr[cpos] = '\0';
817
818 esl_stack_Destroy(pda);
819 free(multiorder);
820 free(inface);
821 free(outface);
822
823 ESL_ALLOC(con, sizeof(CMConsensus_t));
824 con->cseq = cseq;
825 con->cstr = cstr;
826 con->ct = ct;
827 con->lpos = lpos;
828 con->rpos = rpos;
829 con->clen = cpos;
830 return con;
831
832 ERROR:
833 if(cseq != NULL) free(cseq);
834 if(cstr != NULL) free(cstr);
835 if(ct != NULL) free(ct);
836 if(lpos != NULL) free(lpos);
837 if(rpos != NULL) free(rpos);
838 if(con != NULL) free(con);
839 return NULL;
840 }
841
842 void
843 FreeCMConsensus(CMConsensus_t *con)
844 {
845 if (con->cseq != NULL) free(con->cseq);
846 if (con->cstr != NULL) free(con->cstr);
847 if (con->ct != NULL) free(con->ct);
848 if (con->lpos != NULL) free(con->lpos);
849 if (con->rpos != NULL) free(con->rpos);
850 free(con);
851 }
852
853 /* Function: createMultifurcationOrderChart()
854 * Incept: SRE, Thu May 23 09:48:33 2002 [St. Louis]
855 *
856 * Purpose: Calculates the degree of multifurcation beneath
857 * the master subtree rooted at every node n.
858 * Returns [0..nodes-1] array of these values.
859 *
860 * Terminal stems have value 0. All nodes n starting with
861 * the BEG node for a terminal stem have height[n] = 0.
862 *
863 * A stem "above" a multifurcation into all terminal stems
864 * has value 1; all nodes n starting with BEG and ending
865 * with BIF have height[n] = 1.
866 *
867 * And so on, for "higher order" (deeper) multifurcations.
868 *
869 * Used for figuring out what characters we'll display a
870 * consensus pair with.
871 *
872 * THIS FUNCTION IS BUGGY (Sat Jun 1 12:24:23 2002)
873 *
874 * Args: cm - the model.
875 *
876 * Returns: [0..cm->nodes-1] array of multifurcation orders, for each node.
877 * This array is allocated here; caller free's w/ free().
878 *
879 * xref: STL6 p.58.
880 */
881 static int *
882 createMultifurcationOrderChart(CM_t *cm)
883 {
884 int status;
885 int v, nd, left, right;
886 int *height;
887 int *seg_has_pairs;
888
889 ESL_ALLOC(height, sizeof(int) * cm->nodes);
890 ESL_ALLOC(seg_has_pairs, sizeof(int) * cm->nodes);
891 for (nd = cm->nodes-1; nd >= 0; nd--)
892 {
893 v = cm->nodemap[nd];
894
895 if (cm->stid[v] == MATP_MP) seg_has_pairs[nd] = TRUE;
896 else if (cm->stid[v] == END_E) seg_has_pairs[nd] = FALSE;
897 else if (cm->stid[v] == BIF_B) seg_has_pairs[nd] = FALSE;
898 else seg_has_pairs[nd] = seg_has_pairs[nd+1];
899
900 if (cm->stid[v] == END_E)
901 height[nd] = 0;
902 else if (cm->stid[v] == BIF_B)
903 {
904 left = cm->ndidx[cm->cfirst[v]];
905 right = cm->ndidx[cm->cnum[v]];
906 height[nd] = ESL_MAX(height[left] + seg_has_pairs[left],
907 height[right] + seg_has_pairs[right]);
908 }
909 else
910 height[nd] = height[nd+1];
911 }
912 free(seg_has_pairs);
913 return height;
914
915 ERROR:
916 cm_Fail("Memory allocation error.\n");
917 return 0; /* never reached */
918 }
919
920
921 /* Function: createFaceCharts()
922 * Incept: SRE, Thu May 23 12:40:04 2002 [St. Louis]
923 *
924 * Purpose: Calculate "inface" and "outface" for each node
925 * in the consensus (master) structure of the CM.
926 * These can be used to label nodes:
927 * inface outface
928 * ------------ ----------
929 * external ss any 0
930 * hairpin loop 0 1
931 * bulge/interior 1 1
932 * multifurc >1 1
933 * multifurc 1 >1
934 * doesn't happen 0 >1
935 *
936 * hairpin closing bp 0 1
937 * extern closing bp 1 0
938 * stem bp 1 1
939 * multifurc close bp >1 1
940 * multifurc close bp 1 >1
941 * doesn't happen 0 >1
942 *
943 * Args: cm - the model
944 * ret_inface - RETURN: inface[0..nodes-1]
945 * ret_outface - RETURN: outface[0..nodes-1]
946 *
947 * Returns: inface, outface;
948 * they're alloc'ed here. Caller free's with free()
949 *
950 * Xref: STL6 p.58
951 */
952 static void
953 createFaceCharts(CM_t *cm, int **ret_inface, int **ret_outface)
954 {
955 int status;
956 int *inface;
957 int *outface;
958 int nd, left, right, parent;
959 int v,y;
960
961 ESL_ALLOC(inface, sizeof(int) * cm->nodes);
962 ESL_ALLOC(outface, sizeof(int) * cm->nodes);
963
964 /* inface - the number of faces below us in descendant
965 * subtrees. if 0, we're either external, or
966 * a closing basepair, or we're in a hairpin loop.
967 * inface is exclusive of current pair - so we
968 * can easily detect closing base pairs.
969 */
970 for (nd = cm->nodes-1; nd >= 0; nd--)
971 {
972 v = cm->nodemap[nd];
973 if (cm->ndtype[nd] == END_nd) inface[nd] = 0;
974 else if (cm->ndtype[nd] == BIF_nd) {
975 left = cm->ndidx[cm->cfirst[v]];
976 right = cm->ndidx[cm->cnum[v]];
977 inface[nd] = inface[left] + inface[right];
978 } else {
979 if (cm->ndtype[nd+1] == MATP_nd) inface[nd] = 1;
980 else inface[nd] = inface[nd+1];
981 }
982 }
983
984 /* outface - the number of faces above us in the tree
985 * excluding our subtree. if 0, we're external.
986 * Like inface, outface is exclusive of current
987 * pair.
988 */
989 for (nd = 0; nd < cm->nodes; nd++)
990 {
991 v = cm->nodemap[nd];
992 if (cm->ndtype[nd] == ROOT_nd) outface[nd] = 0;
993 else if (cm->ndtype[nd] == BEGL_nd)
994 {
995 parent = cm->ndidx[cm->plast[v]];
996 y = cm->nodemap[parent];
997 right = cm->ndidx[cm->cnum[y]];
998 outface[nd] = outface[parent] + inface[right];
999 }
1000 else if (cm->ndtype[nd] == BEGR_nd)
1001 {
1002 parent = cm->ndidx[cm->plast[v]];
1003 left = cm->ndidx[cm->cfirst[y]];
1004 outface[nd] = outface[parent] + inface[left];
1005 }
1006 else
1007 {
1008 parent = nd-1;
1009 if (cm->ndtype[parent] == MATP_nd) outface[nd] = 1;
1010 else outface[nd] = outface[parent];
1011 }
1012 }
1013
1014 *ret_inface = inface;
1015 *ret_outface = outface;
1016 return;
1017
1018 ERROR:
1019 cm_Fail("Memory allocation error.\n");
1020 }
1021
1022 /* Function: IsCompensatory()
1023 * Date: SRE, Sun Jun 2 10:16:59 2002 [Madison]
1024 *
1025 * Purpose: Returns TRUE if log[pij/(pi*pj)] is >= 0,
1026 * where pij is the probability of a base pair,
1027 * pi and pj are the marginal probabilities
1028 * for the symbols at i and j.
1029 *
1030 * Currently returns FALSE if symi or symj
1031 * are ambiguous IUPAC nucs. Could do a more
1032 * sophisticated marginalization - prob not
1033 * worth it right now.
1034 *
1035 * Args: pij - joint emission probability vector [0..15]
1036 * indexed symi*4 + symj.
1037 * symi - symbol index at i [0..3], equiv to [a..u]
1038 * symj - symbol index at j [0..3], equiv to [a..u]
1039 *
1040 * Returns: TRUE or FALSE.
1041 */
1042 int
1043 IsCompensatory(const ESL_ALPHABET *abc, float *pij, int symi, int symj)
1044 {
1045 int x;
1046 float pi, pj;
1047
1048 if (symi >= abc->K || symj >= abc->K)
1049 return FALSE;
1050
1051 pi = pj = 0.;
1052 for (x = 0; x < abc->K; x++)
1053 {
1054 pi += pij[symi*abc->K + x];
1055 pj += pij[x*abc->K + symi];
1056 }
1057 if (log(pij[symi*abc->K+symj]) - log(pi) - log(pj) >= 0)
1058 return TRUE;
1059 else
1060 return FALSE;
1061 }
1062
1063 /* Implementation of CMEmitMap_t structure:
1064 * map of a CM's nodes onto consensus sequence positions.
1065 * Structure is declared in infernal.h.
1066 *
1067 * Used for constructing multiple alignments.
1068 *
1069 * clen : consensus length.
1070 * clen is 2* n(MATP) + n(MATL) + n(MATR).
1071 * The consensus sequence is indexed 1..clen.
1072 * 0 and clen+1 are also used, as boundary conditions.
1073 *
1074 * lpos[0..nodes-1] : has values 0 to clen+1.
1075 * Any left match emission from node nd is placed in lpos[nd].
1076 * Any left insert emission from node nd *follows* lpos[nd].
1077 *
1078 * rpos[0..nodes-1] : has values 0..clen+1
1079 * Any right match emission from node nd is placed in rpos[nd].
1080 * Any right insert emission from node nd *precedes* rpos[nd]
1081 *
1082 * epos[0..nodes-1] : has values 0..clen+1.
1083 * Any EL insertion from a nd->EL transition *follows* epos[nd].
1084 *
1085 * There are no dummy values; all lpos, rpos, epos are valid coords
1086 * 0..clen+1, as described above, even for END_nd's.
1087 *
1088 * For nonemitting nodes, rpos and lpos give a noninclusive bound:
1089 * for example, lpos[0] = 0 and rpos[0] = clen+1 by definition.
1090 *
1091 * Insertions occur between consensus positions. An inter-consensus-position
1092 * space may contain more than one type of insertion: an IL insertion and
1093 * an EL insertion, an IR insertion and an EL insertion; or (in
1094 * a single absurd case of a model with a consensus length of 0)
1095 * all three insertion types. Insertions are placed in order IL/EL/IR.
1096 *
1097 */
1098
1099 /* Function: CreateEmitMap()
1100 * Date: ? (SRE pre Infernal version 0.55).
1101 *
1102 * Purpose: Create and fill an emit map for a given CM <cm>
1103 * and return it.
1104 * If we run out of memory or we have a problem creating
1105 * the map, we return NULL.
1106 *
1107 */
1108
1109 CMEmitMap_t *
1110 CreateEmitMap(CM_t *cm)
1111 {
1112 int status;
1113 CMEmitMap_t *map = NULL;
1114 ESL_STACK *pda;
1115 int cpos;
1116 int nd;
1117 int on_right;
1118
1119 ESL_ALLOC(map, sizeof(CMEmitMap_t));
1120 ESL_ALLOC(map->lpos, sizeof(int) * cm->nodes);
1121 ESL_ALLOC(map->rpos, sizeof(int) * cm->nodes);
1122 ESL_ALLOC(map->epos, sizeof(int) * cm->nodes);
1123
1124 for (nd = 0; nd < cm->nodes; nd++)
1125 map->lpos[nd] = map->rpos[nd] = map->epos[nd] = -1;
1126
1127 cpos = 0;
1128 nd = 0;
1129 if ((pda = esl_stack_ICreate()) == NULL) goto ERROR;
1130 if ((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR; /* 0 = left side. 1 would = right side. */
1131 if ((status = esl_stack_IPush(pda, nd)) != eslOK) goto ERROR;
1132 while (esl_stack_IPop(pda, &nd) != eslEOD)
1133 {
1134 esl_stack_IPop(pda, &on_right);
1135
1136 if (on_right)
1137 {
1138 map->rpos[nd] = cpos+1;
1139 if (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATR_nd) cpos++;
1140 }
1141 else
1142 {
1143 if (cm->ndtype[nd] == MATP_nd || cm->ndtype[nd] == MATL_nd) cpos++;
1144 map->lpos[nd] = cpos;
1145
1146 if (cm->ndtype[nd] == BIF_nd)
1147 {
1148 /* push the BIF back on for its right side */
1149 if ((status = esl_stack_IPush(pda, 1)) != eslOK) goto ERROR;
1150 if ((status = esl_stack_IPush(pda, nd)) != eslOK) goto ERROR;
1151 /* push node index for right child */
1152 if ((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR;
1153 if ((status = esl_stack_IPush(pda, cm->ndidx[cm->cnum[cm->nodemap[nd]]])) != eslOK) goto ERROR;
1154 /* push node index for left child */
1155 if ((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR;
1156 if ((status = esl_stack_IPush(pda, cm->ndidx[cm->cfirst[cm->nodemap[nd]]])) != eslOK) goto ERROR;
1157 }
1158 else
1159 {
1160 /* push the node back on for right side */
1161 if ((status = esl_stack_IPush(pda, 1)) != eslOK) goto ERROR;
1162 if ((status = esl_stack_IPush(pda, nd)) != eslOK) goto ERROR;
1163 /* push child node on */
1164 if (cm->ndtype[nd] != END_nd) {
1165 if ((status = esl_stack_IPush(pda, 0)) != eslOK) goto ERROR;
1166 if ((status = esl_stack_IPush(pda, nd+1)) != eslOK) goto ERROR;
1167 }
1168 }
1169 }
1170 }
1171
1172 /* Construct the epos map: if we do a v->EL transition,
1173 * the EL follows what consensus position (and its IL insertions,
1174 * if any)
1175 */
1176 for (nd = cm->nodes-1; nd >= 0; nd--) {
1177 if (cm->ndtype[nd] == END_nd)
1178 cpos = map->lpos[nd];
1179 else if (cm->ndtype[nd] == BIF_nd) /* propagate epos for *right* branch. */
1180 cpos = map->epos[cm->ndidx[cm->cnum[cm->nodemap[nd]]]];
1181
1182 map->epos[nd] = cpos;
1183 }
1184
1185 map->clen = map->rpos[0]-1;
1186 esl_stack_Destroy(pda);
1187
1188 /* ensure we've filled in the map correctly */
1189 for (nd = 0; nd < cm->nodes; nd++) {
1190 if(map->lpos[nd] == -1) goto ERROR;
1191 if(map->rpos[nd] == -1) goto ERROR;
1192 if(map->epos[nd] == -1) goto ERROR;
1193 }
1194
1195 return map;
1196
1197 ERROR:
1198 if(map != NULL) FreeEmitMap(map);
1199 return NULL;
1200 }
1201
1202
1203 /* Function: SizeofEmitMap()
1204 * Date: EPN, Wed Jan 18 10:15:46 2012
1205 *
1206 * Purpose: Calculate and return the size of an emit map
1207 * in Mb.
1208 */
1209
1210 float
1211 SizeofEmitMap(CM_t *cm, CMEmitMap_t *emap)
1212 {
1213 float bytes = 0.;
1214
1215 if(emap == NULL) return 0.;
1216
1217 bytes = sizeof(CMEmitMap_t);
1218 bytes += sizeof(int) * cm->nodes; /* lpos */
1219 bytes += sizeof(int) * cm->nodes; /* rpos */
1220 bytes += sizeof(int) * cm->nodes; /* epos */
1221
1222 return bytes / 1000000.;
1223 }
1224
1225 void
1226 DumpEmitMap(FILE *fp, CMEmitMap_t *map, CM_t *cm)
1227 {
1228 int nd;
1229
1230 fprintf(fp, "CM to consensus emit map; consensus length = %d \n",
1231 map->clen);
1232 fprintf(fp, "%4s %7s %9s %4s %4s %4s\n",
1233 "Node", "State 1", "Node type", "lpos", "rpos", "epos");
1234 fprintf(fp, "%4s %7s %9s %4s %4s %4s\n",
1235 "----", "-------", "---------", "----", "----", "----");
1236 for (nd = 0; nd < cm->nodes; nd++)
1237 fprintf(fp, "%4d %7d %9s %4d %4d %4d\n",
1238 nd, cm->nodemap[nd], Nodetype(cm->ndtype[nd]),
1239 map->lpos[nd], map->rpos[nd], map->epos[nd]);
1240 }
1241
1242 void
1243 FreeEmitMap(CMEmitMap_t *map)
1244 {
1245 free(map->lpos);
1246 free(map->rpos);
1247 free(map->epos);
1248 free(map);
1249 }
1250
1251 /* FormatTimeString()
1252 * Date: SRE, Fri Nov 26 15:06:28 1999 [St. Louis]
1253 *
1254 * Purpose: Given a number of seconds, format into
1255 * hh:mm:ss.xx in a provided buffer.
1256 *
1257 * Args: buf - allocated space (128 is plenty!)
1258 * n - size of buf (128 is plenty!)
1259 * sec - number of seconds
1260 * do_frac - TRUE (1) to include hundredths of a sec
1261 */
1262 void
1263 FormatTimeString(char *buf, int n, double sec, int do_frac)
1264 {
1265 int h, m, s, hs;
1266
1267 h = (int) (sec / 3600.);
1268 m = (int) (sec / 60.) - h * 60;
1269 s = (int) (sec) - h * 3600 - m * 60;
1270 if (do_frac) {
1271 hs = (int) (sec * 100.) - h * 360000 - m * 6000 - s * 100;
1272 snprintf(buf, n, "%02d:%02d:%02d.%02d", h,m,s,hs);
1273 } else {
1274 snprintf(buf, n, "%02d:%02d:%02d", h,m,s);
1275 }
1276 }
1277
1278
1279 /* Function: GetCommand
1280 * Date: EPN, Fri Jan 25 13:56:10 2008
1281 *
1282 * Purpose: Return the command used to call an infernal executable
1283 * in <ret_command>.
1284 *
1285 * Returns: eslOK on success; eslEMEM on allocation failure.
1286 */
1287 int
1288 GetCommand(const ESL_GETOPTS *go, char *errbuf, char **ret_command)
1289 {
1290 int status;
1291 int i;
1292 char *command = NULL;
1293
1294 for (i = 0; i < go->argc; i++) { /* copy all command line options and args */
1295 if((status = esl_strcat(&(command), -1, go->argv[i], -1)) != eslOK) goto ERROR;
1296 if(i < (go->argc-1)) if((status = esl_strcat(&(command), -1, " ", 1)) != eslOK) goto ERROR;
1297 }
1298 *ret_command = command;
1299
1300 return eslOK;
1301
1302 ERROR:
1303 ESL_FAIL(status, errbuf, "GetCommand(): memory allocation error.");
1304 return status;
1305 }
1306
1307 /* Function: GetDate
1308 * Date: EPN, Fri Jan 25 13:59:22 2008
1309 *
1310 * Purpose: Return a string that gives the current date.
1311 *
1312 * Returns: eslOK on success; eslEMEM on allocation failure.
1313 */
1314 int
1315 GetDate(char *errbuf, char **ret_date)
1316 {
1317 int status;
1318 time_t date = time(NULL);
1319 char *sdate = NULL;
1320
1321 if((status = esl_strdup(ctime(&date), -1, &sdate)) != eslOK) goto ERROR;
1322 esl_strchop(sdate, -1); /* doesn't return anything but eslOK */
1323
1324 *ret_date = sdate;
1325 return eslOK;
1326
1327 ERROR:
1328 ESL_FAIL(status, errbuf, "get_date() error status: %d, probably out of memory.", status);
1329 return status;
1330 }
1331
1332
1333 /* Function: bp_is_canonical
1334 * Date: EPN, Wed Oct 14 06:17:27 2009
1335 *
1336 * Purpose: Determine if two residues form a canonical base pair or not.
1337 * Works for RNA or DNA (because for some reason cmsearch allows
1338 * the user to format output as DNA (with --dna)).
1339 *
1340 * Returns: TRUE if:
1341 * lseq rseq
1342 * ---- ----
1343 * A U
1344 * U A
1345 * C G
1346 * G C
1347 * G U
1348 * U G
1349 * A T
1350 * T A
1351 * G T
1352 * T G
1353 * Else, return FALSE.
1354 */
1355 int
1356 bp_is_canonical(char lseq, char rseq)
1357 {
1358 switch (toupper(lseq)) {
1359 case 'A':
1360 switch (toupper(rseq)) {
1361 case 'U': return TRUE; break;
1362 case 'T': return TRUE; break;
1363 default: break;
1364 }
1365 break;
1366 case 'C':
1367 switch (toupper(rseq)) {
1368 case 'G': return TRUE; break;
1369 default: break;
1370 }
1371 break;
1372 case 'G':
1373 switch (toupper(rseq)) {
1374 case 'C': return TRUE; break;
1375 case 'U': return TRUE; break;
1376 case 'T': return TRUE; break;
1377 default: break;
1378 }
1379 break;
1380 case 'U':
1381 switch (toupper(rseq)) {
1382 case 'A': return TRUE; break;
1383 case 'G': return TRUE; break;
1384 default: break;
1385 }
1386 break;
1387 case 'T':
1388 switch (toupper(rseq)) {
1389 case 'A': return TRUE; break;
1390 case 'G': return TRUE; break;
1391 default: break;
1392 }
1393 break;
1394 default: break;
1395 }
1396
1397 return FALSE;
1398 }
1399