Debian Codegraph @

hmmer/src/tracealign.c

raw symbols SCIP
1 /* Construction of multiple alignments from traces.
2 *
3 * Contents:
4 * 1. API for aligning sequence or MSA traces
5 * 2. Internal functions used by the API
6 * 3. Test driver
7 *
8 * SRE, Tue Oct 21 19:38:19 2008 [Casa de Gatos]
9 */
10 #include <p7_config.h>
11
12 #include "easel.h"
13 #include "esl_vectorops.h"
14
15 #include "hmmer.h"
16
17 static int map_new_msa(P7_TRACE **tr, int nseq, int M, int optflags, int **ret_inscount, int **ret_matuse, int **ret_matmap, int *ret_alen);
18 static ESL_DSQ get_dsq_z(ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int idx, int z);
19 static int make_digital_msa(ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int nseq, const int *matuse, const int *matmap, int M, int alen, int optflags, ESL_MSA **ret_msa);
20 static int make_text_msa (ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int nseq, const int *matuse, const int *matmap, int M, int alen, int optflags, ESL_MSA **ret_msa);
21 static int annotate_rf(ESL_MSA *msa, int M, const int *matuse, const int *matmap);
22 static int annotate_mm(ESL_MSA *msa, P7_HMM *hmm, const int *matuse, const int *matmap);
23 static int annotate_posterior_probability(ESL_MSA *msa, P7_TRACE **tr, const int *matmap, int M, int optflags);
24 static int rejustify_insertions_digital ( ESL_MSA *msa, const int *inserts, const int *matmap, const int *matuse, int M);
25 static int rejustify_insertions_text (const ESL_ALPHABET *abc, ESL_MSA *msa, const int *inserts, const int *matmap, const int *matuse, int M);
26
27
28 /*****************************************************************
29 * 1. API for aligning sequence or MSA traces
30 *****************************************************************/
31
32 /* Function: p7_tracealign_Seqs()
33 * Synopsis: Convert array of traces (for a sequence array) to a new MSA.
34 * Incept: SRE, Tue Oct 21 19:40:33 2008 [Janelia]
35 *
36 * Purpose: Convert an array of <nseq> traces <tr[0..nseq-1]>,
37 * corresponding to an array of digital sequences
38 * <sq[0..nseq-1]> aligned to a model of
39 * length <M>, to a new multiple sequence alignment.
40 * The new alignment structure is allocated here, and returned
41 * in <*ret_msa>.
42 *
43 * As a special case, the traces may contain I->D and D->I
44 * transitions. This feature is used by <hmmalign --mapali>
45 * to reconstruct an input alignment without modification
46 * from trace doctoring.
47 *
48 * <optflags> controls some optional behaviors in producing
49 * the alignment, as follows:
50 *
51 * <p7_DIGITIZE>: creates the MSA in digital mode, as
52 * opposed to a default text mode.
53 *
54 * <p7_ALL_CONSENSUS_COLS>: create a column for every
55 * consensus column in the model, even if it means having
56 * all gap characters (deletions) in a column; this
57 * guarantees that the alignment will have at least <M>
58 * columns. The default is to only show columns that have
59 * at least one residue in them.
60 *
61 * <p7_TRIM>: trim off any residues that get assigned to
62 * flanking N,C states (in profile traces) or I_0 and I_M
63 * (in core traces).
64 *
65 * The <optflags> can be combined by logical OR; for
66 * example, <p7_DIGITIZE | p7_ALL_CONSENSUS_COLS>.
67 *
68 * Args: sq - array of digital sequences, 0..nseq-1
69 * tr - array of tracebacks, 0..nseq-1
70 * nseq - number of sequences
71 * M - length of model sequences were aligned to
72 * optflags - flags controlling optional behaviours.
73 * ret_msa - RETURN: new multiple sequence alignment
74 *
75 * Returns: <eslOK> on success, and <*ret_msa> points to a new
76 * <ESL_MSA> object. Caller is responsible for free'ing
77 * this new MSA with <esl_msa_Destroy()>.
78 *
79 * Throws: <eslEMEM> on allocation failure; <*ret_msa> is <NULL>.
80 *
81 * Notes: * why a text mode, when most of HMMER works in digital
82 * sequences and alignments? Text mode MSAs are created
83 * for output, whereas digital mode MSAs are created for
84 * internal use. Text mode allows HMMER's output
85 * conventions to be used for match vs. insert columns:
86 * lowercase/. for residues/gaps in inserts, uppercase/-
87 * for residues/gaps in match columns.
88 *
89 * * why not pass HMM as an argument, so we can transfer
90 * column annotation? In <p7_tophits_Alignment()>, the
91 * HMM is unavailable -- because of constraints of what's
92 * made available to the master process in an MPI
93 * implementation. (We could make the HMM an optional
94 * argument.)
95 */
96 int
97 p7_tracealign_Seqs(ESL_SQ **sq, P7_TRACE **tr, int nseq, int M, int optflags, P7_HMM *hmm, ESL_MSA **ret_msa)
98 {
99 ESL_MSA *msa = NULL; /* RETURN: new MSA */
100 const ESL_ALPHABET *abc = sq[0]->abc;
101 int *inscount = NULL; /* array of max gaps between aligned columns */
102 int *matmap = NULL; /* matmap[k] = apos of match k matmap[1..M] = [1..alen] */
103 int *matuse = NULL; /* TRUE if an alignment column is associated with match state k [1..M] */
104 int idx; /* counter over sequences */
105 int alen; /* width of alignment */
106 int status;
107
108 if ((status = map_new_msa(tr, nseq, M, optflags, &inscount, &matuse, &matmap, &alen)) != eslOK) return status;
109
110 if (optflags & p7_DIGITIZE) { if ((status = make_digital_msa(sq, NULL, tr, nseq, matuse, matmap, M, alen, optflags, &msa)) != eslOK) goto ERROR; }
111 else { if ((status = make_text_msa (sq, NULL, tr, nseq, matuse, matmap, M, alen, optflags, &msa)) != eslOK) goto ERROR; }
112
113 if ((status = annotate_rf(msa, M, matuse, matmap)) != eslOK) goto ERROR;
114 if (hmm)
115 if ((status = annotate_mm(msa, hmm, matuse, matmap)) != eslOK) goto ERROR;
116 if ((status = annotate_posterior_probability(msa, tr, matmap, M, optflags)) != eslOK) goto ERROR;
117
118 if (optflags & p7_DIGITIZE) rejustify_insertions_digital( msa, inscount, matmap, matuse, M);
119 else rejustify_insertions_text (abc, msa, inscount, matmap, matuse, M);
120
121 for (idx = 0; idx < nseq; idx++)
122 {
123 esl_msa_SetSeqName(msa, idx, sq[idx]->name, -1);
124 if (sq[idx]->acc[0] != '\0') esl_msa_SetSeqAccession (msa, idx, sq[idx]->acc, -1);
125 if (sq[idx]->desc[0] != '\0') esl_msa_SetSeqDescription(msa, idx, sq[idx]->desc, -1);
126 msa->wgt[idx] = 1.0;
127 if (msa->sqlen != NULL) msa->sqlen[idx] = sq[idx]->n;
128 }
129
130 free(inscount);
131 free(matmap);
132 free(matuse);
133 *ret_msa = msa;
134 return eslOK;
135
136 ERROR:
137 if (msa != NULL) esl_msa_Destroy(msa);
138 if (inscount != NULL) free(inscount);
139 if (matmap != NULL) free(matmap);
140 if (matuse != NULL) free(matuse);
141 *ret_msa = NULL;
142 return status;
143 }
144
145
146 /* Function: p7_tracealign_MSA()
147 * Synopsis: Convert array of traces (for a previous MSA) to a new MSA.
148 * Incept: SRE, Mon Mar 2 18:18:22 2009 [Casa de Gatos]
149 *
150 * Purpose: Identical to <p7_tracealign_Seqs()> except that the trace
151 * array <tr> accompanies a digital multiple alignment <premsa>,
152 * rather than an array of digital sequences.
153 *
154 * This gets used in <p7_Builder()>, where we've
155 * constructed an array of faux traces directly from an
156 * input alignment, and we want to reconstruct the
157 * MSA that corresponds to what HMMER actually used
158 * to build its model (after trace doctoring to be
159 * compatible with Plan 7, and with <#=RF> annotation
160 * on assigned consensus columns).
161 *
162 * Xref: J4/102.
163 */
164 int
165 p7_tracealign_MSA(const ESL_MSA *premsa, P7_TRACE **tr, int M, int optflags, ESL_MSA **ret_postmsa)
166 {
167 const ESL_ALPHABET *abc = premsa->abc;
168 ESL_MSA *msa = NULL; /* RETURN: new MSA */
169 int *inscount = NULL; /* array of max gaps between aligned columns */
170 int *matmap = NULL; /* matmap[k] = apos of match k matmap[1..M] = [1..alen] */
171 int *matuse = NULL; /* TRUE if an alignment column is associated with match state k [1..M] */
172 int idx; /* counter over sequences */
173 int alen; /* width of alignment */
174 int status;
175
176 if ((status = map_new_msa(tr, premsa->nseq, M, optflags, &inscount, &matuse, &matmap, &alen)) != eslOK) return status;
177
178 if (optflags & p7_DIGITIZE) { if ((status = make_digital_msa(NULL, premsa, tr, premsa->nseq, matuse, matmap, M, alen, optflags, &msa)) != eslOK) goto ERROR; }
179 else { if ((status = make_text_msa (NULL, premsa, tr, premsa->nseq, matuse, matmap, M, alen, optflags, &msa)) != eslOK) goto ERROR; }
180
181 if ((status = annotate_rf(msa, M, matuse, matmap)) != eslOK) goto ERROR;
182 if ((status = annotate_posterior_probability(msa, tr, matmap, M, optflags)) != eslOK) goto ERROR;
183
184 if (optflags & p7_DIGITIZE) rejustify_insertions_digital( msa, inscount, matmap, matuse, M);
185 else rejustify_insertions_text (abc, msa, inscount, matmap, matuse, M);
186
187
188 /* Transfer information from old MSA to new */
189 esl_msa_SetName (msa, premsa->name, -1);
190 esl_msa_SetDesc (msa, premsa->desc, -1);
191 esl_msa_SetAccession(msa, premsa->acc, -1);
192
193 for (idx = 0; idx < premsa->nseq; idx++)
194 {
195 esl_msa_SetSeqName (msa, idx, premsa->sqname[idx], -1);
196 if (msa->sqacc) esl_msa_SetSeqAccession (msa, idx, premsa->sqacc[idx], -1);
197 if (msa->sqdesc) esl_msa_SetSeqDescription(msa, idx, premsa->sqdesc[idx], -1);
198 msa->wgt[idx] = premsa->wgt[idx];
199 }
200
201 if (premsa->flags & eslMSA_HASWGTS)
202 msa->flags |= eslMSA_HASWGTS;
203
204 free(inscount);
205 free(matmap);
206 free(matuse);
207 *ret_postmsa = msa;
208 return eslOK;
209
210 ERROR:
211 if (msa != NULL) esl_msa_Destroy(msa);
212 if (inscount != NULL) free(inscount);
213 if (matmap != NULL) free(matmap);
214 if (matuse != NULL) free(matuse);
215 *ret_postmsa = NULL;
216 return status;
217 }
218
219
220
221 /* Function: p7_tracealign_computeTraces()
222 *
223 * Synopsis: Compute traces for a collection of sequences relative to
224 * a given HMM
225 *
226 * Purpose: Given an <hmm> and a set of sequences <sq> (along with
227 * an <offset> into the first sequence for which a trace is
228 * desired), calculate the optimal accuracy alignment trace
229 * for each of <N> sequences. The calling function provides
230 * a allocated array of P7_TRACEs (<tr>) into which the
231 * results are placed.
232 *
233 * Return: eslOK if no errors
234 */
235 int
236 p7_tracealign_computeTraces(P7_HMM *hmm, ESL_SQ **sq, int offset, int N, P7_TRACE **tr)
237 {
238
239 P7_OMX *oxf = NULL; /* optimized Forward matrix */
240 P7_OMX *oxb = NULL; /* optimized Backward matrix */
241 P7_GMX *gxf = NULL; /* generic Forward mx for failover */
242 P7_GMX *gxb = NULL; /* generic Backward mx for failover*/
243 P7_PROFILE *gm = NULL;
244 P7_OPROFILE *om = NULL;
245 P7_BG *bg = NULL;
246 int tfrom, tto;
247
248 int idx;
249 float fwdsc; /* Forward score */
250 float oasc; /* optimal accuracy score */
251 int status;
252
253 bg = p7_bg_Create(hmm->abc);
254 gm = p7_profile_Create (hmm->M, hmm->abc);
255 om = p7_oprofile_Create(hmm->M, hmm->abc);
256
257 p7_ProfileConfig(hmm, bg, gm, sq[offset]->n, p7_UNILOCAL);
258 p7_oprofile_Convert(gm, om);
259
260
261 oxf = p7_omx_Create(hmm->M, sq[offset]->n, sq[offset]->n);
262 oxb = p7_omx_Create(hmm->M, sq[offset]->n, sq[offset]->n);
263
264 /* Collect an OA trace for each sequence that needs to be aligned
265 */
266 for (idx = offset; idx < offset+ N; idx++)
267 {
268 /* special case: a sequence of length 0. HMMER model can't generate 0 length seq. Set tr->N == 0 as a flag. (bug #h100 fix) */
269 if (sq[idx]->n == 0) { tr[idx]->N = 0; continue; }
270
271 p7_omx_GrowTo(oxf, hmm->M, sq[idx]->n, sq[idx]->n);
272 p7_omx_GrowTo(oxb, hmm->M, sq[idx]->n, sq[idx]->n);
273
274 p7_oprofile_ReconfigLength(om, sq[idx]->n);
275
276 p7_Forward (sq[idx]->dsq, sq[idx]->n, om, oxf, &fwdsc);
277 p7_Backward(sq[idx]->dsq, sq[idx]->n, om, oxf, oxb, NULL);
278
279 status = p7_Decoding(om, oxf, oxb, oxb); /* <oxb> is now overwritten with post probabilities */
280
281 if (status == eslOK)
282 {
283 p7_OptimalAccuracy(om, oxb, oxf, &oasc); /* <oxf> is now overwritten with OA scores */
284 p7_OATrace (om, oxb, oxf, tr[idx]); /* tr[idx] is now an OA traceback for seq #idx */
285 }
286 else if (status == eslERANGE)
287 {
288 /* Work around the numeric overflow problem in Decoding()
289 * xref J3/119-121 for commentary;
290 * also the note in impl_sse/decoding.c::p7_Decoding().
291 *
292 * In short: p7_Decoding() can overflow in cases where the
293 * model is in unilocal mode (expects to see a single
294 * "domain") but the target contains more than one domain.
295 * In searches, I believe this only happens on repetitive
296 * garbage, because the domain postprocessor is very good
297 * about identifying single domains before doing posterior
298 * decoding. But in hmmalign, we're in unilocal mode
299 * to begin with, and the user can definitely give us a
300 * multidomain protein.
301 *
302 * We need to make this far more robust; but that's probably
303 * an issue to deal with when we really spend some time
304 * looking hard at hmmalign performance. For now (Nov 2009;
305 * in beta tests leading up to 3.0 release) I'm more
306 * concerned with stabilizing the search programs.
307 *
308 * The workaround is to detect the overflow and fail over to
309 * slow generic routines.
310 */
311 if (gxf == NULL) gxf = p7_gmx_Create(hmm->M, sq[idx]->n);
312 else p7_gmx_GrowTo(gxf, hmm->M, sq[idx]->n);
313
314 if (gxb == NULL) gxb = p7_gmx_Create(hmm->M, sq[idx]->n);
315 else p7_gmx_GrowTo(gxb, hmm->M, sq[idx]->n);
316
317 p7_ReconfigLength(gm, sq[idx]->n);
318
319 p7_GForward (sq[idx]->dsq, sq[idx]->n, gm, gxf, &fwdsc);
320 p7_GBackward(sq[idx]->dsq, sq[idx]->n, gm, gxb, NULL);
321 p7_GDecoding(gm, gxf, gxb, gxb);
322 p7_GOptimalAccuracy(gm, gxb, gxf, &oasc);
323 p7_GOATrace (gm, gxb, gxf, tr[idx]);
324 p7_gmx_Reuse(gxf);
325 p7_gmx_Reuse(gxb);
326 }
327
328
329 /* the above steps aren't storing the tfrom/tto values in the trace,
330 * which are required for downstream processing in this case, so
331 * hack them here. Note - this treats the whole thing as one domain,
332 * even if there are really multiple domains.
333 */
334 // skip the parts of the trace that precede the first match state
335 tfrom = 2;
336 while (tr[idx]->st[tfrom] != p7T_M) tfrom++;
337
338 tto = tfrom + 1;
339 //run until the model is exited
340 while (tr[idx]->st[tto] != p7T_E) tto++;
341
342 tr[idx]->tfrom[0] = tfrom;
343 tr[idx]->tto[0] = tto - 1;
344
345
346 p7_omx_Reuse(oxf);
347 p7_omx_Reuse(oxb);
348 }
349
350 #if 0
351 for (idx = 0; idx < nseq; idx++)
352 p7_trace_Dump(stdout, tr[idx], gm, sq[idx]->dsq);
353 #endif
354
355
356
357 p7_omx_Destroy(oxf);
358 p7_omx_Destroy(oxb);
359 p7_gmx_Destroy(gxf);
360 p7_gmx_Destroy(gxb);
361 p7_bg_Destroy(bg);
362 p7_profile_Destroy(gm);
363 p7_oprofile_Destroy(om);
364
365
366 return eslOK;
367 }
368
369
370 /* Function: p7_tracealign_getTracesAndStats()
371 *
372 * Synopsis: Compute traces and stats for a collection of sequences
373 * relative to a given HMM
374 *
375 * Purpose: Given an <hmm> and a set of sequences <sq>, calculate an
376 * optimal accuracy MSA (returned in <ret_msa>) along with
377 * three arrays mapping values onto positions of the input
378 * sequences. The mapped values are:
379 * <ret_pp> - The posterior probability associated with
380 * each residue aligned to the core model
381 * <ret_relent> - The relative entropy of the model position
382 * to which each matched residue is aligned
383 * <ret_scores> - The bit score of residue vs the model for
384 * each matched residue
385 *
386 * Return: eslOK if no errors
387 */
388 int
389 p7_tracealign_getMSAandStats(P7_HMM *hmm, ESL_SQ **sq, int N, ESL_MSA **ret_msa, float **ret_pp, float **ret_relent, float **ret_scores )
390 {
391
392 P7_TRACE **tr = NULL; /* array of tracebacks */
393 ESL_MSA *msa = NULL; /* resulting multiple alignment */
394 P7_BG *bg = NULL;
395 int i; // seq_id
396 int z; // trace position
397 int j; // position in the query seq
398 int k; // positon in the model
399 int x; // counter
400 float p; // temporary probability holder
401 int status;
402 int msaopts = 0; /* flags to p7_tracealign_Seqs() */
403
404 msaopts |= p7_ALL_CONSENSUS_COLS; /* default as of 3.1 */
405
406 bg = p7_bg_Create(hmm->abc);
407
408 ESL_ALLOC(tr, sizeof(P7_TRACE *) * N);
409 for (i = 0; i < N; i++)
410 tr[i] = p7_trace_CreateWithPP();
411
412
413 p7_tracealign_computeTraces(hmm, sq, 0, N, tr);
414 p7_tracealign_Seqs(sq, tr, N, hmm->M, msaopts, hmm, &msa);
415 *ret_msa = msa;
416
417 for (i=0; i<N; i++) {
418 for (j=0; j<=sq[i]->n; j++) {
419 ret_pp[i][j] = 0.0;
420 ret_relent[i][j] = 0.0;
421 ret_scores[i][j] = 0.0;
422 }
423
424 j = tr[i]->tfrom[0] - 2;
425 for (z = tr[i]->tfrom[0]; z <= tr[i]->tto[0]; z++) {
426
427 if (tr[i]->st[z] != p7T_D ) { //M or I
428
429 ret_pp[i][j] = tr[i]->pp[z];
430
431 if (tr[i]->st[z] == p7T_M ) {
432 k = tr[i]->k[z];
433 for (x=0; x<hmm->abc->K; x++) {
434 p = hmm->mat[k][x];
435 ret_relent[i][j] += p * log(p / bg->f[x]) / log(2);
436 }
437
438 p = hmm->mat[k][sq[i]->dsq[j]];
439 ret_scores[i][j] = log(p / bg->f[sq[i]->dsq[j]]) / log(2);
440
441 }
442 j++;
443 }
444
445 }
446 }
447
448 for (i = 0; i < N; i++) p7_trace_Destroy(tr[i]);
449 free(tr);
450
451 return eslOK;
452
453 ERROR:
454 if (tr != NULL) {
455 for (i = 0; i < N; i++) p7_trace_Destroy(tr[i]);
456 free(tr);
457 }
458 return status;
459 }
460
461
462 /*--------------- end, exposed API ------------------------------*/
463
464
465
466
467 /*****************************************************************
468 * 2. Internal functions used by the API
469 *****************************************************************/
470
471 /* map_new_msa()
472 *
473 * Construct <inscount[0..M]>, <matuse[1..M]>, and <matmap[1..M]>
474 * arrays for mapping model consensus nodes <1..M> onto columns
475 * <1..alen> of a new MSA.
476 *
477 * Here's the problem. We want to align the match states in columns,
478 * but some sequences have inserted symbols in them; we need some
479 * sort of overall knowledge of where the inserts are and how long
480 * they are in order to create the alignment.
481 *
482 * Here's our trick. inscount[] is a 0..M array; inserts[k] stores
483 * the maximum number of times insert substate k was used. This
484 * is the maximum number of gaps to insert between canonical
485 * column k and k+1. inserts[0] is the N-term tail; inserts[M] is
486 * the C-term tail.
487 *
488 * Additionally, matuse[k=1..M] says whether we're going to make an
489 * alignment column for consensus position k. By default this is
490 * <TRUE> only if there is at least one residue in the column. If
491 * the <p7_ALL_CONSENSUS_COLS> option flag is set, though, all
492 * matuse[1..M] are set <TRUE>. (matuse[0] is unused, always <FALSE>.)
493 *
494 * Then, using these arrays, we construct matmap[] and determine alen.
495 * If match state k is represented as an alignment column,
496 * matmap[1..M] = that position, <1..alen>.
497 * If match state k is not in the alignment (<matuse[k] == FALSE>),
498 * matmap[k] = matmap[k-1] = the last alignment column that a match
499 * state did map to; this is a trick to make some apos coordinate setting
500 * work cleanly.
501 * Because of this trick, you can't just assume because matmap[k] is
502 * nonzero that match state k maps somewhere in the alignment;
503 * you have to check matuse[k] == TRUE, then look at what matmap[k] says.
504 * Remember that N and C emit on transition, hence the check for an
505 * N->N or C->C transition before bumping nins.
506 * <matmap[0]> is unused; by convention, <matmap[0] = 0>.
507 */
508 static int
509 map_new_msa(P7_TRACE **tr, int nseq, int M, int optflags, int **ret_inscount,
510 int **ret_matuse, int **ret_matmap, int *ret_alen)
511 {
512 int *inscount = NULL; /* inscount[k=0..M] == max # of inserts in node k */
513 int *insnum = NULL; /* insct[k=0..M] == # of inserts in node k in current trace */
514 int *matuse = NULL; /* matuse[k=1..M] == TRUE|FALSE: does node k map to an alignment column */
515 int *matmap = NULL; /* matmap[k=1..M]: if matuse[k] TRUE, what column 1..alen does node k map to */
516 int idx; /* counter over sequences */
517 int z; /* index into trace positions */
518 int alen; /* length of alignment */
519 int k; /* counter over nodes 1..M */
520 int status;
521
522 ESL_ALLOC(inscount, sizeof(int) * (M+1));
523 ESL_ALLOC(insnum, sizeof(int) * (M+1));
524 ESL_ALLOC(matuse, sizeof(int) * (M+1)); matuse[0] = 0;
525 ESL_ALLOC(matmap, sizeof(int) * (M+1)); matmap[0] = 0;
526 esl_vec_ISet(inscount, M+1, 0);
527 if (optflags & p7_ALL_CONSENSUS_COLS) esl_vec_ISet(matuse+1, M, TRUE);
528 else esl_vec_ISet(matuse+1, M, FALSE);
529
530 /* Collect inscount[], matuse[] in a fairly general way
531 * (either profile or core traces work)
532 */
533 for (idx = 0; idx < nseq; idx++)
534 {
535 esl_vec_ISet(insnum, M+1, 0);
536 for (z = 1; z < tr[idx]->N; z++)
537 {
538 switch (tr[idx]->st[z]) {
539 case p7T_I: insnum[tr[idx]->k[z]]++; break;
540 case p7T_N: if (tr[idx]->st[z-1] == p7T_N) insnum[0]++; break;
541 case p7T_C: if (tr[idx]->st[z-1] == p7T_C) insnum[M]++; break;
542 case p7T_M: matuse[tr[idx]->k[z]] = TRUE; break;
543 case p7T_J: p7_Die("J state unsupported");
544 default: break;
545 }
546 }
547 for (k = 0; k <= M; k++)
548 inscount[k] = ESL_MAX(inscount[k], insnum[k]);
549 }
550
551 /* if we're trimming N and C off, reset inscount[0], inscount[M] to 0. */
552 if (optflags & p7_TRIM) { inscount[0] = inscount[M] = 0; }
553
554 /* Use inscount, matuse to set the matmap[] */
555 alen = inscount[0];
556 for (k = 1; k <= M; k++) {
557 if (matuse[k]) { matmap[k] = alen+1; alen += 1+inscount[k]; }
558 else { matmap[k] = alen; alen += inscount[k]; }
559 }
560
561 free(insnum);
562 *ret_inscount = inscount;
563 *ret_matuse = matuse;
564 *ret_matmap = matmap;
565 *ret_alen = alen;
566 return eslOK;
567
568 ERROR:
569 if (inscount) free(inscount);
570 if (insnum) free(insnum);
571 if (matuse) free(matuse);
572 if (matmap) free(matmap);
573 *ret_inscount = NULL;
574 *ret_matuse = NULL;
575 *ret_matmap = NULL;
576 *ret_alen = 0;
577 return status;
578 }
579
580
581 /* get_dsq_z()
582 * this abstracts residue-fetching from either a sq array or a previous MSA;
583 * one and only one of <sq>, <msa> is non-<NULL>;
584 * get the digital residue corresponding to tr[idx]->i[z].
585 */
586 static ESL_DSQ
587 get_dsq_z(ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int idx, int z)
588 {
589 return ( (premsa == NULL) ? sq[idx]->dsq[tr[idx]->i[z]] : premsa->ax[idx][tr[idx]->i[z]]);
590 }
591
592 /* make_digital_msa()
593 * Create a new digital MSA, given traces <tr> for digital <sq> or for
594 * a digital <premsa>. (One and only one of <sq>,<premsa> are
595 * non-<NULL>.
596 * The traces may either be profile traces or core traces;
597 * core traces may contain X "states" for fragments.
598 *
599 * matmap[k] = apos of match k, in digital coords: matmap[1..M] = [1..alen]
600 */
601
602 static int
603 make_digital_msa(ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int nseq, const int *matuse, const int *matmap, int M, int alen, int optflags, ESL_MSA **ret_msa)
604 {
605 const ESL_ALPHABET *abc = (sq == NULL) ? premsa->abc : sq[0]->abc;
606 ESL_MSA *msa = NULL;
607 int idx;
608 int apos;
609 int z;
610 int status;
611
612 if ((msa = esl_msa_CreateDigital(abc, nseq, alen)) == NULL) { status = eslEMEM; goto ERROR; }
613
614 for (idx = 0; idx < nseq; idx++)
615 {
616 msa->ax[idx][0] = eslDSQ_SENTINEL;
617 for (apos = 1; apos <= alen; apos++) msa->ax[idx][apos] = esl_abc_XGetGap(abc);
618 msa->ax[idx][alen+1] = eslDSQ_SENTINEL;
619
620 apos = 1;
621 for (z = 0; z < tr[idx]->N; z++)
622 {
623 switch (tr[idx]->st[z]) {
624 case p7T_M:
625 msa->ax[idx][matmap[tr[idx]->k[z]]] = get_dsq_z(sq, premsa, tr, idx, z);
626 apos = matmap[tr[idx]->k[z]] + 1;
627 break;
628
629 case p7T_D:
630 if (matuse[tr[idx]->k[z]]) /* bug h77: if all col is deletes, do nothing; do NOT overwrite a column */
631 msa->ax[idx][matmap[tr[idx]->k[z]]] = esl_abc_XGetGap(abc); /* overwrites ~ in Dk column on X->Dk */
632 apos = matmap[tr[idx]->k[z]] + 1;
633 break;
634
635 case p7T_I:
636 if ( !(optflags & p7_TRIM) || (tr[idx]->k[z] != 0 && tr[idx]->k[z] != M)) {
637 msa->ax[idx][apos] = get_dsq_z(sq, premsa, tr, idx, z);
638 apos++;
639 }
640 break;
641
642 case p7T_N:
643 case p7T_C:
644 if (! (optflags & p7_TRIM) && tr[idx]->i[z] > 0) {
645 msa->ax[idx][apos] = get_dsq_z(sq, premsa, tr, idx, z);
646 apos++;
647 }
648 break;
649
650 case p7T_E:
651 apos = matmap[M]+1; /* set position for C-terminal tail */
652 break;
653
654 case p7T_X:
655 /* Mark fragments (B->X and X->E containing core traces):
656 * convert flanks from gaps to ~
657 */
658 if (tr[idx]->st[z-1] == p7T_B)
659 { /* B->X leader. This is a core trace and a fragment. Convert leading gaps to ~ */
660 /* to set apos for an initial Ik: peek at next state for B->X->Ik; superfluous for ->{DM}k: */
661 for (apos = 1; apos <= matmap[tr[idx]->k[z+1]]; apos++)
662 msa->ax[idx][apos] = esl_abc_XGetMissing(abc);
663 /* tricky! apos is now exactly where it needs to be for X->Ik. all other cases except B->X->Ik set their own apos */
664 }
665 else if (tr[idx]->st[z+1] == p7T_E)
666 { /* X->E trailer. This is a core trace and a fragment. Convert trailing gaps to ~ */
667 /* don't need to set apos for trailer. There can't be any more residues in a core trace once we hit X->E */
668 for (; apos <= alen; apos++)
669 msa->ax[idx][apos] = esl_abc_XGetMissing(abc);
670 }
671 else ESL_XEXCEPTION(eslECORRUPT, "make_digital_msa(): X state in unexpected position in trace");
672
673 break;
674
675 default:
676 break;
677 }
678 }
679 }
680
681 msa->nseq = nseq;
682 msa->alen = alen;
683 *ret_msa = msa;
684 return eslOK;
685
686 ERROR:
687 if (msa) esl_msa_Destroy(msa);
688 *ret_msa = NULL;
689 return status;
690 }
691
692
693 /* make_text_msa()
694 * Create a new text MSA, given traces <tr> for digital <sq> or for a digital <premsa>.
695 * (One and only one of <sq>,<premsa> are non-<NULL>.
696 *
697 * The reason to make a text-mode MSA rather than let Easel handle printing a digital
698 * MSA is to impose HMMER's standard representation on gap characters and insertions:
699 * at inserts, gaps are '.' and residues are lower-case, whereas at matches, gaps are '-'
700 * and residues are upper case.
701 *
702 * Also see comments in make_digital_msa(), above.
703 */
704 static int
705 make_text_msa(ESL_SQ **sq, const ESL_MSA *premsa, P7_TRACE **tr, int nseq, const int *matuse, const int *matmap, int M, int alen, int optflags, ESL_MSA **ret_msa)
706 {
707 const ESL_ALPHABET *abc = (sq == NULL) ? premsa->abc : sq[0]->abc;
708 ESL_MSA *msa = NULL;
709 int idx;
710 int apos;
711 int z;
712 int k;
713 int status;
714
715 if ((msa = esl_msa_Create(nseq, alen)) == NULL) { status = eslEMEM; goto ERROR; }
716
717 for (idx = 0; idx < nseq; idx++)
718 {
719 for (apos = 0; apos < alen; apos++) msa->aseq[idx][apos] = '.';
720 for (k = 1; k <= M; k++) if (matuse[k]) msa->aseq[idx][-1+matmap[k]] = '-';
721 msa->aseq[idx][apos] = '\0';
722
723 apos = 0;
724 for (z = 0; z < tr[idx]->N; z++)
725 {
726 switch (tr[idx]->st[z]) {
727 case p7T_M:
728 msa->aseq[idx][-1+matmap[tr[idx]->k[z]]] = toupper(abc->sym[get_dsq_z(sq, premsa, tr, idx, z)]);
729 apos = matmap[tr[idx]->k[z]]; /* i.e. one past the match column. remember, text mode is 0..alen-1 */
730 break;
731
732 case p7T_D:
733 if (matuse[tr[idx]->k[z]]) /* bug #h77: if all column is deletes, do nothing; do NOT overwrite a column */
734 msa->aseq[idx][-1+matmap[tr[idx]->k[z]]] = '-'; /* overwrites ~ in Dk column on X->Dk */
735 apos = matmap[tr[idx]->k[z]];
736 break;
737
738 case p7T_I:
739 if ( !(optflags & p7_TRIM) || (tr[idx]->k[z] != 0 && tr[idx]->k[z] != M)) {
740 msa->aseq[idx][apos] = tolower(abc->sym[get_dsq_z(sq, premsa, tr, idx, z)]);
741 apos++;
742 }
743 break;
744
745 case p7T_N:
746 case p7T_C:
747 if (! (optflags & p7_TRIM) && tr[idx]->i[z] > 0) {
748 msa->aseq[idx][apos] = tolower(abc->sym[get_dsq_z(sq, premsa, tr, idx, z)]);
749 apos++;
750 }
751 break;
752
753 case p7T_E:
754 apos = matmap[M]; /* set position for C-terminal tail */
755 break;
756
757 case p7T_X:
758 /* Mark fragments (B->X and X->E containing core traces):
759 * convert flanks from gaps to ~
760 */
761 if (tr[idx]->st[z-1] == p7T_B)
762 { /* B->X leader. This is a core trace and a fragment. Convert leading gaps to ~ */
763 for (apos = 0; apos < matmap[tr[idx]->k[z+1]]; apos++)
764 msa->aseq[idx][apos] = '~';
765 /* tricky; apos exactly where it must be for X->Ik; see comments in make_digital_msa() */
766 }
767 else if (tr[idx]->st[z+1] == p7T_E)
768 { /* X->E trailer. This is a core trace and a fragment. Convert trailing gaps to ~ */
769 for (; apos < alen; apos++)
770 msa->aseq[idx][apos] = '~';
771 }
772 else ESL_XEXCEPTION(eslECORRUPT, "make_text_msa(): X state in unexpected position in trace");
773
774 break;
775
776 default:
777 break;
778 }
779 }
780 }
781 msa->nseq = nseq;
782 msa->alen = alen;
783 *ret_msa = msa;
784 return eslOK;
785
786 ERROR:
787 if (msa != NULL) esl_msa_Destroy(msa);
788 *ret_msa = NULL;
789 return status;
790 }
791
792
793
794 /* annotate_rf()
795 * Synopsis: Add RF reference coordinate annotation line to new MSA.
796 * Incept: SRE, Fri Jan 16 09:30:08 2009 [Janelia]
797 *
798 * Purpose: Create an RF reference coordinate annotation line that annotates the
799 * consensus columns: the columns associated with profile match states.
800 *
801 * Recall that msa->rf is <NULL> when unset/by default in an MSA;
802 * msa->rf[0..alen-1] = 'x' | '.' is the simplest convention;
803 * msa->rf is a NUL-terminated string (msa->rf[alen] = '\0')
804 *
805 * Args: msa - alignment to annotate (<msa->rf> is allocated, set)
806 * M - profile length
807 * matuse - matuse[1..M] == TRUE | FALSE : is this match state represented
808 * by a column in the alignment.
809 * matmap - matmap[1..M] == (1..alen): if matuse[k], then what alignment column
810 * does state k map to.
811 *
812 * Returns: <eslOK> on success; msa->rf is set to an appropriate reference
813 * coordinate string.
814 *
815 * Throws: <eslEMEM> on allocation failure.
816 */
817 static int
818 annotate_rf(ESL_MSA *msa, int M, const int *matuse, const int *matmap)
819 {
820 int apos, k;
821 int status;
822
823 ESL_ALLOC(msa->rf, sizeof(char) * (msa->alen+1));
824 for (apos = 0; apos < msa->alen; apos++)
825 msa->rf[apos] = '.';
826 msa->rf[msa->alen] = '\0';
827
828 for (k = 1; k <= M; k++)
829 if (matuse[k]) msa->rf[matmap[k]-1] = 'x'; /* watch off by one: rf[0..alen-1]; matmap[] = 1..alen */
830 return eslOK;
831
832 ERROR:
833 return status;
834 }
835
836
837 /* annotate_mm()
838 * Synopsis: Add MM reference coordinate annotation line to new MSA.
839 *
840 * Purpose: Create an MM Model Mask annotation line that annotates the
841 * consensus columns: the columns associated with profile match states.
842 *
843 * Recall that msa->mm is <NULL> when unset/by default in an MSA;
844 * msa->mm[0..alen-1] = 'm' | '.' is the simplest convention;
845 * msa->mm is a NUL-terminated string (msa->mm[alen] = '\0')
846 *
847 * Args: msa - alignment to annotate (<msa->rf> is allocated, set)
848 * M - profile length
849 * matuse - matuse[1..M] == TRUE | FALSE : is this match state represented
850 * by a column in the alignment.
851 * matmap - matmap[1..M] == (1..alen): if matuse[k], then what alignment column
852 * does state k map to.
853 *
854 * Returns: <eslOK> on success; msa->mm is set to an appropriate model mask
855 * coordinate string.
856 *
857 * Throws: <eslEMEM> on allocation failure.
858 */
859 static int
860 annotate_mm(ESL_MSA *msa, P7_HMM * hmm, const int *matuse, const int *matmap)
861 {
862 int apos, k;
863 int status;
864
865 if (hmm->mm == NULL) return eslOK; //nothing to do
866
867 ESL_ALLOC(msa->mm, sizeof(char) * (msa->alen+1));
868 for (apos = 0; apos < msa->alen; apos++)
869 msa->mm[apos] = '.';
870 msa->mm[msa->alen] = '\0';
871
872 for (k = 0; k < hmm->M; k++)
873 if (matuse[k])
874 msa->mm[matmap[k]-1] = hmm->mm[k];
875 return eslOK;
876
877 ERROR:
878 return status;
879 }
880
881 /* annotate_posterior_probability()
882 * Synopsis: Add posterior probability annotation lines to new MSA.
883 */
884 static int
885 annotate_posterior_probability(ESL_MSA *msa, P7_TRACE **tr, const int *matmap, int M, int optflags)
886 {
887 double *totp = NULL; /* total posterior probability in column <apos>: [0..alen-1] */
888 int *matuse = NULL; /* #seqs with pp annotation in column <apos>: [0..alen-1] */
889 int idx; /* counter over sequences [0..nseq-1] */
890 int apos; /* counter for alignment columns: pp's are [0..alen-1] (unlike ax) */
891 int z; /* counter over trace positions [0..tr->N-1] */
892 int status;
893
894 /* Determine if any of the traces have posterior probability annotation. */
895 for (idx = 0; idx < msa->nseq; idx++)
896 if (tr[idx]->pp != NULL) break;
897 if (idx == msa->nseq) return eslOK;
898
899 ESL_ALLOC(matuse, sizeof(double) * (msa->alen)); esl_vec_ISet(matuse, msa->alen, 0);
900 ESL_ALLOC(totp, sizeof(double) * (msa->alen)); esl_vec_DSet(totp, msa->alen, 0.0);
901
902 ESL_ALLOC(msa->pp, sizeof(char *) * msa->sqalloc);
903 for (idx = 0; idx < msa->nseq; idx++)
904 {
905 if (tr[idx]->pp == NULL) { msa->pp[idx] = NULL; continue; }
906
907 ESL_ALLOC(msa->pp[idx], sizeof(char) * (msa->alen+1));
908 for (apos = 0; apos < msa->alen; apos++) msa->pp[idx][apos] = '.';
909 msa->pp[idx][msa->alen] = '\0';
910
911 apos = 0;
912 for (z = 0; z < tr[idx]->N; z++)
913 {
914 switch (tr[idx]->st[z]) {
915 case p7T_M:
916 msa->pp[idx][matmap[tr[idx]->k[z]]-1] = p7_alidisplay_EncodePostProb(tr[idx]->pp[z]);
917 totp [matmap[tr[idx]->k[z]]-1]+= tr[idx]->pp[z];
918 matuse[matmap[tr[idx]->k[z]]-1]++;
919 case p7T_D:
920 apos = matmap[tr[idx]->k[z]];
921 break;
922
923 case p7T_I:
924 if ( !(optflags & p7_TRIM) || (tr[idx]->k[z] != 0 && tr[idx]->k[z] != M)) {
925 msa->pp[idx][apos] = p7_alidisplay_EncodePostProb(tr[idx]->pp[z]);
926 apos++;
927 }
928 break;
929
930 case p7T_N:
931 case p7T_C:
932 if (! (optflags & p7_TRIM) && tr[idx]->i[z] > 0) {
933 msa->pp[idx][apos] = p7_alidisplay_EncodePostProb(tr[idx]->pp[z]);
934 apos++;
935 }
936 break;
937
938 case p7T_E:
939 apos = matmap[M]; /* set position for C-terminal tail */
940 break;
941
942 default:
943 break;
944 }
945 }
946 }
947 for (; idx < msa->sqalloc; idx++) msa->pp[idx] = NULL; /* for completeness, following easel MSA conventions, but should be a no-op: nseq==sqalloc */
948
949 /* Consensus posterior probability annotation: only on match columns */
950 ESL_ALLOC(msa->pp_cons, sizeof(char) * (msa->alen+1));
951 for (apos = 0; apos < msa->alen; apos++) msa->pp_cons[apos] = '.';
952 msa->pp_cons[msa->alen] = '\0';
953 for (apos = 0; apos < msa->alen; apos++)
954 if (matuse[apos]) msa->pp_cons[apos] = p7_alidisplay_EncodePostProb( totp[apos] / (double) matuse[apos]);
955
956 free(matuse);
957 free(totp);
958 return eslOK;
959
960 ERROR:
961 if (matuse != NULL) free(matuse);
962 if (totp != NULL) free(totp);
963 if (msa->pp != NULL) esl_Free2D((void **) msa->pp, msa->sqalloc);
964 return status;
965 }
966
967
968 /* Function: rejustify_insertions_digital()
969 * Synopsis:
970 * Incept: SRE, Thu Oct 23 13:06:12 2008 [Janelia]
971 *
972 * Purpose:
973 *
974 * Args: msa - alignment to rejustify
975 * digital mode: ax[0..nseq-1][1..alen] and abc is valid
976 * text mode: aseq[0..nseq-1][0..alen-1]
977 * inserts - # of inserted columns following node k, for k=0.1..M
978 * inserts[0] is for N state; inserts[M] is for C state
979 * matmap - index of column associated with node k [k=0.1..M; matmap[0] = 0]
980 * this is an alignment column index 1..alen, same offset as <ax>
981 * if applied to text mode aseq or annotation, remember to -1
982 * if no residues use match state k, matmap[k] is the
983 * index of the last column used before node k's columns
984 * start: thus matmap[k]+1 is always the start of
985 * node k's insertion (if any).
986 * matuse - TRUE if an alignment column is associated with node k: [k=0.1..M; matuse[0] = 0].
987 * if matuse[k] == 0, every sequence deleted at node k,
988 * and we're collapsing the column rather than showing all
989 * gaps.
990 *
991 * Note: The insertion for node k is of length <inserts[k]> columns,
992 * and in 1..alen coords it runs from
993 * matmap[k]+1 .. matmap[k+1]-matuse[k+1].
994 *
995 *
996 * Returns:
997 *
998 * Throws: (no abnormal error conditions)
999 *
1000 * Xref:
1001 */
1002 static int
1003 rejustify_insertions_digital(ESL_MSA *msa, const int *inserts, const int *matmap, const int *matuse, int M)
1004 {
1005 int idx;
1006 int k;
1007 int apos;
1008 int nins;
1009 int npos, opos;
1010
1011 for (idx = 0; idx < msa->nseq; idx++)
1012 {
1013 for (k = 0; k < M; k++)
1014 if (inserts[k] > 1)
1015 {
1016 for (nins = 0, apos = matmap[k]+1; apos <= matmap[k+1]-matuse[k+1]; apos++)
1017 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos])) nins++;
1018
1019 if (k == 0) nins = 0; /* N-terminus is right justified */
1020 else nins /= 2; /* split in half; nins now = # of residues left left-justified */
1021
1022 opos = npos = matmap[k+1]-matuse[k+1];
1023 while (opos >= matmap[k]+1+nins) {
1024 if (esl_abc_XIsGap(msa->abc, msa->ax[idx][opos])) opos--;
1025 else {
1026 msa->ax[idx][npos] = msa->ax[idx][opos];
1027 if (msa->pp != NULL && msa->pp[idx] != NULL) msa->pp[idx][npos-1] = msa->pp[idx][opos-1];
1028 npos--;
1029 opos--;
1030 }
1031 }
1032 while (npos >= matmap[k]+1+nins) {
1033 msa->ax[idx][npos] = esl_abc_XGetGap(msa->abc);
1034 if (msa->pp != NULL && msa->pp[idx] != NULL) msa->pp[idx][npos-1] = '.';
1035 npos--;
1036 }
1037 }
1038 }
1039 return eslOK;
1040 }
1041
1042 static int
1043 rejustify_insertions_text(const ESL_ALPHABET *abc, ESL_MSA *msa, const int *inserts, const int *matmap, const int *matuse, int M)
1044 {
1045 int idx;
1046 int k;
1047 int apos;
1048 int nins;
1049 int npos, opos;
1050
1051 for (idx = 0; idx < msa->nseq; idx++)
1052 {
1053 for (k = 0; k < M; k++)
1054 if (inserts[k] > 1)
1055 {
1056 for (nins = 0, apos = matmap[k]; apos < matmap[k+1]-matuse[k+1]; apos++)
1057 if (esl_abc_CIsResidue(abc, msa->aseq[idx][apos])) nins++;
1058
1059 if (k == 0) nins = 0; /* N-terminus is right justified */
1060 else nins /= 2; /* split in half; nins now = # of residues left left-justified */
1061
1062 opos = npos = -1+matmap[k+1]-matuse[k+1];
1063 while (opos >= matmap[k]+nins) {
1064 if (esl_abc_CIsGap(abc, msa->aseq[idx][opos])) opos--;
1065 else {
1066 msa->aseq[idx][npos] = msa->aseq[idx][opos];
1067 if (msa->pp != NULL && msa->pp[idx] != NULL) msa->pp[idx][npos] = msa->pp[idx][opos];
1068 npos--;
1069 opos--;
1070 }
1071 }
1072 while (npos >= matmap[k]+nins) {
1073 msa->aseq[idx][npos] = '.';
1074 if (msa->pp != NULL && msa->pp[idx] != NULL) msa->pp[idx][npos] = '.';
1075 npos--;
1076 }
1077 }
1078 }
1079 return eslOK;
1080 }
1081 /*---------------- end, internal functions ----------------------*/
1082
1083
1084 /*****************************************************************
1085 * 3. Test driver
1086 *****************************************************************/
1087
1088 #ifdef p7TRACEALIGN_TRACESTATS_TESTDRIVE
1089 /*
1090 gcc -o p7_tracealign_tracestats_test -msse2 -std=gnu99 -g -O2 -I. -L. -I../easel -L../easel -Dp7TRACEALIGN_TRACESTATS_TESTDRIVE tracealign.c -lhmmer -leasel -lm
1091 ./p7_tracealign_tracestats_test ../tutorial/SNORD96.hmm ../tutorial/SNORD96.sto
1092 */
1093
1094 #include <p7_config.h>
1095
1096 #include <stdio.h>
1097 #include <stdlib.h>
1098 #include <string.h>
1099
1100 #include "easel.h"
1101 #include "esl_alphabet.h"
1102 #include "esl_getopts.h"
1103 #include "esl_msa.h"
1104 #include "esl_msafile.h"
1105 #include "esl_sq.h"
1106 #include "esl_sqio.h"
1107 #include "esl_vectorops.h"
1108
1109 #include "hmmer.h"
1110
1111 static ESL_OPTIONS options[] = {
1112 /* name type default env range toggles reqs incomp help docgroup*/
1113 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
1114 { "-o", eslARG_OUTFILE, NULL, NULL, NULL, NULL, NULL, NULL, "output alignment to file <f>, not stdout", 1 },
1115 { "--trim", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "trim terminal tails of nonaligned residues from alignment", 2 },
1116 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "assert <seqfile>, <hmmfile> both protein: no autodetection", 2 },
1117 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "assert <seqfile>, <hmmfile> both DNA: no autodetection", 2 },
1118 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "assert <seqfile>, <hmmfile> both RNA: no autodetection", 2 },
1119 { "--informat", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "assert <seqfile> is in format <s>: no autodetection", 2 },
1120 { "--outformat", eslARG_STRING, "Stockholm", NULL, NULL, NULL, NULL, NULL, "output alignment in format <s>", 2 },
1121 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1122 };
1123
1124
1125 static char usage[] = "[-options] <hmmfile> <seqfile>";
1126 static char banner[] = "test driver for P7TRACE_SEQALIGNSTATS";
1127
1128 int
1129 main(int argc, char **argv)
1130 {
1131
1132 ESL_GETOPTS *go = NULL;
1133 char *hmmfile = NULL; /* HMM file name */
1134 char *seqfile = NULL; /* sequence file name */
1135 int infmt = eslSQFILE_UNKNOWN;
1136 int outfmt = eslMSAFILE_STOCKHOLM;
1137 P7_HMMFILE *hfp = NULL; /* open HMM file */
1138 ESL_SQFILE *sqfp = NULL; /* open sequence file */
1139 char *outfile = NULL; /* output filename */
1140 FILE *ofp = stdout; /* output stream */
1141 ESL_SQ **sq = NULL; /* array of sequences */
1142 void *p = NULL; /* tmp ptr for reallocation */
1143 int nseq = 0; /* # of sequences in <seqfile> */
1144 int totseq = 0; /* # of seqs in all sources */
1145 ESL_ALPHABET *abc = NULL; /* alphabet (set from the HMM file)*/
1146 P7_HMM *hmm = NULL;
1147 ESL_MSA *msa = NULL; /* resulting multiple alignment */
1148 int msaopts = 0; /* flags to p7_tracealign_Seqs() */
1149 int idx; /* counter over seqs, traces */
1150 int status; /* easel/hmmer return code */
1151 char errbuf[eslERRBUFSIZE];
1152 int j;
1153
1154 float **pp;
1155 float **relent;
1156 float **scores;
1157
1158
1159 /* Parse the command line
1160 */
1161 go = esl_getopts_Create(options);
1162 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) esl_fatal(argv[0], "Failed to parse command line: %s\n", go->errbuf);
1163
1164 if (esl_opt_VerifyConfig(go) != eslOK) esl_fatal(argv[0], "Error in configuration: %s\n", go->errbuf);
1165
1166 if (esl_opt_GetBoolean(go, "-h") ) {
1167 p7_banner (stdout, argv[0], banner);
1168 esl_usage (stdout, argv[0], usage);
1169 puts("\nBasic options:");
1170 esl_opt_DisplayHelp(stdout, go, 1, 2, 80);
1171 puts("\nLess common options:");
1172 esl_opt_DisplayHelp(stdout, go, 2, 2, 80);
1173 }
1174
1175
1176 if (esl_opt_ArgNumber(go) != 2) esl_fatal(argv[0], "Incorrect number of command line arguments.\n");
1177
1178
1179
1180 hmmfile = esl_opt_GetArg(go, 1);
1181 seqfile = esl_opt_GetArg(go, 2);
1182
1183 if (strcmp(hmmfile, "-") == 0 && strcmp(seqfile, "-") == 0)
1184 esl_fatal(argv[0], "Either <hmmfile> or <seqfile> may be '-' (to read from stdin), but not both.\n");
1185
1186 msaopts |= p7_ALL_CONSENSUS_COLS; /* default as of 3.1 */
1187 if (esl_opt_GetBoolean(go, "--trim")) msaopts |= p7_TRIM;
1188
1189 /* If caller declared an input format, decode it
1190 */
1191 if (esl_opt_IsOn(go, "--informat")) {
1192 infmt = esl_sqio_EncodeFormat(esl_opt_GetString(go, "--informat"));
1193 if (infmt == eslSQFILE_UNKNOWN) esl_fatal(argv[0], "%s is not a recognized input sequence file format\n", esl_opt_GetString(go, "--informat"));
1194 }
1195
1196 /* Determine output alignment file format */
1197 outfmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--outformat"));
1198 if (outfmt == eslMSAFILE_UNKNOWN) esl_fatal(argv[0], "%s is not a recognized output MSA file format\n", esl_opt_GetString(go, "--outformat"));
1199
1200 /* Open output stream */
1201 if ( (outfile = esl_opt_GetString(go, "-o")) != NULL)
1202 {
1203 if ((ofp = fopen(outfile, "w")) == NULL)
1204 esl_fatal(argv[0], "failed to open -o output file %s for writing\n", outfile);
1205 }
1206
1207
1208 /* If caller forced an alphabet on us, create the one the caller wants
1209 */
1210 if (esl_opt_GetBoolean(go, "--amino")) abc = esl_alphabet_Create(eslAMINO);
1211 else if (esl_opt_GetBoolean(go, "--dna")) abc = esl_alphabet_Create(eslDNA);
1212 else if (esl_opt_GetBoolean(go, "--rna")) abc = esl_alphabet_Create(eslRNA);
1213
1214 /* Read one HMM, and make sure there's only one.
1215 */
1216 status = p7_hmmfile_Open(hmmfile, NULL, &hfp, errbuf);
1217 if (status == eslENOTFOUND) p7_Fail("File existence/permissions problem in trying to open HMM file %s.\n%s\n", hmmfile, errbuf);
1218 else if (status == eslEFORMAT) p7_Fail("File format problem in trying to open HMM file %s.\n%s\n", hmmfile, errbuf);
1219 else if (status != eslOK) p7_Fail("Unexpected error %d in opening HMM file %s.\n%s\n", status, hmmfile, errbuf);
1220
1221 status = p7_hmmfile_Read(hfp, &abc, &hmm);
1222 if (status == eslEFORMAT) p7_Fail("Bad file format in HMM file %s:\n%s\n", hfp->fname, hfp->errbuf);
1223 else if (status == eslEINCOMPAT) p7_Fail("HMM in %s is not in the expected %s alphabet\n", hfp->fname, esl_abc_DecodeType(abc->type));
1224 else if (status == eslEOF) p7_Fail("Empty HMM file %s? No HMM data found.\n", hfp->fname);
1225 else if (status != eslOK) p7_Fail("Unexpected error in reading HMMs from %s\n", hfp->fname);
1226
1227 status = p7_hmmfile_Read(hfp, &abc, NULL);
1228 if (status != eslEOF) p7_Fail("HMM file %s does not contain just one HMM\n", hfp->fname);
1229 p7_hmmfile_Close(hfp);
1230
1231
1232
1233 /* Read digital sequences into an array (possibly concat'ed onto mapped seqs)
1234 */
1235 status = esl_sqfile_OpenDigital(abc, seqfile, infmt, NULL, &sqfp);
1236 if (status == eslENOTFOUND) p7_Fail("Failed to open sequence file %s for reading\n", seqfile);
1237 else if (status == eslEFORMAT) p7_Fail("Sequence file %s is empty or misformatted\n", seqfile);
1238 else if (status != eslOK) p7_Fail("Unexpected error %d opening sequence file %s\n", status, seqfile);
1239
1240 ESL_RALLOC(sq, p, sizeof(ESL_SQ *) * (totseq + 1));
1241 sq[totseq] = esl_sq_CreateDigital(abc);
1242 nseq = 0;
1243 while ((status = esl_sqio_Read(sqfp, sq[totseq+nseq])) == eslOK)
1244 {
1245 nseq++;
1246 ESL_RALLOC(sq, p, sizeof(ESL_SQ *) * (totseq+nseq+1));
1247 sq[totseq+nseq] = esl_sq_CreateDigital(abc);
1248 }
1249 if (status == eslEFORMAT) esl_fatal("Parse failed (sequence file %s):\n%s\n",
1250 sqfp->filename, esl_sqfile_GetErrorBuf(sqfp));
1251 else if (status != eslEOF) esl_fatal("Unexpected error %d reading sequence file %s", status, sqfp->filename);
1252 esl_sqfile_Close(sqfp);
1253 totseq += nseq;
1254
1255
1256 /* Remaining initializations, including trace array allocation
1257 */
1258 ESL_ALLOC(pp, sizeof(float*) * totseq );
1259 ESL_ALLOC(relent, sizeof(float*) * totseq );
1260 ESL_ALLOC(scores, sizeof(float*) * totseq );
1261 for (idx = 0; idx < totseq; idx++) {
1262 ESL_ALLOC(pp[idx], sizeof(float) * (1+sq[idx]->L));
1263 ESL_ALLOC(relent[idx], sizeof(float) * (1+sq[idx]->L));
1264 ESL_ALLOC(scores[idx], sizeof(float) * (1+sq[idx]->L));
1265 }
1266
1267 p7_tracealign_getMSAandStats(hmm, sq, totseq, &msa, pp, relent, scores);
1268
1269 esl_msafile_Write(ofp, msa, outfmt);
1270
1271 for (idx = 0; idx < totseq; idx++) {
1272 printf("%s\n------------------\n", sq[idx]->name);
1273 for (j=1; j<=sq[idx]->L; j++) {
1274 printf("%d: %.3f %.3f %.3f\n", j, pp[idx][j], relent[idx][j], scores[idx][j]);
1275 }
1276 printf("\n\n");
1277 }
1278
1279 for (idx = 0; idx < totseq; idx++) {
1280 free(pp[idx]);
1281 free(relent[idx]);
1282 free(scores[idx]);
1283 }
1284 free(pp);
1285 free(relent);
1286 free(scores);
1287
1288 for (idx = 0; idx <= totseq; idx++) esl_sq_Destroy(sq[idx]); /* including sq[nseq] because we overallocated */
1289 free(sq);
1290 esl_msa_Destroy(msa);
1291 p7_hmm_Destroy(hmm);
1292 if (ofp != stdout) fclose(ofp);
1293 esl_alphabet_Destroy(abc);
1294 esl_getopts_Destroy(go);
1295 return eslOK;
1296
1297 ERROR:
1298 return status;
1299 }
1300
1301 #endif /*p7TRACE_SEQALIGNSTATS_TESTDRIVE*/
1302 /*--------------------- end, test driver ------------------------*/
1303
1304
1305
1306
1307