Debian Codegraph @

easel/esl_msa.c

raw symbols SCIP
1 /* Multiple sequence alignments.
2 *
3 * Contents:
4 * 1. The <ESL_MSA> object
5 * 2. Digital mode MSA's
6 * 3. Setting, checking data fields in an <ESL_MSA>
7 * 4. Miscellaneous functions for manipulating MSAs
8 * 5. Debugging, testing, development
9 * 6. Unit tests
10 * 7. Test driver
11 */
12 #include <esl_config.h>
13
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <limits.h>
19 #ifdef HAVE_STRINGS_H
20 #include <strings.h> /* POSIX strcasecmp() */
21 #endif
22
23 #include "easel.h"
24 #include "esl_alphabet.h"
25 #include "esl_bitfield.h"
26 #include "esl_arr2.h"
27 #include "esl_arr3.h"
28 #include "esl_keyhash.h"
29 #include "esl_mem.h"
30 #include "esl_random.h"
31 #include "esl_randomseq.h"
32 #include "esl_ssi.h"
33 #include "esl_vectorops.h"
34 #include "esl_wuss.h"
35
36 #include "esl_msa.h"
37
38 /******************************************************************************
39 *# 1. The <ESL_MSA> object
40 *****************************************************************************/
41
42 static ESL_MSA *msa_create_mostly(int nseq, int64_t alen);
43
44
45 /* Function: esl_msa_Create()
46 * Synopsis: Creates an <ESL_MSA> object.
47 *
48 * Purpose: Creates and initializes an <ESL_MSA> object, and returns a
49 * pointer to it.
50 *
51 * If caller already knows the dimensions of the alignment,
52 * both <nseq> and <alen>, then <msa = esl_msa_Create(nseq,
53 * alen)> allocates the whole thing at once. The MSA's
54 * <nseq> and <alen> fields are set accordingly, and the
55 * caller doesn't have to worry about setting them; it can
56 * just fill in <aseq>.
57 *
58 * If caller doesn't know the dimensions of the alignment
59 * (for example, when parsing an alignment file), then
60 * <nseq> is taken to be an initial allocation size, and
61 * <alen> must be -1. <alen=-1> is used as a flag for a
62 * "growable" MSA. For example, the call <msa =
63 * esl_msa_Create(16, -1)>. allocates internally for an
64 * initial block of 16 sequences, but without allocating
65 * any space for individual sequences. This allocation can
66 * be expanded (by doubling) by calling <esl_msa_Expand()>.
67 * A created <msa> can only be <_Expand()>'ed if <alen> is
68 * -1.
69 *
70 * In a growable alignment, caller becomes responsible for
71 * memory allocation of each individual <aseq[i]>. Caller
72 * is also responsible for setting <nseq> and <alen> when
73 * it is done parsing and creating the new MSA. In
74 * particular, the <esl_msa_Destroy()> function relies on
75 * <nseq> to know how many individual sequences are
76 * allocated.
77 *
78 * Args: <nseq> - number of sequences, or nseq allocation blocksize
79 * <alen> - length of alignment in columns, or -1
80 *
81 * Returns: pointer to new MSA object, w/ all values initialized.
82 *
83 * Throws: <NULL> on allocation failure.
84 */
85 ESL_MSA *
86 esl_msa_Create(int nseq, int64_t alen)
87 {
88 int status;
89 ESL_MSA *msa;
90 int i;
91
92 ESL_DASSERT1(( nseq > 0 ));
93 ESL_DASSERT1(( alen >= -1));
94
95 msa = msa_create_mostly(nseq, alen); /* aseq is null upon successful return */
96 if (msa == NULL) return NULL; /* already threw error in msa_create_mostly, so percolate */
97
98 ESL_ALLOC(msa->aseq, sizeof(char *) * msa->sqalloc);
99 for (i = 0; i < msa->sqalloc; i++)
100 msa->aseq[i] = NULL;
101
102 if (alen != -1) {
103 for (i = 0; i < nseq; i++)
104 {
105 ESL_ALLOC(msa->aseq[i], sizeof(char) * (alen+1));
106 msa->aseq[i][alen] = '\0'; /* caller might forget to null terminate; help the poor */
107 }
108 msa->nseq = nseq;
109 }
110 return msa;
111
112 ERROR:
113 esl_msa_Destroy(msa);
114 return NULL;
115 }
116
117
118 /* Function: esl_msa_Expand()
119 * Synopsis: Reallocate for more sequences.
120 *
121 * Purpose: Double the current sequence allocation in <msa>.
122 * Typically used when we're reading an alignment sequentially
123 * from a file, so we don't know nseq 'til we're done.
124 *
125 * Returns: <eslOK> on success.
126 *
127 * Throws: <eslEMEM> on reallocation failure; <msa> is undamaged,
128 * and the caller may attempt to recover from the error.
129 *
130 * Throws <eslEINVAL> if <msa> is not growable: its <alen>
131 * field must be -1 to be growable.
132 *
133 * Xref: squid's MSAExpand(), 1999.
134 */
135 int
136 esl_msa_Expand(ESL_MSA *msa)
137 {
138 int status;
139 int old, new_size; /* old & new allocation sizes (max # seqs) */
140 int i,j;
141
142 if (msa->alen != -1)
143 ESL_EXCEPTION(eslEINVAL, "that MSA is not growable");
144
145 old = msa->sqalloc;
146 new_size = 2*old;
147
148 /* Normally either aseq (ascii) or ax (digitized) would be active, not both.
149 * We could make sure that that's true, but that's checked elsewhere.
150 */
151 if (msa->aseq) ESL_REALLOC(msa->aseq, sizeof(char *) * new_size);
152 if (msa->ax) ESL_REALLOC(msa->ax, sizeof(ESL_DSQ *) * new_size);
153
154 ESL_REALLOC(msa->sqname, sizeof(char *) * new_size);
155 ESL_REALLOC(msa->wgt, sizeof(double) * new_size);
156 ESL_REALLOC(msa->sqlen, sizeof(int64_t)* new_size);
157
158 if (msa->ss)
159 {
160 ESL_REALLOC(msa->ss, sizeof(char *) * new_size);
161 ESL_REALLOC(msa->sslen, sizeof(int64_t) * new_size);
162 }
163
164 if (msa->sa)
165 {
166 ESL_REALLOC(msa->sa, sizeof(char *) * new_size);
167 ESL_REALLOC(msa->salen, sizeof(int64_t) * new_size);
168 }
169
170 if (msa->pp)
171 {
172 ESL_REALLOC(msa->pp, sizeof(char *) * new_size);
173 ESL_REALLOC(msa->pplen, sizeof(int64_t) * new_size);
174 }
175
176 if (msa->sqacc) ESL_REALLOC(msa->sqacc, sizeof(char *) * new_size);
177 if (msa->sqdesc) ESL_REALLOC(msa->sqdesc, sizeof(char *) * new_size);
178
179 for (i = old; i < new_size; i++)
180 {
181 if (msa->aseq) msa->aseq[i] = NULL;
182 if (msa->ax) msa->ax[i] = NULL;
183
184 msa->sqname[i] = NULL;
185 msa->wgt[i] = -1.0; /* -1.0 means "unset so far" */
186 msa->sqlen[i] = 0;
187
188 if (msa->ss) { msa->ss[i] = NULL; msa->sslen[i] = 0; }
189 if (msa->sa) { msa->sa[i] = NULL; msa->salen[i] = 0; }
190 if (msa->pp) { msa->pp[i] = NULL; msa->pplen[i] = 0; }
191
192 if (msa->sqacc) msa->sqacc[i] = NULL;
193 if (msa->sqdesc) msa->sqdesc[i] = NULL;
194 }
195
196 /* Reallocate and re-init for unparsed #=GS tags, if we have some.
197 * gs is [0..ngs-1][0..nseq-1][], so we're reallocing the middle
198 * set of pointers.
199 */
200 if (msa->gs)
201 for (i = 0; i < msa->ngs; i++)
202 {
203 if (msa->gs[i])
204 {
205 ESL_REALLOC(msa->gs[i], sizeof(char *) * new_size);
206 for (j = old; j < new_size; j++)
207 msa->gs[i][j] = NULL;
208 }
209 }
210 /* Reallocate and re-init for unparsed #=GR tags, if we have some.
211 * gr is [0..ngs-1][0..nseq-1][], so we're reallocing the middle
212 * set of pointers.
213 */
214 if (msa->gr)
215 for (i = 0; i < msa->ngr; i++)
216 {
217 if (msa->gr[i])
218 {
219 ESL_REALLOC(msa->gr[i], sizeof(char *) * new_size);
220 for (j = old; j < new_size; j++)
221 msa->gr[i][j] = NULL;
222 }
223 }
224
225 msa->sqalloc = new_size;
226 return eslOK;
227
228 ERROR:
229 return status;
230 }
231
232 /* Function: esl_msa_Copy()
233 * Synopsis: Copies an MSA.
234 *
235 * Purpose: Makes a copy of <msa> in <new_msa>. Caller has
236 * already allocated <new_msa> to hold an MSA of
237 * at least <msa->nseq> sequences and <msa->alen>
238 * columns.
239 *
240 * Note: Because MSA's are not reusable, this function does a
241 * lot of internal allocation for optional fields, without
242 * checking <new_msa> to see if space was already allocated. To
243 * reuse an MSA <new_msa> and copy new data into it, we'll
244 * eventually need a <esl_msa_Reuse()> function, and/or
245 * recode this to reuse or free any already-allocated
246 * optional memory it encounters in <new_msa>. Until then,
247 * it's unlikely that <esl_msa_Copy()> is useful on its own;
248 * the caller would be expected to call <esl_msa_Clone()>
249 * instead.
250 *
251 * Returns: <eslOK> on success.
252 *
253 * Throws: <eslEMEM> on allocation failure. In this case, <new_msa>
254 * was only partially constructed, and should be treated
255 * as corrupt.
256 */
257 int
258 esl_msa_Copy(const ESL_MSA *msa, ESL_MSA *new_msa)
259 {
260 int i, x, j;
261 int status;
262
263 /* aseq[0..nseq-1][0..alen-1] strings,
264 * or ax[0..nseq-1][(0) 1..alen (alen+1)] digital seqs
265 * <new> must have one of them allocated already.
266 */
267 if (! (msa->flags & eslMSA_DIGITAL))
268 for (i = 0; i < msa->nseq; i++)
269 strcpy(new_msa->aseq[i], msa->aseq[i]);
270 else
271 {
272 for (i = 0; i < msa->nseq; i++)
273 memcpy(new_msa->ax[i], msa->ax[i], (msa->alen+2) * sizeof(ESL_DSQ));
274 new_msa->abc = msa->abc;
275 }
276
277 for (i = 0; i < msa->nseq; i++) {
278 esl_strdup(msa->sqname[i], -1, &(new_msa->sqname[i]));
279 new_msa->wgt[i] = msa->wgt[i];
280 }
281 /* alen, nseq were already set by Create() */
282 new_msa->flags = msa->flags;
283
284 esl_strdup(msa->name, -1, &(new_msa->name));
285 esl_strdup(msa->desc, -1, &(new_msa->desc));
286 esl_strdup(msa->acc, -1, &(new_msa->acc));
287 esl_strdup(msa->au, -1, &(new_msa->au));
288 esl_strdup(msa->ss_cons, -1, &(new_msa->ss_cons));
289 esl_strdup(msa->sa_cons, -1, &(new_msa->sa_cons));
290 esl_strdup(msa->pp_cons, -1, &(new_msa->pp_cons));
291 esl_strdup(msa->rf, -1, &(new_msa->rf));
292 esl_strdup(msa->mm, -1, &(new_msa->mm));
293
294 if (msa->sqacc != NULL) {
295 ESL_ALLOC(new_msa->sqacc, sizeof(char *) * new_msa->sqalloc);
296 for (i = 0; i < msa->nseq; i++) esl_strdup(msa->sqacc[i], -1, &(new_msa->sqacc[i]));
297 for ( ; i < new_msa->sqalloc; i++) new_msa->sqacc[i] = NULL;
298 }
299 if (msa->sqdesc != NULL) {
300 ESL_ALLOC(new_msa->sqdesc, sizeof(char *) * new_msa->sqalloc);
301 for (i = 0; i < msa->nseq; i++) esl_strdup(msa->sqdesc[i], -1, &(new_msa->sqdesc[i]));
302 for ( ; i < new_msa->sqalloc; i++) new_msa->sqdesc[i] = NULL;
303 }
304 if (msa->ss != NULL) {
305 ESL_ALLOC(new_msa->ss, sizeof(char *) * new_msa->sqalloc);
306 for (i = 0; i < msa->nseq; i++) esl_strdup(msa->ss[i], -1, &(new_msa->ss[i]));
307 for ( ; i < new_msa->sqalloc; i++) new_msa->ss[i] = NULL;
308 }
309 if (msa->sa != NULL) {
310 ESL_ALLOC(new_msa->sa, sizeof(char *) * msa->nseq);
311 for (i = 0; i < msa->nseq; i++) esl_strdup(msa->sa[i], -1, &(new_msa->sa[i]));
312 for ( ; i < new_msa->sqalloc; i++) new_msa->sa[i] = NULL;
313 }
314 if (msa->pp != NULL) {
315 ESL_ALLOC(new_msa->pp, sizeof(char *) * msa->nseq);
316 for (i = 0; i < msa->nseq; i++) esl_strdup(msa->pp[i], -1, &(new_msa->pp[i]));
317 for ( ; i < new_msa->sqalloc; i++) new_msa->pp[i] = NULL;
318 }
319
320 for (x = 0; x < eslMSA_NCUTS; x++) {
321 new_msa->cutoff[x] = msa->cutoff[x];
322 new_msa->cutset[x] = msa->cutset[x];
323 }
324
325 if (msa->ncomment > 0) {
326 ESL_ALLOC(new_msa->comment, sizeof(char *) * msa->ncomment);
327 new_msa->ncomment = msa->ncomment;
328 new_msa->alloc_ncomment = msa->ncomment;
329 for (i = 0; i < msa->ncomment; i++)
330 esl_strdup(msa->comment[i], -1, &(new_msa->comment[i]));
331 }
332
333 if (msa->ngf > 0) {
334 ESL_ALLOC(new_msa->gf_tag, sizeof(char *) * msa->ngf);
335 ESL_ALLOC(new_msa->gf, sizeof(char *) * msa->ngf);
336 new_msa->ngf = msa->ngf;
337 new_msa->alloc_ngf = msa->ngf;
338 for (i = 0; i < msa->ngf; i++) {
339 esl_strdup(msa->gf_tag[i], -1, &(new_msa->gf_tag[i]));
340 esl_strdup(msa->gf[i], -1, &(new_msa->gf[i]));
341 }
342 }
343
344 if (msa->ngs > 0) {
345 ESL_ALLOC(new_msa->gs_tag, sizeof(char *) * msa->ngs);
346 ESL_ALLOC(new_msa->gs, sizeof(char **) * msa->ngs);
347 new_msa->ngs = msa->ngs;
348 for (i = 0; i < msa->ngs; i++) {
349 ESL_ALLOC(new_msa->gs[i], sizeof(char *) * msa->nseq);
350 esl_strdup(msa->gs_tag[i], -1, &(new_msa->gs_tag[i]));
351 for (j = 0; j < msa->nseq; j++)
352 esl_strdup(msa->gs[i][j], -1, &(new_msa->gs[i][j]));
353 }
354 }
355
356 if (msa->ngc > 0) {
357 ESL_ALLOC(new_msa->gc_tag, sizeof(char *) * msa->ngc);
358 ESL_ALLOC(new_msa->gc, sizeof(char *) * msa->ngc);
359 new_msa->ngc = msa->ngc;
360 for (i = 0; i < msa->ngc; i++) {
361 esl_strdup(msa->gc_tag[i], -1, &(new_msa->gc_tag[i]));
362 esl_strdup(msa->gc[i], -1, &(new_msa->gc[i]));
363 }
364 }
365
366 if (msa->ngr > 0) {
367 ESL_ALLOC(new_msa->gr_tag, sizeof(char *) * msa->ngr);
368 ESL_ALLOC(new_msa->gr, sizeof(char **) * msa->ngr);
369 new_msa->ngr = msa->ngr;
370 for (i = 0; i < msa->ngr; i++) {
371 ESL_ALLOC(new_msa->gr[i], sizeof(char *) * msa->nseq);
372 esl_strdup(msa->gr_tag[i], -1, &(new_msa->gr_tag[i]));
373 for (j = 0; j < msa->nseq; j++)
374 esl_strdup(msa->gr[i][j], -1, &(new_msa->gr[i][j]));
375 }
376 }
377
378 esl_keyhash_Destroy(new_msa->index); new_msa->index = NULL;
379 esl_keyhash_Destroy(new_msa->gs_idx); new_msa->gs_idx = NULL;
380 esl_keyhash_Destroy(new_msa->gc_idx); new_msa->gc_idx = NULL;
381 esl_keyhash_Destroy(new_msa->gr_idx); new_msa->gr_idx = NULL;
382
383 if (msa->index != NULL) new_msa->index = esl_keyhash_Clone(msa->index);
384 if (msa->gs_idx != NULL) new_msa->gs_idx = esl_keyhash_Clone(msa->gs_idx);
385 if (msa->gc_idx != NULL) new_msa->gc_idx = esl_keyhash_Clone(msa->gc_idx);
386 if (msa->gr_idx != NULL) new_msa->gr_idx = esl_keyhash_Clone(msa->gr_idx);
387
388 new_msa->offset = msa->offset;
389 return eslOK;
390
391 ERROR:
392 return status;
393 }
394
395 /* Function: esl_msa_Clone()
396 * Synopsis: Duplicates an MSA.
397 *
398 * Purpose: Make a duplicate of <msa>, in newly
399 * allocated space.
400 *
401 * Returns: a pointer to the newly allocated clone.
402 * Caller is responsible for free'ing it.
403 *
404 * Throws: <NULL> on allocation error.
405 */
406 ESL_MSA *
407 esl_msa_Clone(const ESL_MSA *msa)
408 {
409 ESL_MSA *nw = NULL;
410 int status;
411
412 if (msa->flags & eslMSA_DIGITAL)
413 {
414 if ((nw = esl_msa_CreateDigital(msa->abc, msa->nseq, msa->alen)) == NULL) return NULL;
415 }
416 else
417 if ((nw = esl_msa_Create(msa->nseq, msa->alen)) == NULL) return NULL;
418
419 if ((status = esl_msa_Copy(msa, nw) ) != eslOK) goto ERROR;
420 return nw;
421
422 ERROR:
423 esl_msa_Destroy(nw);
424 return NULL;
425 }
426
427
428 /* Function: esl_msa_Sizeof()
429 * Synopsis: Returns approximate size of an ESL_MSA, in bytes
430 * Incept: SRE, Thu Nov 2 11:17:18 2017
431 *
432 * Purpose: Returns the approximate size of an <ESL_MSA>, in
433 * bytes. Approximate, because it counts used data size
434 * (the size of the alignment) rather than alloced size
435 * (the actual memory required by the structure),
436 * and the structure may be overallocated (e.g. by
437 * <esl_msa_Expand()>.) That is, returns the minimum
438 * size required to store the data.
439 *
440 * (We may want to distinguish between true allocated
441 * size versus minimum size in the future.)
442 */
443 size_t
444 esl_msa_Sizeof(ESL_MSA *msa)
445 {
446 size_t n = 0;
447
448 n += sizeof(ESL_MSA);
449
450 n += esl_arr2_SSizeof(msa->sqname, msa->nseq);
451 n += sizeof(double) * msa->nseq; // wgt
452
453 if (msa->aseq)
454 n += esl_arr2_SSizeof(msa->aseq, msa->nseq);
455 else if (msa->ax)
456 {
457 n += sizeof(ESL_DSQ *) * msa->nseq;
458 n += sizeof(ESL_DSQ) * msa->nseq * (msa->alen + 2);
459 }
460
461 if (msa->name) n += sizeof(char) * (1 + strlen(msa->name));
462 if (msa->desc) n += sizeof(char) * (1 + strlen(msa->desc));
463 if (msa->acc) n += sizeof(char) * (1 + strlen(msa->acc));
464 if (msa->au) n += sizeof(char) * (1 + strlen(msa->au));
465
466 if (msa->ss_cons) n += sizeof(char) * msa->alen;
467 if (msa->sa_cons) n += sizeof(char) * msa->alen;
468 if (msa->pp_cons) n += sizeof(char) * msa->alen;
469 if (msa->rf) n += sizeof(char) * msa->alen;
470 if (msa->mm) n += sizeof(char) * msa->alen;
471
472 n += esl_arr2_SSizeof(msa->sqacc, msa->nseq);
473 n += esl_arr2_SSizeof(msa->sqdesc, msa->nseq);
474 n += esl_arr2_SSizeof(msa->ss, msa->nseq);
475 n += esl_arr2_SSizeof(msa->sa, msa->nseq);
476 n += esl_arr2_SSizeof(msa->pp, msa->nseq);
477
478 n += esl_arr2_SSizeof(msa->comment, msa->ncomment);
479 n += esl_arr2_SSizeof(msa->gf_tag, msa->ngf);
480 n += esl_arr2_SSizeof(msa->gf, msa->ngf);
481 n += esl_arr2_SSizeof(msa->gs_tag, msa->ngs);
482 n += esl_arr3_SSizeof(msa->gs, msa->ngs, msa->nseq);
483 n += esl_arr2_SSizeof(msa->gc_tag, msa->ngc);
484 n += esl_arr2_SSizeof(msa->gc, msa->ngc);
485 n += esl_arr2_SSizeof(msa->gr_tag, msa->ngr);
486 n += esl_arr3_SSizeof(msa->gr, msa->ngr, msa->nseq);
487
488 n += esl_keyhash_Sizeof(msa->index);
489 n += esl_keyhash_Sizeof(msa->gs_idx);
490 n += esl_keyhash_Sizeof(msa->gc_idx);
491 n += esl_keyhash_Sizeof(msa->gr_idx);
492
493 return n;
494 }
495
496
497 /* Function: esl_msa_Destroy()
498 * Synopsis: Frees an <ESL_MSA>.
499 *
500 * Purpose: Destroys <msa>.
501 *
502 * Xref: squid's MSADestroy().
503 */
504 void
505 esl_msa_Destroy(ESL_MSA *msa)
506 {
507 if (msa == NULL) return;
508
509 esl_arr2_Destroy((void **) msa->aseq, msa->nseq);
510 esl_arr2_Destroy((void **) msa->ax, msa->nseq);
511
512 esl_arr2_Destroy((void **) msa->sqname, msa->nseq);
513 esl_arr2_Destroy((void **) msa->sqacc, msa->nseq);
514 esl_arr2_Destroy((void **) msa->sqdesc, msa->nseq);
515 esl_arr2_Destroy((void **) msa->ss, msa->nseq);
516 esl_arr2_Destroy((void **) msa->sa, msa->nseq);
517 esl_arr2_Destroy((void **) msa->pp, msa->nseq);
518
519 if (msa->sqlen != NULL) free(msa->sqlen);
520 if (msa->wgt != NULL) free(msa->wgt);
521
522 if (msa->name != NULL) free(msa->name);
523 if (msa->desc != NULL) free(msa->desc);
524 if (msa->acc != NULL) free(msa->acc);
525 if (msa->au != NULL) free(msa->au);
526 if (msa->ss_cons != NULL) free(msa->ss_cons);
527 if (msa->sa_cons != NULL) free(msa->sa_cons);
528 if (msa->pp_cons != NULL) free(msa->pp_cons);
529 if (msa->rf != NULL) free(msa->rf);
530 if (msa->mm != NULL) free(msa->mm);
531 if (msa->sslen != NULL) free(msa->sslen);
532 if (msa->salen != NULL) free(msa->salen);
533 if (msa->pplen != NULL) free(msa->pplen);
534
535 esl_arr2_Destroy((void **) msa->comment, msa->ncomment);
536 esl_arr2_Destroy((void **) msa->gf_tag, msa->ngf);
537 esl_arr2_Destroy((void **) msa->gf, msa->ngf);
538
539 esl_arr2_Destroy((void **) msa->gs_tag, msa->ngs);
540 esl_arr3_Destroy((void ***)msa->gs, msa->ngs, msa->nseq);
541 esl_arr2_Destroy((void **) msa->gc_tag, msa->ngc);
542 esl_arr2_Destroy((void **) msa->gc, msa->ngc);
543 esl_arr2_Destroy((void **) msa->gr_tag, msa->ngr);
544 esl_arr3_Destroy((void ***)msa->gr, msa->ngr, msa->nseq);
545
546 esl_keyhash_Destroy(msa->index);
547 esl_keyhash_Destroy(msa->gs_idx);
548 esl_keyhash_Destroy(msa->gc_idx);
549 esl_keyhash_Destroy(msa->gr_idx);
550
551 free(msa);
552 return;
553 }
554
555
556 /* msa_create_mostly()
557 *
558 * This is the routine called by esl_msa_Create() and esl_msa_CreateDigital()
559 * that does all allocation except the aseq/ax alignment data.
560 *
561 * <nseq> may be the exact known # of seqs in an alignment; or <nseq>
562 * may be an allocation block size (to be expanded by doubling, in
563 * esl_msa_Expand(), as in:
564 * <if (msa->nseq == msa->sqalloc) esl_msa_Expand(msa);>
565 * <nseq> should not be 0.
566 *
567 * <alen> may be the exact length of an alignment, in columns; or it
568 * may be -1, which states that your parser will take responsibility
569 * for expanding as needed as new input is read into a growing new
570 * alignment.
571 *
572 * A created <msa> can only be <_Expand()>'ed if <alen> is -1.
573 *
574 * Args: <nseq> - number of sequences, or nseq allocation blocksize
575 * <alen> - length of alignment in columns, or -1
576 *
577 * Returns: pointer to new MSA object, w/ all values initialized.
578 * Note that msa->nseq is initialized to 0 here, even though space
579 * is allocated.
580 *
581 * Throws: <NULL> on allocation failure.
582 */
583 static ESL_MSA *
584 msa_create_mostly(int nseq, int64_t alen)
585 {
586 int status;
587 ESL_MSA *msa = NULL;
588 int i;
589
590 ESL_ALLOC(msa, sizeof(ESL_MSA));
591 msa->aseq = NULL;
592 msa->sqname = NULL;
593 msa->wgt = NULL;
594 msa->alen = alen; /* if -1, then we're growable. */
595 msa->nseq = 0; /* our caller (text or digital allocation) sets this. */
596 msa->flags = 0;
597
598 msa->abc = NULL;
599 msa->ax = NULL;
600
601 msa->name = NULL;
602 msa->desc = NULL;
603 msa->acc = NULL;
604 msa->au = NULL;
605 msa->ss_cons = NULL;
606 msa->sa_cons = NULL;
607 msa->pp_cons = NULL;
608 msa->rf = NULL;
609 msa->mm = NULL;
610 msa->sqacc = NULL;
611 msa->sqdesc = NULL;
612 msa->ss = NULL;
613 msa->sa = NULL;
614 msa->pp = NULL;
615 for (i = 0; i < eslMSA_NCUTS; i++) {
616 msa->cutoff[i] = 0.;
617 msa->cutset[i] = FALSE;
618 }
619 msa->sqalloc = nseq;
620 msa->sqlen = NULL;
621 msa->sslen = NULL;
622 msa->salen = NULL;
623 msa->pplen = NULL;
624 msa->lastidx = 0;
625
626 /* Unparsed markup, including comments and Stockholm tags.
627 */
628 msa->comment = NULL;
629 msa->ncomment = 0;
630 msa->alloc_ncomment = 0;
631
632 msa->gf_tag = NULL;
633 msa->gf = NULL;
634 msa->ngf = 0;
635 msa->alloc_ngf = 0;
636
637 msa->gs_tag = NULL;
638 msa->gs = NULL;
639 msa->ngs = 0;
640
641 msa->gc_tag = NULL;
642 msa->gc = NULL;
643 msa->ngc = 0;
644
645 msa->gr_tag = NULL;
646 msa->gr = NULL;
647 msa->ngr = 0;
648
649 msa->index = esl_keyhash_Create();
650 msa->gs_idx = NULL;
651 msa->gc_idx = NULL;
652 msa->gr_idx = NULL;
653
654 msa->offset = 0;
655
656 /* Allocation, round 2.
657 */
658 if(nseq > 0) {
659 ESL_ALLOC(msa->sqname, sizeof(char *) * nseq);
660 ESL_ALLOC(msa->wgt, sizeof(double) * nseq);
661 ESL_ALLOC(msa->sqlen, sizeof(int64_t)* nseq);
662 }
663 /* Initialize at the second level.
664 */
665 for (i = 0; i < nseq; i++)
666 {
667 msa->sqname[i] = NULL;
668 msa->sqlen[i] = 0;
669 msa->wgt[i] = -1.0; /* "unset so far" */
670 }
671
672 return msa;
673
674 ERROR:
675 esl_msa_Destroy(msa);
676 return NULL;
677 }
678 /*------------------- end, ESL_MSA object -----------------------*/
679
680
681
682 /*****************************************************************
683 *# 2. Digital mode MSA's
684 *****************************************************************/
685
686 /* Function: esl_msa_GuessAlphabet()
687 * Synopsis: Guess alphabet of MSA.
688 *
689 * Purpose: Guess whether the sequences in the <msa> are
690 * <eslDNA>, <eslRNA>, or <eslAMINO>, and return
691 * that guess in <*ret_type>.
692 *
693 * The determination is made based on the classifications
694 * of the individual sequences in the alignment. At least
695 * one sequence must contain ten residues or more to be
696 * classified. If one or more sequences is called
697 * <eslAMINO> and one or more is called <eslDNA>/<eslRNA>,
698 * the alignment's alphabet is considered to be
699 * indeterminate (<eslUNKNOWN>). If some sequences are
700 * <eslDNA> and some are <eslRNA>, the alignment is called
701 * <eslDNA>; this should cause no problems, because Easel
702 * reads U as a synonym for T in DNA sequence anyway.
703 *
704 * Tested on Pfam 21.0 and Rfam 7.0, this routine correctly
705 * classified all 8957 Pfam alignments as protein, and 503
706 * Rfam alignments as RNA (both seed and full alignments).
707 *
708 * Returns: <eslOK> on success, and <*ret_type> is set
709 * to <eslDNA>, <eslRNA>, or <eslAMINO>.
710 *
711 * Returns <eslENOALPHABET> and sets <*ret_type> to
712 * <eslUNKNOWN> if the alphabet cannot be reliably guessed.
713 *
714 * Xref: J1/62
715 */
716 int
717 esl_msa_GuessAlphabet(const ESL_MSA *msa, int *ret_type)
718 {
719 int64_t namino = 0,
720 ndna = 0,
721 nrna = 0;
722 int type;
723 int i,x;
724 int64_t j,n;
725 int64_t ct[26];
726
727 if (msa->flags & eslMSA_DIGITAL) { *ret_type = msa->abc->type; return eslOK; }
728
729 *ret_type = eslUNKNOWN;
730
731 /* On wide alignments, we're better off looking at individual sequence
732 * classifications. We don't want to end up calling the whole alignment
733 * indeterminate just because a few sequences have degenerate residue
734 * codes.
735 */
736 for (i = 0; i < msa->nseq; i++)
737 {
738 for (x = 0; x < 26; x++) ct[x] = 0;
739 for (n = 0, j = 0; j < msa->alen; j++) {
740 x = toupper(msa->aseq[i][j]) - 'A';
741 if (x < 0 || x > 25) continue;
742 ct[x]++;
743 n++;
744 if (n > 10000) break; /* ought to know by now */
745 }
746 esl_abc_GuessAlphabet(ct, &type);
747
748 switch (type) {
749 case eslAMINO: namino++; break;
750 case eslDNA: ndna++; break;
751 case eslRNA: nrna++; break;
752 case eslUNKNOWN: break;
753 default: break;
754 }
755 }
756 if (namino > 0 && (ndna+nrna) == 0) *ret_type = eslAMINO;
757 else if (ndna > 0 && (nrna+namino) == 0) *ret_type = eslDNA;
758 else if (nrna > 0 && (ndna+namino) == 0) *ret_type = eslRNA;
759 else if (ndna+nrna > 0 && namino == 0) *ret_type = eslDNA;
760
761 /* On narrow alignments, no single sequence may be long enough to
762 * be classified, but we can determine alphabet from composition
763 * of the complete alignment. Of course, degenerate residue codes in
764 * a DNA alignment will still screw us.
765 */
766 if (*ret_type == eslUNKNOWN)
767 {
768
769 n = 0;
770 for (x = 0; x < 26; x++) ct[x] = 0;
771 for (i = 0; i < msa->nseq; i++) {
772 for (j = 0; j < msa->alen; j++) {
773 x = toupper(msa->aseq[i][j]) - 'A';
774 if (x < 0 || x > 26) continue;
775 ct[x]++;
776 n++;
777 if (n > 10000) break; /* ought to know by now */
778 }
779 if (n > 10000) break;
780 }
781 esl_abc_GuessAlphabet(ct, ret_type);
782 }
783
784 if (*ret_type == eslUNKNOWN) return eslENOALPHABET;
785 else return eslOK;
786 }
787
788
789 /* Function: esl_msa_CreateDigital()
790 * Synopsis: Create a digital <ESL_MSA>.
791 *
792 * Purpose: Same as <esl_msa_Create()>, except the returned MSA is configured
793 * for a digital alignment using internal alphabet <abc>, instead of
794 * a text alignment.
795 *
796 * Internally, this means the <ax> field is allocated instead of
797 * the <aseq> field, and the <eslMSA_DIGITAL> flag is raised.
798 *
799 * Args: <nseq> - number of sequences, or nseq allocation blocksize
800 * <alen> - length of alignment in columns, or -1
801 *
802 * Returns: pointer to new MSA object, w/ all values initialized.
803 * Note that <msa->nseq> is initialized to 0, even though space
804 * is allocated.
805 *
806 * Throws: NULL on allocation failure.
807 *
808 * Xref: squid's MSAAlloc()
809 */
810 ESL_MSA *
811 esl_msa_CreateDigital(const ESL_ALPHABET *abc, int nseq, int64_t alen)
812 {
813 int status;
814 ESL_MSA *msa;
815 int i;
816
817 msa = msa_create_mostly(nseq, alen); /* aseq is null upon successful return */
818 if (msa == NULL) return NULL; /* already threw error in mostly_create, so percolate */
819
820 ESL_ALLOC(msa->ax, sizeof(ESL_DSQ *) * msa->sqalloc);
821 for (i = 0; i < msa->sqalloc; i++)
822 msa->ax[i] = NULL;
823
824 if (alen != -1)
825 {
826 for (i = 0; i < nseq; i++) {
827 ESL_ALLOC(msa->ax[i], sizeof(ESL_DSQ) * (alen+2));
828 msa->ax[i][0] = msa->ax[i][alen+1] = eslDSQ_SENTINEL; /* help the poor */
829 }
830 msa->nseq = nseq;
831 }
832
833 msa->abc = (ESL_ALPHABET *) abc; /* this cast away from const-ness is deliberate & safe. */
834 msa->flags |= eslMSA_DIGITAL;
835 return msa;
836
837 ERROR:
838 esl_msa_Destroy(msa);
839 return NULL;
840 }
841
842 /* Function: esl_msa_Digitize()
843 * Synopsis: Digitizes an msa, converting it from text mode.
844 *
845 * Purpose: Given an alignment <msa> in text mode, convert it to
846 * digital mode, using alphabet <abc>.
847 *
848 * Internally, the <ax> digital alignment field is filled,
849 * the <aseq> text alignment field is destroyed and free'd,
850 * a copy of the alphabet pointer is kept in the msa's
851 * <abc> reference, and the <eslMSA_DIGITAL> flag is raised
852 * in <flags>.
853 *
854 * Because <esl_msa_Digitize()> may be called on
855 * unvalidated user data, <errbuf> may be passed, for
856 * capturing an informative error message. For example, in
857 * reading alignments from files, invalid characters in the
858 * alignment are caught at the digitization step.
859 *
860 * Args: abc - digital alphabet
861 * msa - multiple alignment to digitize
862 * errbuf - optional: error message buffer, or <NULL>
863 *
864 * Returns: <eslOK> on success;
865 * <eslEINVAL> if one or more sequences contain invalid characters
866 * that can't be digitized. If this happens, the <msa> is returned
867 * unaltered - left in text mode, with <aseq> as it was. (This is
868 * a normal error, because <msa->aseq> may be user input that we
869 * haven't validated yet.)
870 *
871 * Throws: <eslEMEM> on allocation failure; in this case, state of <msa> may be
872 * wedged, and it should only be destroyed, not used.
873 */
874 int
875 esl_msa_Digitize(const ESL_ALPHABET *abc, ESL_MSA *msa, char *errbuf)
876 {
877 char errbuf2[eslERRBUFSIZE];
878 int i;
879 int status;
880
881 /* Contract checks */
882 if (msa->aseq == NULL) ESL_EXCEPTION(eslEINVAL, "msa has no text alignment");
883 if (msa->ax != NULL) ESL_EXCEPTION(eslEINVAL, "msa already has digital alignment");
884 if (msa->flags & eslMSA_DIGITAL) ESL_EXCEPTION(eslEINVAL, "msa is flagged as digital");
885
886 /* Validate before we convert. Then we can leave the <aseq> untouched if
887 * any of the sequences contain invalid characters.
888 */
889 for (i = 0; i < msa->nseq; i++)
890 if (esl_abc_ValidateSeq(abc, msa->aseq[i], msa->alen, errbuf2) != eslOK)
891 ESL_FAIL(eslEINVAL, errbuf, "%s: %s", msa->sqname[i], errbuf2);
892
893 /* Convert, sequence-by-sequence, free'ing aseq as we go. */
894 ESL_ALLOC(msa->ax, msa->sqalloc * sizeof(ESL_DSQ *));
895 for (i = 0; i < msa->nseq; i++)
896 {
897 ESL_ALLOC(msa->ax[i], (msa->alen+2) * sizeof(ESL_DSQ));
898 status = esl_abc_Digitize(abc, msa->aseq[i], msa->ax[i]);
899 if (status != eslOK) goto ERROR;
900 free(msa->aseq[i]);
901 }
902 for (; i < msa->sqalloc; i++)
903 msa->ax[i] = NULL;
904 free(msa->aseq);
905 msa->aseq = NULL;
906
907 msa->abc = (ESL_ALPHABET *) abc; /* convince compiler that removing const-ness is safe */
908 msa->flags |= eslMSA_DIGITAL;
909 return eslOK;
910
911 ERROR:
912 return status;
913 }
914
915 /* Function: esl_msa_Textize()
916 * Synopsis: Convert a digital msa to text mode.
917 *
918 * Purpose: Given an alignment <msa> in digital mode, convert it
919 * to text mode.
920 *
921 * Internally, the <aseq> text alignment field is filled, the
922 * <ax> digital alignment field is destroyed and free'd, the
923 * msa's <abc> digital alphabet reference is nullified, and
924 * the <eslMSA_DIGITAL> flag is dropped in <flags>.
925 *
926 * Args: msa - multiple alignment to convert to text
927 *
928 * Returns: <eslOK> on success.
929 *
930 * Throws: <eslEMEM> on allocation failure.
931 * <eslECORRUPT> if one or more of the digitized alignment strings
932 * contain invalid characters.
933 */
934 int
935 esl_msa_Textize(ESL_MSA *msa)
936 {
937 int status;
938 int i;
939
940 /* Contract checks
941 */
942 if (msa->ax == NULL) ESL_EXCEPTION(eslEINVAL, "msa has no digital alignment");
943 if (msa->aseq != NULL) ESL_EXCEPTION(eslEINVAL, "msa already has text alignment");
944 if (! (msa->flags & eslMSA_DIGITAL)) ESL_EXCEPTION(eslEINVAL, "msa is not flagged as digital");
945 if (msa->abc == NULL) ESL_EXCEPTION(eslEINVAL, "msa has no digital alphabet");
946
947 /* Convert, sequence-by-sequence, free'ing ax as we go.
948 */
949 ESL_ALLOC(msa->aseq, msa->sqalloc * sizeof(char *));
950 for (i = 0; i < msa->nseq; i++)
951 {
952 ESL_ALLOC(msa->aseq[i], (msa->alen+1) * sizeof(char));
953 status = esl_abc_Textize(msa->abc, msa->ax[i], msa->alen, msa->aseq[i]);
954 if (status != eslOK) goto ERROR;
955 free(msa->ax[i]);
956 }
957 for (; i < msa->sqalloc; i++)
958 msa->aseq[i] = NULL;
959 free(msa->ax);
960 msa->ax = NULL;
961
962 msa->abc = NULL; /* nullify reference (caller still owns real abc) */
963 msa->flags &= ~eslMSA_DIGITAL; /* drop the flag */
964 return eslOK;
965
966 ERROR:
967 return status;
968 }
969
970 /* Function: esl_msa_ConvertDegen2X()
971 * Synopsis: Convert all degenerate residues to X/N
972 *
973 * Purpose: Convert all the degenerate residue codes in digital
974 * MSA <msa> to the code for "unknown residue" (maximum
975 * degeneracy); for example, X for protein, N for
976 * nucleic acid.
977 *
978 * This is handy when you need to be compatible with
979 * software that can't deal with unusual residue codes.
980 * For example, WU-BLAST can't deal with O (pyrrolysine)
981 * codes.
982 *
983 * Returns: <eslOK> on success.
984 *
985 * Throws: <eslEINVAL> if <msa> isn't in digital mode.
986 * (We only know how to interpret the alphabet in digital
987 * mode. In text mode, letters are just letters.)
988 */
989 int
990 esl_msa_ConvertDegen2X(ESL_MSA *msa)
991 {
992 int i;
993 int status;
994
995 if (! (msa->flags & eslMSA_DIGITAL)) ESL_EXCEPTION(eslEINVAL, "esl_msa_ConvertDegen2X only works on digital sequences");
996
997 for (i = 0; i < msa->nseq; i++)
998 if ((status = esl_abc_ConvertDegen2X(msa->abc, msa->ax[i])) != eslOK) return status;
999
1000 return eslOK;
1001 }
1002
1003 /*---------------------- end of digital MSA functions -----------------------*/
1004
1005
1006
1007 /*****************************************************************
1008 *# 3. Setting, checking data fields in an ESL_MSA
1009 *****************************************************************/
1010
1011 /* These get used by parsers, which might be using an ESL_BUFFER.
1012 * They need to handle either NUL-terminated strings or memory lines.
1013 */
1014
1015 /* Function: esl_msa_SetName()
1016 * Synopsis: Set name of an MSA.
1017 *
1018 * Purpose: Sets the name of the msa <msa> to string <s>,
1019 * of length <n>.
1020 *
1021 * If <s> is a NUL-terminated string, <n> is optional; if
1022 * the length is unknown, pass <n=-1>. <s> may also be a
1023 * memory line, non-NUL terminated, in which case <n> is
1024 * required.
1025 *
1026 * <s> can also be <NULL> because the MSA name is an
1027 * optional field. (In this case, <n> is irrelevant and
1028 * ignored.)
1029 *
1030 * Returns: <eslOK> on success.
1031 *
1032 * Throws: <eslEMEM> on allocation error.
1033 */
1034 int
1035 esl_msa_SetName(ESL_MSA *msa, const char *s, esl_pos_t n)
1036 {
1037 if (msa->name) free(msa->name);
1038 if (n >= 0) return esl_memstrdup(s, n, &(msa->name));
1039 else return esl_strdup( s, -1, &(msa->name));
1040 }
1041
1042
1043 /* Function: esl_msa_SetDesc()
1044 * Synopsis: Set the description line of an MSA.
1045 *
1046 * Purpose: Sets the optional description line of the msa <msa> to
1047 * string <s> of length <n>.
1048 *
1049 * If <s> is a NUL-terminated string, <n> is optional; if
1050 * the length is unknown, pass <n=-1>. <s> may also be a
1051 * memory line, non-NUL terminated, in which case <n> is
1052 * required.
1053 *
1054 * <s> can also be <NULL> because the MSA description is an
1055 * optional field. (In this case, <n> is irrelevant and
1056 * ignored.)
1057 *
1058 * Returns: <eslOK> on success.
1059 *
1060 * Throws: <eslEMEM> on allocation error.
1061 */
1062 int
1063 esl_msa_SetDesc(ESL_MSA *msa, const char *s, esl_pos_t n)
1064 {
1065 if (msa->desc) free(msa->desc);
1066 if (n >= 0) return esl_memstrdup(s, n, &(msa->desc));
1067 else return esl_strdup( s, -1, &(msa->desc));
1068 }
1069
1070 /* Function: esl_msa_SetAccession()
1071 * Synopsis: Set the accession field of an MSA.
1072 *
1073 * Purpose: Sets accession field of the msa <msa> to string <s> of
1074 * length <n>.
1075 *
1076 * If <s> is a NUL-terminated string, <n> is optional; if
1077 * the length is unknown, pass <n=-1>. <s> may also be a
1078 * memory line, non-NUL terminated, in which case <n> is
1079 * required.
1080 *
1081 * <s> can also be <NULL> because the MSA accession is an
1082 * optional field. (In this case, <n> is irrelevant and
1083 * ignored.)
1084 *
1085 * Returns: <eslOK> on success.
1086 *
1087 * Throws: <eslEMEM> on allocation error.
1088 */
1089 int
1090 esl_msa_SetAccession(ESL_MSA *msa, const char *s, esl_pos_t n)
1091 {
1092 if (msa->acc) free(msa->acc);
1093 if (n >= 0) return esl_memstrdup(s, n, &(msa->acc));
1094 else return esl_strdup( s, -1, &(msa->acc));
1095 }
1096
1097
1098 /* Function: esl_msa_SetAuthor()
1099 * Synopsis: Set the author string in an MSA.
1100 *
1101 * Purpose: Sets the author string in <msa> to string <s> of
1102 * length <n>.
1103 *
1104 * If <s> is a NUL-terminated string, <n> is optional; if
1105 * the length is unknown, pass <n=-1>. <s> may also be a
1106 * memory line, non-NUL terminated, in which case <n> is
1107 * required.
1108 *
1109 * <s> can also be <NULL> because the MSA author is an
1110 * optional field. (In this case, <n> is irrelevant and
1111 * ignored.)
1112 *
1113 * Returns: <eslOK> on success.
1114 *
1115 * Throws: <eslEMEM> on allocation error.
1116 */
1117 int
1118 esl_msa_SetAuthor(ESL_MSA *msa, const char *s, esl_pos_t n)
1119 {
1120 if (msa->au) free(msa->au);
1121 if (n >= 0) return esl_memstrdup(s, n, &(msa->au));
1122 else return esl_strdup( s, -1, &(msa->au));
1123 }
1124
1125
1126 /* Function: esl_msa_SetSeqName()
1127 * Synopsis: Set an individual sequence name in an MSA.
1128 *
1129 * Purpose: Set the name of sequence number <idx> in <msa>
1130 * to string <s> of length <n>.
1131 *
1132 * If <s> is a NUL-terminated string, <n> is optional; if
1133 * the length is unknown, pass <n=-1>. <s> may also be a
1134 * memory line, non-NUL terminated, in which case <n> is
1135 * required.
1136 *
1137 * Returns: <eslOK> on success.
1138 *
1139 * Throws: <eslEMEM> on allocation error.
1140 * <eslEINCONCEIVABLE> on coding errors.
1141 *
1142 * Note: msa->sqname[] is not optional, so we may
1143 * rely on it already being allocated for
1144 * i=0..sqalloc-1.
1145 */
1146 int
1147 esl_msa_SetSeqName(ESL_MSA *msa, int idx, const char *s, esl_pos_t n)
1148 {
1149 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINCONCEIVABLE, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1150 if (s == NULL) ESL_EXCEPTION(eslEINCONCEIVABLE, "seq names are mandatory; NULL is not a valid name");
1151
1152 if (msa->sqname[idx]) free(msa->sqname[idx]);
1153 if (n >= 0) return esl_memstrdup(s, n, &(msa->sqname[idx]));
1154 else return esl_strdup( s, -1, &(msa->sqname[idx]));
1155 }
1156
1157 /* Function: esl_msa_SetSeqAccession()
1158 * Synopsis: Sets individual sequence accession in an MSA.
1159 *
1160 * Purpose: Set the accession of sequence number <idx> in <msa> to
1161 * string <s> of length <n>.
1162 *
1163 * If <s> is a NUL-terminated string, <n> is optional; if
1164 * the length is unknown, pass <n=-1>. <s> may also be a
1165 * memory line, non-NUL terminated, in which case <n> is
1166 * required.
1167 *
1168 * <s> can also be <NULL> because a seq accession is an
1169 * optional field. (In this case, <n> is irrelevant and
1170 * ignored.)
1171 *
1172 * Returns: <eslOK> on success.
1173 *
1174 * Throws: <eslEMEM> on allocation error.
1175 * <eslEINCONCEIVABLE> on coding errors.
1176 */
1177 int
1178 esl_msa_SetSeqAccession(ESL_MSA *msa, int idx, const char *s, esl_pos_t n)
1179 {
1180 int i;
1181 int status;
1182
1183 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINCONCEIVABLE, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1184
1185 if (msa->sqacc && msa->sqacc[idx]) { free(msa->sqacc[idx]); msa->sqacc[idx] = NULL; }
1186
1187 /* erasure case */
1188 if (! s && msa->sqacc) {
1189 for (i = 0; i < msa->sqalloc; i++) if (msa->sqacc[i]) break;
1190 if (i == msa->sqalloc) { free(msa->sqacc); msa->sqacc = NULL; }
1191 return eslOK;
1192 }
1193
1194 /* Allocate/initialize the optional sqacc array, if it's not already done: */
1195 if (! msa->sqacc) {
1196 ESL_ALLOC(msa->sqacc, sizeof(char *) * msa->sqalloc);
1197 for (i = 0; i < msa->sqalloc; i++) msa->sqacc[i] = NULL;
1198 }
1199
1200 if (n >= 0) status = esl_memstrdup(s, n, &(msa->sqacc[idx]));
1201 else status = esl_strdup( s, -1, &(msa->sqacc[idx]));
1202
1203 return status;
1204
1205 ERROR:
1206 return status;
1207 }
1208
1209 /* Function: esl_msa_SetSeqDescription()
1210 * Synopsis: Sets individual sequence description in an MSA.
1211 *
1212 * Purpose: Set the description of sequence number <idx> in <msa> to
1213 * string <s> of length <n>.
1214 *
1215 * If <s> is a NUL-terminated string, <n> is optional; if
1216 * the length is unknown, pass <n=-1>. <s> may also be a
1217 * memory line, non-NUL terminated, in which case <n> is
1218 * required.
1219 *
1220 * <s> can also be <NULL> because a seq accession is an
1221 * optional field. (In this case, <n> is irrelevant and
1222 * ignored.)
1223 *
1224 * Returns: <eslOK> on success.
1225 *
1226 * Throws: <eslEMEM> on allocation error.
1227 * <eslEINCONCEIVABLE> on coding error
1228 */
1229 int
1230 esl_msa_SetSeqDescription(ESL_MSA *msa, int idx, const char *s, esl_pos_t n)
1231 {
1232 int i;
1233 int status;
1234
1235 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINCONCEIVABLE, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1236
1237 if (msa->sqdesc && msa->sqdesc[idx]) { free(msa->sqdesc[idx]); msa->sqdesc[idx] = NULL; }
1238
1239 /* erasure case. If we just freed the only description, free the entire optional <sqdesc> array */
1240 if (! s && msa->sqdesc) {
1241 for (i = 0; i < msa->sqalloc; i++) if (msa->sqdesc[i]) break;
1242 if (i == msa->sqalloc) { free(msa->sqdesc); msa->sqdesc = NULL; }
1243 return eslOK;
1244 }
1245
1246 /* Allocate/initialize the optional sqdesc array, if it's not already done: */
1247 if (msa->sqdesc == NULL) {
1248 ESL_ALLOC(msa->sqdesc, sizeof(char *) * msa->sqalloc);
1249 for (i = 0; i < msa->sqalloc; i++) msa->sqdesc[i] = NULL;
1250 }
1251
1252 if (n >= 0) status = esl_memstrdup(s, n, &(msa->sqdesc[idx]));
1253 else status = esl_strdup( s, -1, &(msa->sqdesc[idx]));
1254
1255 ERROR:
1256 return status;
1257 }
1258
1259
1260
1261 /* Function: esl_msa_SetDefaultWeights()
1262 * Synopsis: Set all sequence weights to default 1.0.
1263 *
1264 * Purpose: Set all the sequence weights in <msa> to default,
1265 * 1.0. Drop the <eslMSA_HASWGTS> flag in <msa->flags>.
1266 *
1267 * The <ESL_MSA> data structure has its <wgt> values
1268 * initialized to -1.0, by create and expand functions, as
1269 * a special value for "unset yet". File format parsers use
1270 * this to tell when a weight is mistakenly set twice, or
1271 * not at all. However, when an <msa> is used, you're
1272 * allowed to assume that <wgt> is valid even if the
1273 * <eslMSA_HASWGTS> flag is down. So all creators of new
1274 * MSAs (file format parsers, for example) must assure that
1275 * <msa->wgt> is set correctly, even if the file format
1276 * doesn't include weights. This function gives parsers
1277 * (and other MSA creators) a quick way to do this.
1278 */
1279 int
1280 esl_msa_SetDefaultWeights(ESL_MSA *msa)
1281 {
1282 int idx;
1283
1284 for (idx = 0; idx < msa->nseq; idx++)
1285 msa->wgt[idx] = 1.0;
1286 msa->flags &= ~eslMSA_HASWGTS;
1287 return eslOK;
1288 }
1289
1290
1291 /* Function: esl_msa_FormatName()
1292 * Synopsis: Format name of an MSA, printf()-style.
1293 *
1294 * Purpose: Sets the name of the msa <msa> using <name>, where
1295 * <name> is a <printf()>-style format with
1296 * arguments; for example, <esl_msa_FormatName(msa, "random%d", i)>.
1297 *
1298 * <name> can be <NULL>, because the MSA name is an
1299 * optional field; in which case any existing name in
1300 * the <msa> is erased.
1301 *
1302 * Returns: <eslOK> on success.
1303 *
1304 * Throws: <eslEMEM> on allocation error;
1305 * <eslESYS> if a <*printf()> library call fails.
1306 */
1307 int
1308 esl_msa_FormatName(ESL_MSA *msa, const char *name, ...)
1309 {
1310 va_list ap;
1311 int status;
1312
1313 if (msa->name != NULL) free(msa->name);
1314 if (name == NULL) { msa->name = NULL; return eslOK; }
1315
1316 va_start(ap, name);
1317 status = esl_vsprintf(&(msa->name), name, &ap);
1318 va_end(ap);
1319 return status;
1320 }
1321
1322
1323 /* Function: esl_msa_FormatDesc()
1324 * Synopsis: Format the description line of an MSA, printf()-style.
1325 *
1326 * Purpose: Format the description line of the msa <msa> using <desc>.
1327 * where <desc> is a <printf()>-style format with
1328 * arguments.
1329 * For example, <esl_msa_FormatDesc(msa, "sample %d", i)>.
1330 *
1331 * As a special case, <desc> may be <NULL>, to facilitate
1332 * handling of optional annotation.
1333 *
1334 * Returns: <eslOK> on success.
1335 *
1336 * Throws: <eslEMEM> on allocation error;
1337 * <eslESYS> if a <*printf()> library call fails.
1338 */
1339 int
1340 esl_msa_FormatDesc(ESL_MSA *msa, const char *desc, ...)
1341 {
1342 va_list ap;
1343 int status;
1344
1345 if (msa->desc != NULL) free(msa->desc);
1346 va_start(ap, desc);
1347 status = esl_vsprintf(&(msa->desc), desc, &ap);
1348 va_end(ap);
1349 return status;
1350
1351 }
1352
1353 /* Function: esl_msa_FormatAccession()
1354 * Synopsis: Format the accession number of an MSA, printf()-style.
1355 *
1356 * Purpose: Sets accession number of the msa <msa> using <acc>,
1357 * where <acc> is a <printf()>-style format with arguments.
1358 * For example, <esl_msa_FormatAccession(msa, "PF%06d", i)>.
1359 *
1360 * As a special case, <acc> may be <NULL>, to facilitate
1361 * handling of optional annotation.
1362 *
1363 * Returns: <eslOK> on success.
1364 *
1365 * Throws: <eslEMEM> on allocation error;
1366 * <eslESYS> if a <*printf()> library call fails.
1367 */
1368 int
1369 esl_msa_FormatAccession(ESL_MSA *msa, const char *acc, ...)
1370 {
1371 va_list ap;
1372 int status;
1373
1374 if (msa->acc != NULL) free(msa->acc);
1375 va_start(ap, acc);
1376 status = esl_vsprintf(&(msa->acc), acc, &ap);
1377 va_end(ap);
1378 return status;
1379 }
1380
1381
1382 /* Function: esl_msa_FormatAuthor()
1383 * Synopsis: Format the author string in an MSA, printf()-style.
1384 *
1385 * Purpose: Sets the author string in <msa>, using an <author> string
1386 * and arguments in same format as <printf()> would take.
1387 *
1388 * As a special case, <author> may be <NULL>, to facilitate
1389 * handling of optional annotation.
1390 *
1391 * Returns: <eslOK> on success.
1392 *
1393 * Throws: <eslEMEM> on allocation error;
1394 * <eslESYS> if a <*printf()> library call fails.
1395 */
1396 int
1397 esl_msa_FormatAuthor(ESL_MSA *msa, const char *author, ...)
1398 {
1399 va_list ap;
1400 int status;
1401
1402 if (msa->au != NULL) free(msa->au);
1403 va_start(ap, author);
1404 status = esl_vsprintf(&(msa->au), author, &ap);
1405 va_end(ap);
1406 return status;
1407 }
1408
1409
1410 /* Function: esl_msa_FormatSeqName()
1411 * Synopsis: Formats an individual sequence name in an MSA, printf()-style.
1412 *
1413 * Purpose: Set the name of sequence number <idx> in <msa>
1414 * to <name>, where <name> is a <printf()>
1415 * style format and arguments.
1416 *
1417 * Returns: <eslOK> on success.
1418 *
1419 * Throws: <eslEINVAL> if <name> is <NULL>;
1420 * <eslEMEM> on allocation error;
1421 * <eslESYS> if a <*printf()> library call fails.
1422 *
1423 * Note: msa->sqname[] is not optional, so we may
1424 * rely on it already being allocated for
1425 * i=0..sqalloc-1.
1426 */
1427 int
1428 esl_msa_FormatSeqName(ESL_MSA *msa, int idx, const char *name, ...)
1429 {
1430 va_list ap;
1431 int status;
1432
1433 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINVAL, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1434 if (name == NULL) ESL_EXCEPTION(eslEINVAL, "seq names are mandatory; NULL is not a valid name");
1435
1436 if (msa->sqname[idx] != NULL) free(msa->sqname[idx]);
1437
1438 va_start(ap, name);
1439 status = esl_vsprintf(&(msa->sqname[idx]), name, &ap);
1440 va_end(ap);
1441 return status;
1442 }
1443
1444 /* Function: esl_msa_FormatSeqAccession()
1445 * Synopsis: Format individual sequence accession in an MSA, printf()-style.
1446 *
1447 * Purpose: Set the accession of sequence number <idx> in <msa> to
1448 * <acc>, where <acc> is a <printf()> style format and
1449 * arguments.
1450 *
1451 * Returns: <eslOK> on success.
1452 *
1453 * Throws: <eslEMEM> on allocation error;
1454 * <eslESYS> if a <*printf()> library call fails.
1455 */
1456 int
1457 esl_msa_FormatSeqAccession(ESL_MSA *msa, int idx, const char *acc, ...)
1458 {
1459 va_list ap;
1460 int i;
1461 int status;
1462
1463 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINVAL, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1464 if (acc == NULL) {
1465 if (msa->sqacc != NULL) { free(msa->sqacc[idx]); msa->sqacc[idx] = NULL; }
1466 return eslOK;
1467 }
1468
1469 /* Allocate/initialize the optional sqacc array, if it's not already done: */
1470 if (msa->sqacc == NULL) {
1471 ESL_ALLOC(msa->sqacc, sizeof(char *) * msa->sqalloc);
1472 for (i = 0; i < msa->sqalloc; i++) msa->sqacc[i] = NULL;
1473 }
1474 if (msa->sqacc[idx] != NULL) free(msa->sqacc[idx]);
1475
1476 va_start(ap, acc);
1477 status = esl_vsprintf(&(msa->sqacc[idx]), acc, &ap);
1478 va_end(ap);
1479 return status;
1480
1481 ERROR:
1482 return status;
1483 }
1484
1485 /* Function: esl_msa_FormatSeqDescription()
1486 * Synopsis: Formats individual sequence description in an MSA, printf()-style.
1487 *
1488 * Purpose: Set the description of sequence number <idx> in <msa> to
1489 * <desc>, where <desc> may be a <printf()> style format and
1490 * arguments.
1491 *
1492 * Returns: <eslOK> on success.
1493 *
1494 * Throws: <eslEMEM> on allocation error;
1495 * <eslESYS> if a <*printf()> library call fails.
1496 */
1497 int
1498 esl_msa_FormatSeqDescription(ESL_MSA *msa, int idx, const char *desc, ...)
1499 {
1500 va_list ap;
1501 int i;
1502 int status;
1503
1504 if (idx >= msa->sqalloc) ESL_EXCEPTION(eslEINVAL, "no such sequence %d (only %d allocated)", idx, msa->sqalloc);
1505 if (desc == NULL) {
1506 if (msa->sqdesc != NULL) { free(msa->sqdesc[idx]); msa->sqdesc[idx] = NULL; }
1507 return eslOK;
1508 }
1509
1510 /* Allocate/initialize the optional sqdesc array, if it's not already done: */
1511 if (msa->sqdesc == NULL) {
1512 ESL_ALLOC(msa->sqdesc, sizeof(char *) * msa->sqalloc);
1513 for (i = 0; i < msa->sqalloc; i++) msa->sqdesc[i] = NULL;
1514 }
1515 if (msa->sqdesc[idx] != NULL) free(msa->sqdesc[idx]);
1516
1517 va_start(ap, desc);
1518 status = esl_vsprintf(&(msa->sqdesc[idx]), desc, &ap);
1519 va_end(ap);
1520 return status;
1521
1522 ERROR:
1523 return status;
1524 }
1525
1526 /* Function: esl_msa_AddComment()
1527 * Synopsis: Add an unparsed command to an <ESL_MSA>
1528 *
1529 * Purpose: Add an (unparsed) comment line to the MSA structure,
1530 * allocating as necessary.
1531 *
1532 * Args: msa - a multiple alignment
1533 * p - comment line to add
1534 * n - length of <p>, or -1 if <p> is a NUL-terminated string and length is unknown.
1535 *
1536 * Returns: <eslOK> on success.
1537 *
1538 * Throws: <eslEMEM> on allocation failure.
1539 */
1540 int
1541 esl_msa_AddComment(ESL_MSA *msa, char *p, esl_pos_t n)
1542 {
1543 int status;
1544
1545 if (n == -1) n = strlen(p);
1546
1547 /* If this is our first recorded comment, we need to allocate;
1548 * and if we've filled available space, we need to reallocate.
1549 */
1550 if (msa->comment == NULL) {
1551 ESL_ALLOC(msa->comment, sizeof(char *) * 16);
1552 msa->alloc_ncomment = 16;
1553 }
1554 if (msa->ncomment == msa->alloc_ncomment) {
1555 ESL_REALLOC(msa->comment, sizeof(char *) * msa->alloc_ncomment * 2);
1556 msa->alloc_ncomment *= 2;
1557 }
1558 if ((status = esl_memstrdup(p, n, &(msa->comment[msa->ncomment]))) != eslOK) goto ERROR;
1559 msa->ncomment++;
1560 return eslOK;
1561
1562 ERROR:
1563 return status;
1564 }
1565
1566
1567 /* Function: esl_msa_AddGF()
1568 * Synopsis: Add an unparsed #=GF markup line to an <ESL_MSA>
1569 *
1570 * Purpose: Add an unparsed \verb+#=GF+ markup line to the MSA,
1571 * allocating as necessary. <tag> is the GF markup
1572 * tag; <value> is the text associated w/ that tag.
1573 *
1574 * Args: msa - a multiple alignment
1575 * tag - markup tag
1576 * taglen - length of <tag>; or -1 if <tag> is a string of unknown length
1577 * value - markup text
1578 * vlen - length of <value>; or -1 if <value> is a string of unknown length
1579 *
1580 * Returns: <eslOK> on success.
1581 *
1582 * Throws: <eslEMEM> on allocation failure.
1583 */
1584 int
1585 esl_msa_AddGF(ESL_MSA *msa, char *tag, esl_pos_t taglen, char *value, esl_pos_t vlen)
1586 {
1587 int n;
1588 int status;
1589
1590 if (taglen == -1) taglen = strlen(tag);
1591 if (vlen == -1) vlen = strlen(value);
1592
1593 /* Initialize or grow the allocation? */
1594 if (msa->ngf == msa->alloc_ngf) {
1595 n = (msa->alloc_ngf == 0 ? 16 : msa->alloc_ngf * 2);
1596 ESL_REALLOC(msa->gf_tag, sizeof(char *) * n);
1597 ESL_REALLOC(msa->gf, sizeof(char *) * n);
1598 msa->alloc_ngf = n;
1599 }
1600
1601 if ((status = esl_memstrdup(tag, taglen, &(msa->gf_tag[msa->ngf]))) != eslOK) goto ERROR;
1602 if ((status = esl_memstrdup(value, vlen, &(msa->gf[msa->ngf]))) != eslOK) goto ERROR;
1603 msa->ngf++;
1604 return eslOK;
1605
1606 ERROR:
1607 return status;
1608 }
1609
1610
1611 /* Function: esl_msa_AddGS()
1612 * Synopsis: Add an unparsed #=GS markup line to an <ESL_MSA>
1613 *
1614 * Purpose: Add an unparsed \verb+#=GS+ markup line to the MSA,
1615 * allocating as necessary. It's possible that we
1616 * could get more than one of the same type of GS
1617 * tag per sequence; for example, "DR PDB;" structure
1618 * links in Pfam. Hack: handle these by appending to
1619 * the string, in a \verb+\n+ separated fashion.
1620 *
1621 * Args: msa - multiple alignment structure
1622 * tag - markup tag (e.g. "AC")
1623 * taglen - length of <tag>; or -1 if <tag> is a string of unknown length
1624 * sqidx - index of sequence to assoc markup with (0..nseq-1)
1625 * value - markup (e.g. "P00666")
1626 * vlen - length of <value>; or -1 if <value> is string of unknown length
1627 *
1628 * Returns: <eslOK> on success.
1629 *
1630 * Throws: <eslEMEM> on allocation failure.
1631 */
1632 int
1633 esl_msa_AddGS(ESL_MSA *msa, char *tag, esl_pos_t taglen, int sqidx, char *value, esl_pos_t vlen)
1634 {
1635 int tagidx;
1636 int i;
1637 int status;
1638
1639 if (taglen == -1) taglen = strlen(tag);
1640 if (vlen == -1) vlen = strlen(value);
1641
1642 /* first GS tag? init&allocate */
1643 if (msa->gs_tag == NULL)
1644 {
1645 msa->gs_idx = esl_keyhash_Create();
1646 status = esl_keyhash_Store(msa->gs_idx, tag, taglen, &tagidx);
1647 if (status != eslOK && status != eslEDUP) return status;
1648 ESL_DASSERT1((tagidx == 0));
1649
1650 ESL_ALLOC(msa->gs_tag, sizeof(char *)); /* one at a time. */
1651 ESL_ALLOC(msa->gs, sizeof(char **));
1652 ESL_ALLOC(msa->gs[0], sizeof(char *) * msa->sqalloc);
1653 for (i = 0; i < msa->sqalloc; i++)
1654 msa->gs[0][i] = NULL;
1655 }
1656 else
1657 {
1658 /* Get a tagidx for this GS tag.
1659 * tagidx < ngs; we already saw this tag;
1660 * tagidx == ngs; this is a new one.
1661 */
1662 status = esl_keyhash_Store(msa->gs_idx, tag, taglen, &tagidx);
1663 if (status != eslOK && status != eslEDUP) return status;
1664
1665 /* Reallocation (in blocks of 1) */
1666 if (tagidx == msa->ngs )
1667 {
1668 ESL_REALLOC(msa->gs_tag, (msa->ngs+1) * sizeof(char *));
1669 ESL_REALLOC(msa->gs, (msa->ngs+1) * sizeof(char **));
1670 msa->gs[tagidx] = NULL;
1671 ESL_ALLOC(msa->gs[tagidx], sizeof(char *) * msa->sqalloc);
1672 for (i = 0; i < msa->sqalloc; i++)
1673 msa->gs[tagidx][i] = NULL;
1674 }
1675 }
1676
1677 /* Store the tag, if it's new.
1678 */
1679 if (tagidx == msa->ngs)
1680 {
1681 if ((status = esl_memstrdup(tag, taglen, &(msa->gs_tag[tagidx]))) != eslOK) goto ERROR;
1682 msa->ngs++;
1683 }
1684
1685 /* Store the annotation on the sequence.
1686 * If seq is unannotated, dup the value; if
1687 * seq already has a GS annotation, cat a \n, then cat the value.
1688 */
1689 if (msa->gs[tagidx][sqidx] == NULL)
1690 {
1691 if ((status = esl_memstrdup(value, vlen, &(msa->gs[tagidx][sqidx]))) != eslOK) goto ERROR;
1692 }
1693 else
1694 {
1695 esl_pos_t n1,n2;
1696 n1 = strlen(msa->gs[tagidx][sqidx]);
1697 n2 = (vlen == -1 ? strlen(value) : vlen);
1698 ESL_REALLOC(msa->gs[tagidx][sqidx], sizeof(char) * (n1+n2+2)); /* +2 for \n, \0 */
1699 msa->gs[tagidx][sqidx][n1] = '\n';
1700 memcpy(msa->gs[tagidx][sqidx]+n1+1, value, n2);
1701 msa->gs[tagidx][sqidx][n1+n2+1] = '\0';
1702 }
1703 return eslOK;
1704
1705 ERROR:
1706 return status;
1707 }
1708
1709 /* Function: esl_msa_AppendGC()
1710 * Synopsis: Add an unparsed #=GC markup line to an <ESL_MSA>
1711 *
1712 * Purpose: Add an unparsed \verb+#=GC+ markup line to the MSA
1713 * structure, allocating as necessary. When called
1714 * multiple times for the same tag, appends value
1715 * strings together -- used when parsing multiblock
1716 * alignment files, for example.
1717 *
1718 * Args: msa - multiple alignment structure
1719 * tag - markup tag (e.g. "CS")
1720 * value - markup, one char per aligned column
1721 *
1722 * Returns: <eslOK> on success.
1723 *
1724 * Throws: <eslEMEM> on allocation failure.
1725 */
1726 int
1727 esl_msa_AppendGC(ESL_MSA *msa, char *tag, char *value)
1728 {
1729 int tagidx;
1730 int status;
1731 void *p;
1732
1733 /* Is this an unparsed tag name that we recognize?
1734 * If not, handle adding it to index, and reallocating
1735 * as needed.
1736 */
1737 if (msa->gc_tag == NULL) /* first tag? init&allocate */
1738 {
1739 msa->gc_idx = esl_keyhash_Create();
1740 status = esl_keyhash_Store(msa->gc_idx, tag, -1, &tagidx);
1741 if (status != eslOK && status != eslEDUP) return status;
1742 ESL_DASSERT1((tagidx == 0));
1743
1744 ESL_ALLOC(msa->gc_tag, sizeof(char *));
1745 ESL_ALLOC(msa->gc, sizeof(char *));
1746 msa->gc[0] = NULL;
1747 }
1748 else
1749 { /* new tag? */
1750 /* get tagidx for this GC tag. existing tag: <ngc; new: == ngc. */
1751 status = esl_keyhash_Store(msa->gc_idx, tag, -1, &tagidx);
1752 if (status != eslOK && status != eslEDUP) goto ERROR;
1753
1754 /* Reallocate, in block of one tag at a time
1755 */
1756 if (tagidx == msa->ngc)
1757 {
1758 ESL_RALLOC(msa->gc_tag, p, (msa->ngc+1) * sizeof(char **));
1759 ESL_RALLOC(msa->gc, p, (msa->ngc+1) * sizeof(char **));
1760 msa->gc[tagidx] = NULL;
1761 }
1762 }
1763 /* new tag? store it.
1764 */
1765 if (tagidx == msa->ngc)
1766 {
1767 if ((status = esl_strdup(tag, -1, &(msa->gc_tag[tagidx]))) != eslOK) goto ERROR;
1768 msa->ngc++;
1769 }
1770 return (esl_strcat(&(msa->gc[tagidx]), -1, value, -1));
1771
1772 ERROR:
1773 return status;
1774 }
1775
1776 /* Function: esl_msa_AppendGR()
1777 * Synopsis: Add an unparsed #=GR markup line to an <ESL_MSA>
1778 *
1779 * Purpose: Add an unparsed \verb+#=GR+ markup line to the MSA structure,
1780 * allocating as necessary.
1781 *
1782 * When called multiple times for the same tag, appends
1783 * value strings together -- used when parsing multiblock
1784 * alignment files, for example.
1785 *
1786 * Args: msa - multiple alignment structure
1787 * tag - markup tag (e.g. "SS")
1788 * sqidx - index of seq to assoc markup with (0..nseq-1)
1789 * value - markup, one char per aligned column
1790 *
1791 * Returns: <eslOK> on success.
1792 *
1793 * Throws: <eslEMEM> on allocation failure.
1794 */
1795 int
1796 esl_msa_AppendGR(ESL_MSA *msa, char *tag, int sqidx, char *value)
1797 {
1798 void *p;
1799 int tagidx;
1800 int i;
1801 int status;
1802
1803 if (msa->gr_tag == NULL) /* first tag? init&allocate */
1804 {
1805 msa->gr_idx = esl_keyhash_Create();
1806 status = esl_keyhash_Store(msa->gr_idx, tag, -1, &tagidx);
1807 if (status != eslOK && status != eslEDUP) return status;
1808 ESL_DASSERT1((tagidx == 0));
1809
1810 ESL_ALLOC(msa->gr_tag, sizeof(char *));
1811 ESL_ALLOC(msa->gr, sizeof(char **));
1812 ESL_ALLOC(msa->gr[0], sizeof(char *) * msa->sqalloc);
1813 for (i = 0; i < msa->sqalloc; i++)
1814 msa->gr[0][i] = NULL;
1815 }
1816 else
1817 {
1818 /* get tagidx for this GR tag. existing<ngr; new=ngr.
1819 */
1820 status = esl_keyhash_Store(msa->gr_idx, tag, -1, &tagidx);
1821 if (status != eslOK && status != eslEDUP) return status;
1822
1823 /* if a new tag, realloc for it */
1824 if (tagidx == msa->ngr)
1825 {
1826 ESL_RALLOC(msa->gr_tag, p, (msa->ngr+1) * sizeof(char *));
1827 ESL_RALLOC(msa->gr, p, (msa->ngr+1) * sizeof(char **));
1828 ESL_ALLOC(msa->gr[msa->ngr], sizeof(char *) * msa->sqalloc);
1829 for (i = 0; i < msa->sqalloc; i++)
1830 msa->gr[msa->ngr][i] = NULL;
1831 }
1832 }
1833
1834 if (tagidx == msa->ngr)
1835 {
1836 if ((status = esl_strdup(tag, -1, &(msa->gr_tag[tagidx]))) != eslOK) goto ERROR;
1837 msa->ngr++;
1838 }
1839 return (esl_strcat(&(msa->gr[tagidx][sqidx]), -1, value, -1));
1840
1841 ERROR:
1842 return status;
1843 }
1844
1845 /* Function: esl_msa_CheckUniqueNames()
1846 * Synopsis: Check if all seq names are unique.
1847 *
1848 * Purpose: Check whether all the sequence names in <msa>
1849 * are unique; if so, return <eslOK>, and if not,
1850 * return <eslFAIL>.
1851 *
1852 * Stockholm files require names to be unique. This
1853 * function lets us check whether we need to munge seqnames
1854 * before writing a Stockholm file.
1855 *
1856 * The check uses a keyhash, so it's efficient.
1857 *
1858 * Args: msa - alignment
1859 *
1860 * Returns: <eslOK> if names are unique.
1861 * <eslFAIL> if not.
1862 *
1863 * Throws: <eslMEM> on allocation failure.
1864 */
1865 int
1866 esl_msa_CheckUniqueNames(const ESL_MSA *msa)
1867 {
1868 ESL_KEYHASH *kh = NULL;
1869 int idx;
1870 int status = TRUE;
1871
1872 if ((kh = esl_keyhash_Create()) == NULL) { status = eslEMEM; goto ERROR; }
1873 for (idx = 0; idx < msa->nseq; idx++)
1874 {
1875 status = esl_keyhash_Store(kh, msa->sqname[idx], -1, NULL);
1876 if (status == eslEDUP) { status = eslFAIL; break; }
1877 else if (status != eslOK) goto ERROR;
1878 }
1879 esl_keyhash_Destroy(kh);
1880 return status;
1881
1882 ERROR:
1883 if (kh) esl_keyhash_Destroy(kh);
1884 return status;
1885
1886 }
1887
1888 /* msa_set_seq_ss()
1889 *
1890 * Set the secondary structure annotation for sequence number
1891 * <seqidx> in an alignment <msa> by copying the string <ss>.
1892 *
1893 * Returns: <eslOK> on success.
1894 *
1895 * Throws: <eslEMEM> on allocation failure.
1896 */
1897 static int
1898 msa_set_seq_ss(ESL_MSA *msa, int seqidx, const char *ss)
1899 {
1900 int status;
1901 int i;
1902
1903 if (msa->ss == NULL)
1904 {
1905 ESL_ALLOC(msa->ss, sizeof(char *) * msa->sqalloc);
1906 for (i = 0; i < msa->sqalloc; i++) msa->ss[i] = NULL;
1907 }
1908 if (msa->ss[seqidx] != NULL) free(msa->ss[seqidx]);
1909 return (esl_strdup(ss, -1, &(msa->ss[seqidx])));
1910
1911 ERROR:
1912 return status;
1913 }
1914
1915 /* msa_set_seq_sa()
1916 *
1917 * Set the surface accessibility annotation for sequence number
1918 * <seqidx> in an alignment <msa> by copying the string <sa>.
1919 *
1920 * Returns: <eslOK> on success.
1921 *
1922 * Throws: <eslEMEM> on allocation failure.
1923 */
1924 static int
1925 msa_set_seq_sa(ESL_MSA *msa, int seqidx, const char *sa)
1926 {
1927 int status;
1928 int i;
1929
1930 if (msa->sa == NULL)
1931 {
1932 ESL_ALLOC(msa->sa, sizeof(char *) * msa->sqalloc);
1933 for (i = 0; i < msa->sqalloc; i++) msa->sa[i] = NULL;
1934 }
1935 if (msa->sa[seqidx] != NULL) free(msa->sa[seqidx]);
1936 return (esl_strdup(sa, -1, &(msa->sa[seqidx])));
1937
1938 ERROR:
1939 return status;
1940 }
1941
1942 /* msa_set_seq_pp()
1943 *
1944 * Set the posterior probability annotation for sequence number
1945 * <seqidx> in an alignment <msa> by copying the string <pp>.
1946 *
1947 * Returns: <eslOK> on success.
1948 *
1949 * Throws: <eslEMEM> on allocation failure.
1950 */
1951 static int
1952 msa_set_seq_pp(ESL_MSA *msa, int seqidx, const char *pp)
1953 {
1954 int status;
1955 int i;
1956
1957 if (msa->pp == NULL)
1958 {
1959 ESL_ALLOC(msa->pp, sizeof(char *) * msa->sqalloc);
1960 for (i = 0; i < msa->sqalloc; i++) msa->pp[i] = NULL;
1961 }
1962 if (msa->pp[seqidx] != NULL) free(msa->pp[seqidx]);
1963 return (esl_strdup(pp, -1, &(msa->pp[seqidx])));
1964
1965 ERROR:
1966 return status;
1967 }
1968 /*---------- end of ESL_MSA field setting/checking --------------*/
1969
1970
1971
1972 /*****************************************************************
1973 *# 4. Miscellaneous functions for manipulating MSAs
1974 *****************************************************************/
1975
1976 static int64_t msa_get_rlen(const ESL_MSA *msa, int seqidx);
1977
1978
1979 /* Function: esl_msa_ReasonableRF()
1980 * Synopsis: Determine a reasonable #=RF line marking "consensus" columns.
1981 *
1982 * Purpose: Define an <rfline> for the multiple alignment <msa> that
1983 * marks consensus columns with an 'x' (or the consensus
1984 * letter if useconsseq is TRUE), and non-consensus columns
1985 * with a '.'.
1986 *
1987 * Consensus columns are defined as columns with fractional
1988 * occupancy of $\geq$ <symfrac> in residues. For example,
1989 * if <symfrac> is 0.7, columns containing $\geq$ 70\%
1990 * residues are assigned as 'x' (or consensus letter) in the
1991 * <rfline>, roughly speaking. "Roughly speaking", because the
1992 * fractional occupancy is in fact calculated as a weighted
1993 * frequency using sequence weights in <msa->wgt>, and because
1994 * missing data symbols are ignored in order to be able to
1995 * deal with sequence fragments.
1996 *
1997 * The greater <symfrac> is, the more stringent the
1998 * definition, and the fewer columns will be defined as
1999 * consensus. <symfrac=0> will define all columns as
2000 * consensus. <symfrac=1> will only define a column as
2001 * consensus if it contains no gap characters at all.
2002 *
2003 * If the caller wants to designate any sequences as
2004 * fragments, it must convert all leading and trailing gaps
2005 * to the missing data symbol '~'.
2006 *
2007 * For text mode alignments, any alphanumeric character is
2008 * considered to be a residue, and any non-alphanumeric
2009 * character is considered to be a gap.
2010 *
2011 * The <rfline> is a NUL-terminated string, indexed
2012 * <0..alen-1>.
2013 *
2014 * The <rfline> result can be <msa->rf>, if the caller
2015 * wants to set the <msa's> own RF line; or it can be any
2016 * alternative storage provided by the caller. In either
2017 * case, the caller must provide allocated space for at
2018 * least <msa->alen+1> chars.
2019 *
2020 * Args: msa - MSA to define a consensus RF line for
2021 * symfrac - threshold for defining consensus columns
2022 * useconsseq - if FALSE, use x for a consensus position; else use the consensus letter
2023 * rfline - RESULT: string containing a letter for consensus position, . for not
2024 *
2025 * Returns: <eslOK> on success.
2026 *
2027 * Xref: HMMER p7_Fastmodelmaker() uses an essentially identical
2028 * calculation to define model architecture, and could be
2029 * rewritten now to use this function.
2030 *
2031 * A2M format alignment output uses this to define
2032 * consensus columns when #=RF annotation isn't available.
2033 */
2034 int
2035 esl_msa_ReasonableRF(ESL_MSA *msa, double symfrac, int useconsseq, char *rfline)
2036 {
2037 int apos;
2038 int idx;
2039 double r;
2040 double totwgt;
2041 float *counts = NULL;
2042 int status;
2043
2044 if (useconsseq)
2045 ESL_ALLOC(counts, msa->abc->K * sizeof(float));
2046
2047 if (msa->flags & eslMSA_DIGITAL)
2048 {
2049 for (apos = 1; apos <= msa->alen; apos++)
2050 {
2051 r = totwgt = 0.;
2052 esl_vec_FSet(counts, msa->abc->K, 0.0);
2053 for (idx = 0; idx < msa->nseq; idx++)
2054 {
2055 if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][apos]))
2056 {
2057 r += msa->wgt[idx]; totwgt += msa->wgt[idx];
2058 if (useconsseq) esl_abc_FCount(msa->abc, counts, msa->ax[idx][apos], msa->wgt[idx]);
2059 }
2060 else if (esl_abc_XIsGap(msa->abc, msa->ax[idx][apos])) totwgt += msa->wgt[idx];
2061 else if (esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos])) continue;
2062 }
2063 if (r > 0. && r / totwgt >= symfrac) {
2064 if (useconsseq) rfline[apos-1] = msa->abc->sym[esl_vec_FArgMax(counts, msa->abc->K)];
2065 else rfline[apos-1] = 'x';
2066 }
2067 else rfline[apos-1] = '.';
2068
2069 }
2070 }
2071
2072 if (! (msa->flags & eslMSA_DIGITAL))
2073 {
2074 for (apos = 0; apos < msa->alen; apos++)
2075 {
2076 r = totwgt = 0.;
2077 for (idx = 0; idx < msa->nseq; idx++)
2078 {
2079 if (isalpha(msa->aseq[idx][apos]))
2080 {
2081 r += msa->wgt[idx]; totwgt += msa->wgt[idx];
2082 if (useconsseq) esl_abc_FCount(msa->abc, counts, msa->abc->inmap[ (int) msa->aseq[idx][apos] ], msa->wgt[idx]);
2083 }
2084 else totwgt += msa->wgt[idx];
2085 }
2086 if (r > 0. && r / totwgt >= symfrac) {
2087 if (useconsseq) rfline[apos-1] = msa->abc->sym[esl_vec_FArgMax(counts, msa->abc->K)];
2088 else rfline[apos] = 'x';
2089 }
2090 else rfline[apos] = '.';
2091 }
2092 }
2093
2094 rfline[msa->alen] = '\0';
2095 if (counts) free(counts);
2096 return eslOK;
2097
2098 ERROR:
2099 if (counts) free(counts);
2100 return status;
2101 }
2102
2103
2104 /* Function: esl_msa_MarkFragments()
2105 * Synopsis: Heuristic definition of sequence fragments in an alignment
2106 * Incept: SRE, Sun 14 Apr 2019 [DL4378 LHR-BOS]
2107 *
2108 * Purpose: Heuristically define sequence fragments (as opposed to
2109 * full length sequences) in <msa>. Set bit <i> in <fragassign>
2110 * to <TRUE> if seq <i> is a fragment, else <FALSE>.
2111 *
2112 * The rule is to calculate the fractional "span" of each
2113 * aligned sequence: the aligned length from its first to
2114 * last residue, divided by the total number of aligned
2115 * columns; sequence is defined as a fragment if <aspan/alen
2116 * < fragthresh>.
2117 *
2118 * In a text mode <msa>, any alphanumeric character is
2119 * considered to be a residue, and any non-alphanumeric
2120 * char is considered to be a gap.
2121 *
2122 * <fragassign> is allocated here; caller frees.
2123 *
2124 * Returns: <eslOK> on success.
2125 *
2126 * Throws: <eslEMEM> on allocation error.
2127 *
2128 * Xref: Compare <esl_msaweight>, which uses the same fragment definition
2129 * rule without calling this function, because it's used a little
2130 * differently.
2131 */
2132 int
2133 esl_msa_MarkFragments(const ESL_MSA *msa, float fragthresh, ESL_BITFIELD **ret_fragassign)
2134 {
2135 ESL_BITFIELD *fragassign = NULL;
2136 int minspan = (int) ceil(fragthresh * (float) msa->alen); // precalculated span length threshold using <fragthresh>
2137 int idx,lpos,rpos;
2138 int status;
2139
2140 if (( fragassign = esl_bitfield_Create(msa->nseq)) == NULL) { status = eslEMEM; goto ERROR; }
2141
2142 /* Digital mode */
2143 if (msa->flags & eslMSA_DIGITAL)
2144 {
2145 for (idx = 0; idx < msa->nseq; idx++)
2146 {
2147 for (lpos = 1; lpos <= msa->alen; lpos++) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][lpos])) break;
2148 for (rpos = msa->alen; rpos >= 1; rpos--) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][rpos])) break;
2149 /* L=0 sequence? lpos == msa->alen+1, rpos == 0; lpos > rpos.
2150 * alen=0 alignment? lpos == 1, rpos == 0; lpos > rpos.
2151 * so alispan = rpos-lpos+1 could be <= 0 if lpos > rpos
2152 */
2153 if (rpos-lpos+1 < minspan) esl_bitfield_Set(fragassign, idx);
2154 }
2155 }
2156 /* Text mode */
2157 else
2158 {
2159 for (idx = 0; idx < msa->nseq; idx++)
2160 {
2161 for (lpos = 0; lpos < msa->alen; lpos++) if (isalpha(msa->aseq[idx][lpos])) break;
2162 for (rpos = msa->alen-1; rpos >= 0; rpos--) if (isalpha(msa->aseq[idx][rpos])) break;
2163 if (rpos-lpos+1 < minspan) esl_bitfield_Set(fragassign, idx);
2164 }
2165 }
2166 *ret_fragassign = fragassign;
2167 return eslOK;
2168
2169 ERROR:
2170 esl_bitfield_Destroy(fragassign);
2171 *ret_fragassign = NULL;
2172 return status;
2173 }
2174
2175
2176
2177 /* Function: esl_msa_MarkFragments_old()
2178 * Synopsis: Heuristically define seq fragments in an alignment.
2179 *
2180 * Purpose: Use a heuristic to define sequence fragments (as opposed
2181 * to "full length" sequences) in alignment <msa>.
2182 *
2183 * The rule is that if the sequence has a raw (unaligned)
2184 * length not greater than <fragthresh> times the alignment
2185 * length in columns, the sequence is defined as a fragment.
2186 *
2187 * For each fragment, all leading and trailing gap symbols
2188 * (all gaps before the first residue and after the last
2189 * residue) are converted to missing data symbols
2190 * (typically '~', but nonstandard digital alphabets may
2191 * have defined another character).
2192 *
2193 * If <fragthresh> is 0.0, no nonempty sequence is defined
2194 * as a fragment.
2195 *
2196 * If <fragthresh> is 1.0, all sequences are defined as
2197 * fragments.
2198 *
2199 * Args: msa - alignment in which to define and mark seq fragments
2200 * fragthresh - define frags if rlen <= fragthresh * alen.
2201 *
2202 * Returns: <eslOK> on success.
2203 */
2204 int
2205 esl_msa_MarkFragments_old(ESL_MSA *msa, double fragthresh)
2206 {
2207 int i;
2208 int pos;
2209
2210 for (i = 0; i < msa->nseq; i++)
2211 if (msa_get_rlen(msa, i) <= fragthresh * msa->alen)
2212 {
2213 if (msa->flags & eslMSA_DIGITAL) {
2214 for (pos = 1; pos <= msa->alen; pos++) {
2215 if (esl_abc_XIsResidue(msa->abc, msa->ax[i][pos])) break;
2216 msa->ax[i][pos] = esl_abc_XGetMissing(msa->abc);
2217 }
2218 for (pos = msa->alen; pos >= 1; pos--) {
2219 if (esl_abc_XIsResidue(msa->abc, msa->ax[i][pos])) break;
2220 msa->ax[i][pos] = esl_abc_XGetMissing(msa->abc);
2221 }
2222 }
2223
2224 if (! (msa->flags & eslMSA_DIGITAL))
2225 {
2226 for (pos = 0; pos < msa->alen; pos++) {
2227 if (isalnum(msa->aseq[i][pos])) break;
2228 msa->aseq[i][pos] = '~';
2229 }
2230 for (pos = msa->alen-1; pos >= 0; pos--) {
2231 if (isalnum(msa->aseq[i][pos])) break;
2232 msa->aseq[i][pos] = '~';
2233 }
2234 }
2235 }
2236 return eslOK;
2237 }
2238
2239
2240 /* Function: esl_msa_SequenceSubset()
2241 * Synopsis: Select subset of sequences into a smaller MSA.
2242 *
2243 * Purpose: Given an array <useme> (0..nseq-1) of TRUE/FALSE flags for each
2244 * sequence in an alignment <msa>; create a new alignment containing
2245 * only those seqs which are flagged <useme=TRUE>. Return a pointer
2246 * to this newly allocated alignment through <ret_new>. Caller is
2247 * responsible for freeing it.
2248 *
2249 * The smaller alignment might now contain columns
2250 * consisting entirely of gaps or missing data, depending
2251 * on what sequence subset was extracted. The caller may
2252 * want to immediately call <esl_msa_MinimGaps()> on the
2253 * new alignment to clean this up.
2254 *
2255 * Unparsed GS and GR Stockholm annotation that is presumably still
2256 * valid is transferred to the new alignment. Unparsed GC, GF, and
2257 * comments that are potentially invalidated by taking the subset
2258 * of sequences are not transferred to the new MSA.
2259 *
2260 * Weights are transferred exactly. If they need to be
2261 * renormalized to some new total weight (such as the new,
2262 * smaller total sequence number), the caller must do that.
2263 *
2264 * <msa> may be in text mode or digital mode. The new MSA
2265 * in <ret_new> will have the same mode.
2266 *
2267 * Returns: <eslOK> on success, and <ret_new> is set to point at a new
2268 * (smaller) alignment.
2269 *
2270 * Throws: <eslEINVAL> if the subset has no sequences in it;
2271 * <eslEMEM> on allocation error.
2272 *
2273 * Xref: squid's MSASmallerAlignment(), 1999.
2274 */
2275 int
2276 esl_msa_SequenceSubset(const ESL_MSA *msa, const int *useme, ESL_MSA **ret_new)
2277 {
2278 ESL_MSA *new_msa = NULL;
2279 int nnew; /* number of seqs in the new MSA */
2280 int oidx, nidx; /* old, new indices */
2281 int i;
2282 int status;
2283
2284 ESL_DASSERT1(( msa->nseq > 0 ));
2285 ESL_DASSERT1(( msa->alen >= 0 )); // This silences static checkers that think msa->alen might be -1.
2286 *ret_new = NULL;
2287
2288 nnew = 0;
2289 for (oidx = 0; oidx < msa->nseq; oidx++)
2290 if (useme[oidx]) nnew++;
2291 if (nnew == 0) ESL_EXCEPTION(eslEINVAL, "No sequences selected");
2292
2293 /* Note that the Create() calls allocate exact space for the sequences,
2294 * so we will strcpy()/memcpy() into them below.
2295 */
2296 if ((msa->flags & eslMSA_DIGITAL) &&
2297 (new_msa = esl_msa_CreateDigital(msa->abc, nnew, msa->alen)) == NULL)
2298 {status = eslEMEM; goto ERROR; }
2299
2300 if (! (msa->flags & eslMSA_DIGITAL) &&
2301 (new_msa = esl_msa_Create(nnew, msa->alen)) == NULL)
2302 {status = eslEMEM; goto ERROR; }
2303 if (new_msa == NULL)
2304 {status = eslEMEM; goto ERROR; }
2305
2306
2307 /* Copy the old to the new */
2308 for (nidx = 0, oidx = 0; oidx < msa->nseq; oidx++)
2309 if (useme[oidx])
2310 {
2311 if (msa->flags & eslMSA_DIGITAL)
2312 memcpy(new_msa->ax[nidx], msa->ax[oidx], sizeof(ESL_DSQ) * (msa->alen+2));
2313
2314 if (! (msa->flags & eslMSA_DIGITAL))
2315 strcpy(new_msa->aseq[nidx], msa->aseq[oidx]);
2316
2317 if ((status = esl_strdup(msa->sqname[oidx], -1, &(new_msa->sqname[nidx]))) != eslOK) goto ERROR;
2318
2319 new_msa->wgt[nidx] = msa->wgt[oidx];
2320
2321 if (msa->sqacc && msa->sqacc[oidx] && (status = esl_msa_SetSeqAccession (new_msa, nidx, msa->sqacc[oidx], -1)) != eslOK) goto ERROR;
2322 if (msa->sqdesc && msa->sqdesc[oidx] && (status = esl_msa_SetSeqDescription(new_msa, nidx, msa->sqdesc[oidx], -1)) != eslOK) goto ERROR;
2323 if (msa->ss && msa->ss[oidx] && (status = msa_set_seq_ss (new_msa, nidx, msa->ss[oidx])) != eslOK) goto ERROR;
2324 if (msa->sa && msa->sa[oidx] && (status = msa_set_seq_sa (new_msa, nidx, msa->sa[oidx])) != eslOK) goto ERROR;
2325 if (msa->pp && msa->pp[oidx] && (status = msa_set_seq_pp (new_msa, nidx, msa->pp[oidx])) != eslOK) goto ERROR;
2326
2327 /* unparsed annotation */
2328 for(i = 0; i < msa->ngs; i++) { if (msa->gs[i] && msa->gs[i][oidx] && (status = esl_msa_AddGS (new_msa, msa->gs_tag[i], -1, nidx, msa->gs[i][oidx], -1)) != eslOK) goto ERROR; }
2329 for(i = 0; i < msa->ngr; i++) { if (msa->gr[i] && msa->gr[i][oidx] && (status = esl_msa_AppendGR(new_msa, msa->gr_tag[i], nidx, msa->gr[i][oidx])) != eslOK) goto ERROR; }
2330
2331 nidx++;
2332 }
2333
2334 new_msa->flags = msa->flags;
2335
2336 if ((status = esl_strdup(msa->name, -1, &(new_msa->name))) != eslOK) goto ERROR;
2337 if ((status = esl_strdup(msa->desc, -1, &(new_msa->desc))) != eslOK) goto ERROR;
2338 if ((status = esl_strdup(msa->acc, -1, &(new_msa->acc))) != eslOK) goto ERROR;
2339 if ((status = esl_strdup(msa->au, -1, &(new_msa->au))) != eslOK) goto ERROR;
2340 if ((status = esl_strdup(msa->ss_cons, msa->alen, &(new_msa->ss_cons))) != eslOK) goto ERROR;
2341 if ((status = esl_strdup(msa->sa_cons, msa->alen, &(new_msa->sa_cons))) != eslOK) goto ERROR;
2342 if ((status = esl_strdup(msa->pp_cons, msa->alen, &(new_msa->pp_cons))) != eslOK) goto ERROR;
2343 if ((status = esl_strdup(msa->rf, msa->alen, &(new_msa->rf))) != eslOK) goto ERROR;
2344 if ((status = esl_strdup(msa->mm, msa->alen, &(new_msa->mm))) != eslOK) goto ERROR;
2345
2346 for (i = 0; i < eslMSA_NCUTS; i++) {
2347 new_msa->cutoff[i] = msa->cutoff[i];
2348 new_msa->cutset[i] = msa->cutset[i];
2349 }
2350
2351 new_msa->nseq = nnew;
2352 new_msa->sqalloc = nnew;
2353
2354 /* Since we have a fully constructed MSA, we don't need the
2355 * aux info used by parsers.
2356 */
2357 if (new_msa->sqlen != NULL) { free(new_msa->sqlen); new_msa->sqlen = NULL; }
2358 if (new_msa->sslen != NULL) { free(new_msa->sslen); new_msa->sslen = NULL; }
2359 if (new_msa->salen != NULL) { free(new_msa->salen); new_msa->salen = NULL; }
2360 if (new_msa->pplen != NULL) { free(new_msa->pplen); new_msa->pplen = NULL; }
2361 new_msa->lastidx = -1;
2362
2363 *ret_new = new_msa;
2364 return eslOK;
2365
2366 ERROR:
2367 if (new_msa != NULL) esl_msa_Destroy(new_msa);
2368 *ret_new = NULL;
2369 return status;
2370 }
2371
2372
2373 /* Function: esl_msa_ColumnSubset()
2374 * Synopsis: Remove a selected subset of columns from the MSA
2375 *
2376 * Purpose: Given an array <useme> (0..alen-1) of TRUE/FALSE flags,
2377 * where TRUE means "keep this column in the new alignment";
2378 * remove all columns annotated as FALSE in the <useme>
2379 * array. This is done in-place on the MSA, so the MSA is
2380 * modified: <msa->alen> is reduced, <msa->aseq> is shrunk
2381 * (or <msa->ax>, in the case of a digital mode alignment),
2382 * and all associated per-residue or per-column annotation
2383 * is shrunk.
2384 *
2385 * Returns: <eslOK> on success.
2386 * Possibilities from <esl_msa_RemoveBrokenBasepairs()> call:
2387 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2388 * following <esl_wuss_nopseudo()> is inconsistent.
2389 * <eslEINVAL> if a derived ct array implies a pknotted SS.
2390 */
2391 int
2392 esl_msa_ColumnSubset(ESL_MSA *msa, char *errbuf, const int *useme)
2393 {
2394 int status;
2395 int64_t opos; /* position in original alignment */
2396 int64_t npos; /* position in new alignment */
2397 int idx; /* sequence index */
2398 int i; /* markup index */
2399
2400 /* For RNA/DNA digital alignments only:
2401 * Remove any basepairs from SS_cons and individual sequence SS
2402 * for aln columns i,j for which useme[i-1] or useme[j-1] are FALSE
2403 */
2404 if ( msa->abc && (msa->abc->type == eslRNA || msa->abc->type == eslDNA) &&
2405 (status = esl_msa_RemoveBrokenBasepairs(msa, errbuf, useme)) != eslOK) return status;
2406
2407 /* Since we're minimizing, we can overwrite in place, within the msa
2408 * we've already got.
2409 * opos runs all the way to msa->alen to include (and move) the \0
2410 * string terminators (or sentinel bytes, in the case of digital mode)
2411 */
2412 for (opos = 0, npos = 0; opos <= msa->alen; opos++)
2413 {
2414 if (opos < msa->alen && useme[opos] == FALSE) continue;
2415
2416 if (npos != opos) /* small optimization */
2417 {
2418 /* The alignment, and per-residue annotations */
2419 for (idx = 0; idx < msa->nseq; idx++)
2420 {
2421 if (msa->flags & eslMSA_DIGITAL) /* watch off-by-one in dsq indexing */
2422 msa->ax[idx][npos+1] = msa->ax[idx][opos+1];
2423 else
2424 msa->aseq[idx][npos] = msa->aseq[idx][opos];
2425 if (msa->ss != NULL && msa->ss[idx] != NULL) msa->ss[idx][npos] = msa->ss[idx][opos];
2426 if (msa->sa != NULL && msa->sa[idx] != NULL) msa->sa[idx][npos] = msa->sa[idx][opos];
2427 if (msa->pp != NULL && msa->pp[idx] != NULL) msa->pp[idx][npos] = msa->pp[idx][opos];
2428 for (i = 0; i < msa->ngr; i++)
2429 if (msa->gr[i][idx] != NULL)
2430 msa->gr[i][idx][npos] = msa->gr[i][idx][opos];
2431 }
2432 /* The per-column annotations */
2433 if (msa->ss_cons != NULL) msa->ss_cons[npos] = msa->ss_cons[opos];
2434 if (msa->sa_cons != NULL) msa->sa_cons[npos] = msa->sa_cons[opos];
2435 if (msa->pp_cons != NULL) msa->pp_cons[npos] = msa->pp_cons[opos];
2436 if (msa->rf != NULL) msa->rf[npos] = msa->rf[opos];
2437 if (msa->mm != NULL) msa->mm[npos] = msa->mm[opos];
2438 for (i = 0; i < msa->ngc; i++)
2439 msa->gc[i][npos] = msa->gc[i][opos];
2440 }
2441 npos++;
2442 }
2443 msa->alen = npos-1; /* -1 because npos includes NUL terminators */
2444 return eslOK;
2445 }
2446
2447 /* Function: esl_msa_MinimGaps()
2448 * Synopsis: Remove columns containing all gap symbols.
2449 *
2450 * Purpose: Remove all columns in the multiple alignment <msa>
2451 * that consist entirely of gaps or missing data.
2452 *
2453 * For a text mode alignment, <gaps> is a string defining
2454 * the gap characters, such as <"-_.~">. For a digital mode
2455 * alignment, <gaps> may be passed as <NULL>, because the
2456 * internal alphabet already knows what the gap and missing
2457 * data characters are.
2458 *
2459 * <msa> is changed in-place to a narrower alignment
2460 * containing fewer columns. All per-residue and per-column
2461 * annotation is altered appropriately for the columns that
2462 * remain in the new alignment.
2463 *
2464 * If <consider_rf> is TRUE, only columns that are gaps
2465 * in all sequences of <msa> and a gap in the RF annotation
2466 * of the alignment (<msa->rf>) will be removed. It is
2467 * okay if <consider_rf> is TRUE and <msa->rf> is NULL
2468 * (no error is thrown), the function will behave as if
2469 * <consider_rf> is FALSE.
2470 *
2471 * Returns: <eslOK> on success.
2472 *
2473 * Throws: <eslEMEM> on allocation failure.
2474 * Possibilities from <esl_msa_ColumnSubset()> call:
2475 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2476 * following <esl_wuss_nopseudo()> is inconsistent.
2477 * <eslEINVAL> if a derived ct array implies a pknotted SS.
2478 *
2479 * Xref: squid's MSAMingap().
2480 */
2481 int
2482 esl_msa_MinimGaps(ESL_MSA *msa, char *errbuf, const char *gaps, int consider_rf)
2483 {
2484 int *useme = NULL; /* array of TRUE/FALSE flags for which cols to keep */
2485 int64_t apos; /* column index */
2486 int idx; /* sequence index */
2487 int status;
2488 int rf_is_nongap; /* TRUE if current position is not a gap in msa->rf OR msa->rf is NULL */
2489
2490
2491 if (msa->flags & eslMSA_DIGITAL) /* be careful of off-by-one: useme is 0..L-1 indexed */
2492 {
2493 ESL_ALLOC(useme, sizeof(int) * (msa->alen+1)); /* +1 is just to deal w/ alen=0 special case */
2494
2495 for (apos = 1; apos <= msa->alen; apos++)
2496 {
2497 rf_is_nongap = ((msa->rf != NULL) &&
2498 (! esl_abc_CIsGap (msa->abc, msa->rf[apos-1])) &&
2499 (! esl_abc_CIsMissing(msa->abc, msa->rf[apos-1]))) ?
2500 TRUE : FALSE;
2501 if(rf_is_nongap && consider_rf) { /* RF is not a gap and consider_rf is TRUE, keep this column */
2502 useme[apos-1] = TRUE;
2503 }
2504 else { /* check all seqs to see if this column is all gaps */
2505 for (idx = 0; idx < msa->nseq; idx++)
2506 if (! esl_abc_XIsGap (msa->abc, msa->ax[idx][apos]) &&
2507 ! esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos]))
2508 break;
2509 if (idx == msa->nseq) useme[apos-1] = FALSE; else useme[apos-1] = TRUE;
2510 }
2511 }
2512 if ((status = esl_msa_ColumnSubset(msa, errbuf, useme)) != eslOK) goto ERROR;
2513 }
2514
2515 if (! (msa->flags & eslMSA_DIGITAL)) /* text mode case */
2516 {
2517 if ( (status = esl_msa_MinimGapsText(msa, errbuf, gaps, consider_rf, FALSE)) != eslOK) goto ERROR;
2518 }
2519
2520 if (useme) free(useme);
2521 return eslOK;
2522
2523 ERROR:
2524 if (useme) free(useme);
2525 return status;
2526 }
2527
2528 /* Function: esl_msa_MinimGapsText()
2529 * Synopsis: Remove columns containing all gap symbols, from text mode msa
2530 *
2531 * Purpose: Same as esl\_msa\_MinimGaps(), but specialized for a text mode
2532 * alignment where we don't know the alphabet. The issue is what
2533 * to do about RNA secondary structure annotation (SS, SS\_cons)
2534 * when we remove columns, which can remove one side of a bp and
2535 * invalidate the annotation string. For digital alignments,
2536 * <esl_msa_MinimGaps()> knows the alphabet and will fix base pairs
2537 * for RNA/DNA alignments. For text mode, though, we have to
2538 * get told to do it, because the default behavior for text mode
2539 * alis is to assume that the alphabet is totally arbitrary, and we're
2540 * not allowed to make assumptions about its symbols' meaning.
2541 * Hence, the <fix_bps> flag here.
2542 *
2543 * Ditto for the <gaps> string: we don't know what symbols
2544 * are supposed to be gaps unless we're told something like
2545 * <"-_.~">.
2546 *
2547 * Args: msa - alignment to remove all-gap cols from
2548 * errbuf - if non-<NULL>, space for an informative error message on failure
2549 * gaps - string of gap characters
2550 * consider_rf - if TRUE, also consider gap/nongap cols in RF annotation line
2551 * fix_bps - if TRUE, fix any broken bps in SS/SS\_cons annotation lines.
2552 *
2553 * Returns: <eslOK> on success.
2554 *
2555 * Throws: <eslEMEM> on allocation failure.
2556 * Possibilities from <esl_msa_ColumnSubset()> call:
2557 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2558 * following <esl_wuss_nopseudo()> is inconsistent.
2559 * <eslEINVAL> if a derived ct array implies a pknotted SS.
2560 */
2561 int
2562 esl_msa_MinimGapsText(ESL_MSA *msa, char *errbuf, const char *gaps, int consider_rf, int fix_bps)
2563 {
2564 int *useme = NULL; /* array of TRUE/FALSE flags for which cols to keep */
2565 int64_t apos; /* column index */
2566 int idx; /* sequence index */
2567 int status;
2568 int rf_is_nongap; /* TRUE if current position is not a gap in msa->rf OR msa->rf is NULL */
2569
2570 ESL_ALLOC(useme, sizeof(int) * (msa->alen+1)); /* +1 is just to deal w/ alen=0 special case */
2571
2572 for (apos = 0; apos < msa->alen; apos++)
2573 {
2574 rf_is_nongap = ((msa->rf != NULL) && (strchr(gaps, msa->rf[apos]) == NULL)) ? TRUE : FALSE;
2575 if (rf_is_nongap && consider_rf) useme[apos] = TRUE; /* RF is not a gap and consider_rf is TRUE, keep this column */
2576 else
2577 { /* check all seqs to see if this column is all gaps */
2578 for (idx = 0; idx < msa->nseq; idx++)
2579 if (strchr(gaps, msa->aseq[idx][apos]) == NULL) break;
2580 useme[apos] = (idx == msa->nseq ? FALSE : TRUE);
2581 }
2582 }
2583
2584 if (fix_bps && (status = esl_msa_RemoveBrokenBasepairs(msa, errbuf, useme)) != eslOK) goto ERROR;
2585 if ( (status = esl_msa_ColumnSubset (msa, errbuf, useme)) != eslOK) goto ERROR;
2586
2587 free(useme);
2588 return eslOK;
2589
2590 ERROR:
2591 if (useme) free(useme);
2592 return status;
2593 }
2594
2595
2596 /* Function: esl_msa_NoGaps()
2597 * Synopsis: Remove columns containing any gap symbol.
2598 *
2599 * Purpose: Remove all columns in the multiple alignment <msa> that
2600 * contain any gaps or missing data, such that the modified
2601 * MSA consists only of ungapped columns (a solid block of
2602 * residues).
2603 *
2604 * This is useful for filtering alignments prior to
2605 * phylogenetic analysis using programs that can't deal
2606 * with gaps.
2607 *
2608 * For a text mode alignment, <gaps> is a string defining
2609 * the gap characters, such as <"-_.~">. For a digital mode
2610 * alignment, <gaps> may be passed as <NULL>, because the
2611 * internal alphabet already knows what the gap and
2612 * missing data characters are.
2613 *
2614 * <msa> is changed in-place to a narrower alignment
2615 * containing fewer columns. All per-residue and per-column
2616 * annotation is altered appropriately for the columns that
2617 * remain in the new alignment.
2618 *
2619 * Returns: <eslOK> on success.
2620 *
2621 * Throws: <eslEMEM> on allocation failure.
2622 * Possibilities from <esl_msa_ColumnSubset()> call:
2623 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2624 * following <esl_wuss_nopseudo()> is inconsistent.
2625 * <eslEINVAL> if a derived ct array implies a pknotted SS.
2626 *
2627 * Xref: squid's MSANogap().
2628 */
2629 int
2630 esl_msa_NoGaps(ESL_MSA *msa, char *errbuf, const char *gaps)
2631 {
2632 int *useme = NULL; /* array of TRUE/FALSE flags for which cols to keep */
2633 int64_t apos; /* column index */
2634 int idx; /* sequence index */
2635 int status;
2636
2637 if (msa->flags & eslMSA_DIGITAL) /* be careful of off-by-one: useme is 0..L-1 indexed */
2638 {
2639 ESL_ALLOC(useme, sizeof(int) * (msa->alen+1)); /* +1 is only to deal with alen=0 special case */
2640
2641 for (apos = 1; apos <= msa->alen; apos++)
2642 {
2643 for (idx = 0; idx < msa->nseq; idx++)
2644 if (esl_abc_XIsGap (msa->abc, msa->ax[idx][apos]) ||
2645 esl_abc_XIsMissing(msa->abc, msa->ax[idx][apos]))
2646 break;
2647 if (idx == msa->nseq) useme[apos-1] = TRUE; else useme[apos-1] = FALSE;
2648 }
2649
2650 if ((status = esl_msa_ColumnSubset(msa, errbuf, useme)) != eslOK) goto ERROR;
2651 }
2652
2653 if (! (msa->flags & eslMSA_DIGITAL)) /* text mode case */
2654 {
2655 if ((status = esl_msa_NoGapsText(msa, errbuf, gaps, FALSE)) != eslOK) goto ERROR;
2656 }
2657 if (useme) free(useme);
2658 return eslOK;
2659
2660 ERROR:
2661 if (useme) free(useme);
2662 return status;
2663 }
2664
2665
2666 /* Function: esl_msa_NoGapsText()
2667 * Synopsis: Remove columns containing any gap symbol at all, for text mode msa.
2668 *
2669 * Purpose: Like <esl_msa_NoGaps()> but specialized for textmode <msa> where
2670 * we don't know the alphabet, yet might need to fix alphabet-dependent
2671 * problems.
2672 *
2673 * Like <esl_msa_MinimGapsText()>, the alphabet-dependent issue we might
2674 * want to fix is RNA secondary structure annotation (SS, SS\_cons);
2675 * removing a column might remove one side of a base pair annotation, and
2676 * invalidate a secondary structure string. <fix_bps> tells the function
2677 * that SS and SS\_cons are RNA WUSS format strings, and the function is
2678 * allowed to edit (and fix) them. Normally, in text mode msa's, we
2679 * are not allowed to interpret any meaning of symbols.
2680 *
2681 * Args: msa - alignment to remove any-gap cols from
2682 * errbuf - if non-<NULL>, space for an informative error message on failure
2683 * gaps - string of gap characters
2684 * fix_bps - if TRUE, fix any broken bps in SS/SS\_cons annotation lines
2685 *
2686 * Returns: <eslOK> on success.
2687 *
2688 * Throws: <eslEMEM> on allocation failure.
2689 * Possibilities from <esl_msa_ColumnSubset()> call:
2690 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2691 * following <esl_wuss_nopseudo()> is inconsistent.
2692 * <eslEINVAL> if a derived ct array implies a pknotted SS.
2693 */
2694 int
2695 esl_msa_NoGapsText(ESL_MSA *msa, char *errbuf, const char *gaps, int fix_bps)
2696 {
2697 int *useme = NULL; /* array of TRUE/FALSE flags for which cols to keep */
2698 int64_t apos; /* column index */
2699 int idx; /* sequence index */
2700 int status;
2701
2702 ESL_ALLOC(useme, sizeof(int) * (msa->alen+1)); /* +1 is only to deal with alen=0 special case */
2703
2704 for (apos = 0; apos < msa->alen; apos++)
2705 {
2706 for (idx = 0; idx < msa->nseq; idx++)
2707 if (strchr(gaps, msa->aseq[idx][apos]) != NULL) break;
2708 useme[apos] = (idx == msa->nseq ? TRUE : FALSE);
2709 }
2710
2711 if (fix_bps && (status = esl_msa_RemoveBrokenBasepairs(msa, errbuf, useme)) != eslOK) goto ERROR;
2712 if ( (status = esl_msa_ColumnSubset (msa, errbuf, useme)) != eslOK) goto ERROR;
2713
2714 free(useme);
2715 return eslOK;
2716
2717 ERROR:
2718 if (useme) free(useme);
2719 return status;
2720 }
2721
2722
2723 /* Function: esl_msa_SymConvert()
2724 * Synopsis: Global search/replace of symbols in an MSA.
2725 *
2726 * Purpose: In the aligned sequences in a text-mode <msa>, convert any
2727 * residue in the string <oldsyms> to its counterpart (at the same
2728 * position) in string <newsyms>.
2729 *
2730 * To convert DNA to RNA, <oldsyms> could be "Tt" and
2731 * <newsyms> could be "Uu". To convert IUPAC symbols to
2732 * N's, <oldsyms> could be "RYMKSWHBVDrymkswhbvd" and
2733 * <newsyms> could be "NNNNNNNNNNnnnnnnnnnn".
2734 *
2735 * As a special case, if <newsyms> consists of a single
2736 * character, then any character in the <oldsyms> is
2737 * converted to this character.
2738 *
2739 * Thus, <newsyms> must either be of the same length as
2740 * <oldsyms>, or of length 1. Anything else will cause
2741 * undefined behavior (and probably segfault).
2742 *
2743 * The conversion is done in-place, so the <msa> is
2744 * modified.
2745 *
2746 * This is a poor man's hack for processing text mode MSAs
2747 * into a more consistent text alphabet. It is unnecessary
2748 * for digital mode MSAs, which are already in a standard
2749 * internal alphabet. Calling <esl_msa_SymConvert()> on a
2750 * digital mode alignment throws an <eslEINVAL> error.
2751 *
2752 * Returns: <eslOK> on success.
2753 *
2754 * Throws: <eslEINVAL> if <msa> is in digital mode, or if the <oldsyms>
2755 * and <newsyms> strings aren't valid together.
2756 */
2757 int
2758 esl_msa_SymConvert(ESL_MSA *msa, const char *oldsyms, const char *newsyms)
2759 {
2760 int64_t apos; /* column index */
2761 int idx; /* sequence index */
2762 char *sptr;
2763 int special;
2764
2765 if (msa->flags & eslMSA_DIGITAL)
2766 ESL_EXCEPTION(eslEINVAL, "can't SymConvert a digital mode alignment");
2767 if ((strlen(oldsyms) != strlen(newsyms)) && strlen(newsyms) != 1)
2768 ESL_EXCEPTION(eslEINVAL, "invalid newsyms/oldsyms pair");
2769
2770 special = (strlen(newsyms) == 1 ? TRUE : FALSE);
2771
2772 for (idx = 0; idx < msa->nseq; idx++)
2773 for (apos = 0; apos < msa->alen; apos++)
2774 if ((sptr = strchr(oldsyms, msa->aseq[idx][apos])) != NULL)
2775 msa->aseq[idx][apos] = (special ? *newsyms : newsyms[sptr-oldsyms]);
2776 return eslOK;
2777 }
2778
2779
2780 /* Function: esl_msa_Checksum()
2781 * Synopsis: Calculate a checksum for an MSA.
2782 * Incept: SRE, Tue Sep 16 13:23:34 2008 [Janelia]
2783 *
2784 * Purpose: Calculates a 32-bit checksum for <msa>.
2785 *
2786 * Only the alignment data are considered, not the sequence
2787 * names or other annotation. For text mode alignments, the
2788 * checksum is case sensitive.
2789 *
2790 * This is used as a quick way to try to verify that a
2791 * given alignment is identical to an expected one; for
2792 * example, when HMMER is mapping new sequence alignments
2793 * onto exactly the same seed alignment an HMM was built
2794 * from.
2795 *
2796 * Returns: <eslOK> on success.
2797 *
2798 * Xref: The checksum is a modified version of Jenkin's hash;
2799 * see <esl_keyhash> for the original and citations.
2800 */
2801 int
2802 esl_msa_Checksum(const ESL_MSA *msa, uint32_t *ret_checksum)
2803 {
2804 uint32_t val = 0;
2805 int i,pos;
2806
2807 if (msa->flags & eslMSA_DIGITAL)
2808 {
2809 for (i = 0; i < msa->nseq; i++)
2810 for (pos = 1; pos <= msa->alen; pos++)
2811 {
2812 val += msa->ax[i][pos];
2813 val += (val << 10);
2814 val ^= (val >> 6);
2815 }
2816 }
2817
2818 if (! (msa->flags & eslMSA_DIGITAL))
2819 {
2820 for (i = 0; i < msa->nseq; i++)
2821 for (pos = 0; pos < msa->alen; pos++)
2822 {
2823 val += msa->aseq[i][pos];
2824 val += (val << 10);
2825 val ^= (val >> 6);
2826 }
2827 }
2828 val += (val << 3);
2829 val ^= (val >> 11);
2830 val += (val << 15);
2831
2832 *ret_checksum = val;
2833 return eslOK;
2834 }
2835
2836
2837 /* Function: esl_msa_RemoveBrokenBasepairsFromSS()
2838 * Synopsis: Remove basepairs about to be broken by a column downselect.
2839 *
2840 * Purpose: Given an array <useme> (0..alen-1) of TRUE/FALSE flags,
2841 * remove any basepair from an SS string that is between
2842 * alignment columns (i,j) for which either <useme[i-1]> or
2843 * <useme[j-1]> is FALSE. Called by
2844 * <esl_msa_RemoveBrokenBasepairs()>.
2845 *
2846 * The input SS string will be overwritten. If it was not
2847 * in full WUSS format when passed in, it will be upon
2848 * exit. Note that that means if there's residues in the
2849 * input ss that correspond to gaps in an aligned sequence
2850 * or RF annotation, they will not be treated as gaps in
2851 * the returned SS. For example, a gap may become a '-'
2852 * character, a '<_>' character, or a ':' character. I'm not
2853 * sure how to deal with this in a better way. We could
2854 * demand an aligned sequence to use to de-gap the SS
2855 * string, but that would require disallowing any gap to be
2856 * involved in a basepair, which I'm not sure is something
2857 * we want to forbid.
2858 *
2859 * If the original SS is inconsistent it's left untouched
2860 * and non-<eslOK> is returned as listed below.
2861 *
2862 * Returns: <eslOK> on success.
2863 * <eslESYNTAX> if SS string
2864 * <eslEINVAL> if a derived ct array implies a pknotted
2865 * SS, this should be impossible.
2866 *
2867 * Throws: <eslEMEM> on allocation failure.
2868 */
2869 int
2870 esl_msa_RemoveBrokenBasepairsFromSS(char *ss, char *errbuf, int len, const int *useme)
2871 {
2872 int64_t apos; /* alignment position */
2873 int *ct = NULL; /* 0..alen-1 base pair partners array for current sequence */
2874 int status;
2875
2876 ESL_ALLOC(ct, sizeof(int) * (len+1));
2877
2878 if ((status = esl_wuss2ct(ss, len, ct)) != eslOK)
2879 ESL_FAIL(status, errbuf, "Consensus structure string is inconsistent.");
2880 for (apos = 1; apos <= len; apos++) {
2881 if (!(useme[apos-1])) {
2882 if (ct[apos] != 0) ct[ct[apos]] = 0;
2883 ct[apos] = 0;
2884 }
2885 }
2886 /* All broken bps removed from ct, convert to WUSS SS string and overwrite SS */
2887 if ((status = esl_ct2wuss(ct, len, ss)) != eslOK)
2888 ESL_FAIL(status, errbuf, "Error converting de-knotted bp ct array to WUSS notation.");
2889
2890 free(ct);
2891 return eslOK;
2892
2893 ERROR:
2894 if (ct != NULL) free(ct);
2895 return status;
2896 }
2897
2898 /* Function: esl_msa_RemoveBrokenBasepairs()
2899 * Synopsis: Remove all annotated bps about to be broken by column downselect.
2900 *
2901 * Purpose: Given an array <useme> (0..alen-1) of TRUE/FALSE flags,
2902 * remove any basepair from <SS_cons> and individual SS
2903 * annotation in alignment columns (i,j) for which either
2904 * <useme[i-1]> or <useme[j-1]> is FALSE. Called
2905 * automatically from <esl_msa_ColumnSubset()> with same
2906 * <useme>.
2907 *
2908 * If the original structure data is inconsistent it's left
2909 * untouched.
2910 *
2911 * Returns: <eslOK> on success.
2912 * <eslESYNTAX> if WUSS string for <SS_cons> or <msa->ss>
2913 * following <esl_wuss_nopseudo()> is inconsistent.
2914 * <eslEINVAL> if a derived ct array implies a pknotted
2915 * SS, this should be impossible
2916 *
2917 * Throws: <eslEMEM> on allocation failure.
2918 */
2919 int
2920 esl_msa_RemoveBrokenBasepairs(ESL_MSA *msa, char *errbuf, const int *useme)
2921 {
2922 int status;
2923 int i;
2924
2925 if (msa->ss_cons) {
2926 if((status = esl_msa_RemoveBrokenBasepairsFromSS(msa->ss_cons, errbuf, msa->alen, useme)) != eslOK) return status;
2927 }
2928 /* per-seq SS annotation */
2929 if (msa->ss) {
2930 for(i = 0; i < msa->nseq; i++) {
2931 if (msa->ss[i]) {
2932 if ((status = esl_msa_RemoveBrokenBasepairsFromSS(msa->ss[i], errbuf, msa->alen, useme)) != eslOK) return status;
2933 }
2934 }
2935 }
2936 return eslOK;
2937 }
2938
2939 /* msa_get_rlen()
2940 *
2941 * Returns the raw (unaligned) length of sequence number <seqidx>
2942 * in <msa>.
2943 */
2944 static int64_t
2945 msa_get_rlen(const ESL_MSA *msa, int seqidx)
2946 {
2947 int64_t rlen = 0;
2948 int pos;
2949
2950
2951 if (msa->flags & eslMSA_DIGITAL) rlen = esl_abc_dsqrlen(msa->abc, msa->ax[seqidx]);
2952
2953 if (! (msa->flags & eslMSA_DIGITAL))
2954 {
2955 for (pos = 0; pos < msa->alen; pos++)
2956 if (isalnum(msa->aseq[seqidx][pos])) rlen++;
2957 }
2958 return rlen;
2959 }
2960
2961
2962
2963 /* Function: esl_msa_ReverseComplement()
2964 * Synopsis: Reverse complement a multiple alignment
2965 * Incept: SRE, Wed Feb 10 12:52:13 2016 [JB251 BOS-MCO]
2966 *
2967 * Purpose: Reverse complement the multiple alignment <msa>, in place.
2968 *
2969 * <msa> must be in digital mode, and it must be in an alphabet
2970 * that permits reverse complementation (<eslDNA>, <eslRNA>).
2971 *
2972 * In addition to reverse complementing the sequence data,
2973 * per-column and per-residue annotation also gets reversed
2974 * or reverse complemented. Secondary structure annotations
2975 * (the consensus structure <ss_cons>, and any individual
2976 * structures <ss[i]>) are assumed to be in WUSS format,
2977 * and are "reverse complemented" using
2978 * <esl_wuss_reverse()>. Other annotations are assumed to
2979 * be textual, and are simply reversed. Beware, because
2980 * this can go awry if an optional <gc> or <gr> annotation
2981 * has semantics that would require complementation (an RNA
2982 * structure annotation, for example).
2983 *
2984 * Returns: <eslOK> on success.
2985 *
2986 * Throws: <eslEINCOMPAT> if <msa> isn't digital, or isn't in an alphabet
2987 * that allows reverse complementation.
2988 */
2989 int
2990 esl_msa_ReverseComplement(ESL_MSA *msa)
2991 {
2992 int i;
2993 int m;
2994 int status;
2995
2996 if (! (msa->flags & eslMSA_DIGITAL)) ESL_EXCEPTION(eslEINCOMPAT, "msa isn't digital");
2997 if ( msa->abc->complement == NULL) ESL_EXCEPTION(eslEINCOMPAT, "msa alphabet can't be reverse complemented");
2998
2999 if (msa->ss_cons) esl_wuss_reverse(msa->ss_cons, msa->ss_cons);
3000 if (msa->sa_cons) esl_vec_CReverse(msa->sa_cons, msa->sa_cons, msa->alen);
3001 if (msa->pp_cons) esl_vec_CReverse(msa->pp_cons, msa->pp_cons, msa->alen);
3002 if (msa->rf) esl_vec_CReverse(msa->rf, msa->rf, msa->alen);
3003 if (msa->mm) esl_vec_CReverse(msa->mm, msa->mm, msa->alen);
3004
3005 for (m = 0; m < msa->ngc; m++)
3006 if (msa->gc && msa->gc[m]) esl_vec_CReverse(msa->gc[m], msa->gc[m], msa->alen);
3007
3008 for (i = 0; i < msa->nseq; i++)
3009 {
3010 if ((status = esl_abc_revcomp(msa->abc, msa->ax[i], msa->alen)) != eslOK) goto ERROR;
3011 if (msa->ss && msa->ss[i]) esl_wuss_reverse(msa->ss[i], msa->ss[i]);
3012 if (msa->sa && msa->sa[i]) esl_vec_CReverse(msa->sa[i], msa->sa[i], msa->alen);
3013 if (msa->pp && msa->pp[i]) esl_vec_CReverse(msa->pp[i], msa->pp[i], msa->alen);
3014 }
3015
3016 for (m = 0; m < msa->ngr; m++)
3017 for (i = 0; i < msa->nseq; i++)
3018 if (msa->gr && msa->gr[m] && msa->gr[m][i])
3019 esl_vec_CReverse(msa->gr[m][i], msa->gr[m][i], msa->alen);
3020
3021 return eslOK;
3022
3023 ERROR:
3024 return status;
3025 }
3026
3027
3028
3029
3030 /* Function: esl_msa_Hash()
3031 * Synopsis: Hash sequence names, internally, for faster access/lookup.
3032 *
3033 * Purpose: Caller wants to map sequence names to integer index in the
3034 * <ESL_MSA> structure, using the internal <msa->index> keyhash.
3035 * Create (or recreate) that index.
3036 *
3037 * Each sequence name must be unique. If not, returns
3038 * <eslEDUP>, and <msa->index> is <NULL> (if it already
3039 * existed, it is destroyed).
3040 *
3041 * Returns: <eslOK> on success, and <msa->index> is available for
3042 * keyhash lookups.
3043 *
3044 * <eslEDUP> if any sequence names are duplicated, and
3045 * <msa->index> is <NULL>.
3046 *
3047 * Throws: <eslEMEM> on allocation error.
3048 */
3049 int
3050 esl_msa_Hash(ESL_MSA *msa)
3051 {
3052 int idx;
3053 int status;
3054
3055 if (msa->index) esl_keyhash_Reuse(msa->index);
3056 else msa->index = esl_keyhash_Create();
3057 if (! msa->index) { status = eslEMEM; goto ERROR; }
3058
3059 for (idx = 0; idx < msa->nseq; idx++)
3060 if ((status = esl_keyhash_Store(msa->index, msa->sqname[idx], -1, NULL)) != eslOK) goto ERROR;
3061
3062 return eslOK;
3063
3064 ERROR:
3065 if (msa->index) { esl_keyhash_Destroy(msa->index); msa->index = NULL; }
3066 return status;
3067 }
3068
3069
3070
3071 /* Function: esl_msa_FlushLeftInserts()
3072 * Synopsis: Make all insertions flush left.
3073 * Incept: SRE, Tue Apr 25 17:04:47 2017 [Cambridge Dance Complex]
3074 *
3075 * Purpose: Given an alignment <msa> with reference annotation
3076 * defining consensus (match) columns versus insertions,
3077 * make all the insertions flush left (i.e. in each
3078 * insertion position in the consensus, gaps follow
3079 * inserted residues).
3080 *
3081 * This makes profile multiple alignments unique w.r.t.
3082 * arbitrary gap ordering in insert regions, since profile
3083 * alignments don't specify any alignment of insertions.
3084 * A2M alignment format, for example, does not specify any
3085 * insert alignment.
3086 *
3087 * Returns: <eslOK> on success. <msa> is altered, rearranging the
3088 * order of gaps and inserted residues.
3089 *
3090 * Throws: <eslEINVAL> if <msa> has no reference annotation.
3091 *
3092 * Note: Written for <esl_msafile_a2m.c::utest_gibberish()>.
3093 */
3094 int
3095 esl_msa_FlushLeftInserts(ESL_MSA *msa)
3096 {
3097 int i, a, b;
3098
3099 ESL_DASSERT1(( msa->flags & eslMSA_DIGITAL ));
3100 ESL_DASSERT1(( msa->abc != NULL ));
3101 ESL_DASSERT1(( msa->ax != NULL ));
3102
3103 if (! msa->rf) ESL_EXCEPTION(eslEINVAL, "msa has no reference annotation");
3104
3105 for (i = 0; i < msa->nseq; i++)
3106 {
3107 for (a = 1, b = 1; a <= msa->alen; a++)
3108 {
3109 if ( ! esl_abc_CIsGap(msa->abc, msa->rf[a-1]) ) // if column[a] is consensus:
3110 { for (; b < a; b++) msa->ax[i][b] = esl_abc_XGetGap(msa->abc); } // catch b up to a, adding gaps
3111 else if (esl_abc_XIsGap(msa->abc, msa->ax[i][a])) // else if column[a] is nonconsensus, and ax[a] is a gap:
3112 continue; // do nothing, just advance to next a
3113 msa->ax[i][b++] = msa->ax[i][a]; // copy a consensus position, or nonconsensus residue
3114 }
3115 for (; b <= msa->alen; b++) msa->ax[i][b] = esl_abc_XGetGap(msa->abc); // finally, catch b up to end of alignment, adding gaps as needed.
3116 }
3117 return eslOK;
3118 }
3119
3120
3121 /*----------------- end of misc MSA functions -------------------*/
3122
3123
3124 /*****************************************************************
3125 * 5. Debugging, testing, development
3126 *****************************************************************/
3127
3128 /* Function: esl_msa_Validate()
3129 * Synopsis: Validate an ESL_MSA structure.
3130 *
3131 * Purpose: Validates the fields of the <ESL_MSA> structure
3132 * <msa>. Makes sure required information is present,
3133 * consistent. If so, return <eslOK>.
3134 *
3135 * If a problem is detected, return <eslFAIL>. Caller may
3136 * also provide an optional <errmsg> pointer to a buffer of
3137 * at least <eslERRBUFSIZE>; if this message buffer is
3138 * provided, an informative error message is put there.
3139 *
3140 * Args: msa - MSA structure to validate
3141 * errmsg - OPTIONAL: error message buffer, at least <eslERRBUFSIZE>; or <NULL>
3142 *
3143 * Returns: <eslOK> on success, and <errmsg> (if provided) is set
3144 * to an empty string.
3145 *
3146 * <eslFAIL> on failure and <errmsg> (if provided) contains
3147 * the reason for the failure.
3148 */
3149 int
3150 esl_msa_Validate(const ESL_MSA *msa, char *errmsg)
3151 {
3152 int idx;
3153
3154 if (msa->nseq == 0) ESL_FAIL(eslFAIL, errmsg, "no alignment data found");
3155
3156 for (idx = 0; idx < msa->nseq; idx++)
3157 {
3158
3159 if (msa->flags & eslMSA_DIGITAL)
3160 {
3161 if (! msa->ax || ! msa->ax[idx]) ESL_FAIL(eslFAIL, errmsg, "seq %d: no sequence", idx);
3162 if (esl_abc_dsqlen(msa->ax[idx]) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "seq %d: wrong length", idx);
3163 }
3164
3165 if (! (msa->flags & eslMSA_DIGITAL))
3166 {
3167 if (! msa->aseq || ! msa->aseq[idx]) ESL_FAIL(eslFAIL, errmsg, "seq %d: no sequence", idx);
3168 if (strlen(msa->aseq[idx]) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "seq %d: wrong length", idx);
3169 }
3170
3171 /* either all weights must be set, or none of them */
3172 if ( msa->flags & eslMSA_HASWGTS) { if (msa->wgt[idx] == -1.0) ESL_FAIL(eslFAIL, errmsg, "seq %d: no weight set", idx);}
3173 else { if (msa->wgt[idx] != 1.0) ESL_FAIL(eslFAIL, errmsg, "seq %d: HASWGTS flag down, wgt must be default", idx); }
3174
3175 if (msa->ss && msa->ss[idx] && strlen(msa->ss[idx]) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "seq %d: SS wrong length", idx);
3176 if (msa->sa && msa->sa[idx] && strlen(msa->sa[idx]) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "seq %d: SA wrong length", idx);
3177 if (msa->pp && msa->pp[idx] && strlen(msa->pp[idx]) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "seq %d: PP wrong length", idx);
3178 }
3179
3180 /* if cons SS is present, must have length right */
3181 if (msa->ss_cons && strlen(msa->ss_cons) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "SS_cons wrong length");
3182 if (msa->sa_cons && strlen(msa->sa_cons) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "SA_cons wrong length");
3183 if (msa->pp_cons && strlen(msa->pp_cons) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "PP_cons wrong length");
3184 if (msa->rf && strlen(msa->rf) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "RF wrong length");
3185 if (msa->mm && strlen(msa->mm ) != msa->alen) ESL_FAIL(eslFAIL, errmsg, "MM wrong length");
3186
3187 return eslOK;
3188 }
3189
3190
3191
3192
3193 /* Function: esl_msa_Compare()
3194 * Synopsis: Compare two MSAs for equality.
3195 *
3196 * Purpose: Returns <eslOK> if the mandatory and optional contents
3197 * of MSAs <a1> and <a2> are identical; otherwise return
3198 * <eslFAIL>.
3199 *
3200 * Only mandatory and parsed optional information is
3201 * compared. Unparsed Stockholm markup is not compared.
3202 */
3203 int
3204 esl_msa_Compare(ESL_MSA *a1, ESL_MSA *a2)
3205 {
3206 if (esl_msa_CompareMandatory(a1, a2) != eslOK) return eslFAIL;
3207 if (esl_msa_CompareOptional(a1, a2) != eslOK) return eslFAIL;
3208 return eslOK;
3209 }
3210
3211 /* Function: esl_msa_CompareMandatory()
3212 * Synopsis: Compare mandatory subset of MSA contents.
3213 * Incept: SRE, Wed Jun 13 09:42:56 2007 [Janelia]
3214 *
3215 * Purpose: Compare mandatory contents of two MSAs, <a1> and <a2>.
3216 * This comprises <aseq> (or <ax>, for a digital alignment);
3217 * <sqname>, <wgt>, <alen>, <nseq>, and <flags>.
3218 *
3219 * Returns: <eslOK> if the MSAs are identical;
3220 * <eslFAIL> if they are not.
3221 */
3222 int
3223 esl_msa_CompareMandatory(ESL_MSA *a1, ESL_MSA *a2)
3224 {
3225 int i;
3226
3227 if (a1->nseq != a2->nseq) return eslFAIL;
3228 if (a1->alen != a2->alen) return eslFAIL;
3229 if (a1->flags != a2->flags) return eslFAIL;
3230
3231 for (i = 0; i < a1->nseq; i++)
3232 {
3233 if (strcmp(a1->sqname[i], a2->sqname[i]) != 0) return eslFAIL;
3234 if (esl_DCompare_old(a1->wgt[i], a2->wgt[i], 0.001) != eslOK) return eslFAIL;
3235
3236 if ((a1->flags & eslMSA_DIGITAL) &&
3237 memcmp(a1->ax[i], a2->ax[i], sizeof(ESL_DSQ) * (a1->alen+2)) != 0)
3238 return eslFAIL;
3239
3240 if (! (a1->flags & eslMSA_DIGITAL) && strcmp(a1->aseq[i], a2->aseq[i]) != 0) return eslFAIL;
3241 }
3242 return eslOK;
3243 }
3244
3245 /* Function: esl_msa_CompareOptional()
3246 * Synopsis: Compare optional subset of MSA contents.
3247 * Incept: SRE, Wed Jun 13 09:52:48 2007 [Janelia]
3248 *
3249 * Purpose: Compare optional contents of two MSAs, <a1> and <a2>.
3250 *
3251 * Returns: <eslOK> if the MSAs are identical;
3252 * <eslFAIL> if they are not.
3253 */
3254 int
3255 esl_msa_CompareOptional(ESL_MSA *a1, ESL_MSA *a2)
3256 {
3257 int i;
3258
3259 if (esl_CCompare(a1->name, a2->name) != eslOK) return eslFAIL;
3260 if (esl_CCompare(a1->desc, a2->desc) != eslOK) return eslFAIL;
3261 if (esl_CCompare(a1->acc, a2->acc) != eslOK) return eslFAIL;
3262 if (esl_CCompare(a1->au, a2->au) != eslOK) return eslFAIL;
3263 if (esl_CCompare(a1->ss_cons, a2->ss_cons) != eslOK) return eslFAIL;
3264 if (esl_CCompare(a1->sa_cons, a2->sa_cons) != eslOK) return eslFAIL;
3265 if (esl_CCompare(a1->pp_cons, a2->pp_cons) != eslOK) return eslFAIL;
3266 if (esl_CCompare(a1->rf, a2->rf) != eslOK) return eslFAIL;
3267 if (esl_CCompare(a1->mm, a2->mm) != eslOK) return eslFAIL;
3268
3269 if (a1->sqacc != NULL && a2->sqacc != NULL) {
3270 for (i = 0; i < a1->nseq; i++) if (esl_CCompare(a1->sqacc[i], a2->sqacc[i]) != eslOK) return eslFAIL;
3271 } else if (a1->sqacc != NULL || a2->sqacc != NULL) return eslFAIL;
3272
3273 if (a1->sqdesc != NULL && a2->sqdesc != NULL) {
3274 for (i = 0; i < a1->nseq; i++) if (esl_CCompare(a1->sqdesc[i], a2->sqdesc[i]) != eslOK) return eslFAIL;
3275 } else if (a1->sqdesc != NULL || a2->sqdesc != NULL) return eslFAIL;
3276
3277 if (a1->ss != NULL && a2->ss != NULL) {
3278 for (i = 0; i < a1->nseq; i++) if (esl_CCompare(a1->ss[i], a2->ss[i]) != eslOK) return eslFAIL;
3279 } else if (a1->ss != NULL || a2->ss != NULL) return eslFAIL;
3280
3281 if (a1->sa != NULL && a2->sa != NULL) {
3282 for (i = 0; i < a1->nseq; i++) if (esl_CCompare(a1->sa[i], a2->sa[i]) != eslOK) return eslFAIL;
3283 } else if (a1->sa != NULL || a2->sa != NULL) return eslFAIL;
3284
3285 if (a1->pp != NULL && a2->pp != NULL) {
3286 for (i = 0; i < a1->nseq; i++) if (esl_CCompare(a1->pp[i], a2->pp[i]) != eslOK) return eslFAIL;
3287 } else if (a1->pp != NULL || a2->pp != NULL) return eslFAIL;
3288
3289 for (i = 0; i < eslMSA_NCUTS; i++)
3290 {
3291 if (a1->cutset[i] && a2->cutset[i]) {
3292 if (esl_FCompare_old(a1->cutoff[i], a2->cutoff[i], 0.01) != eslOK) return eslFAIL;
3293 } else if (a1->cutset[i] || a2->cutset[i]) return eslFAIL;
3294 }
3295 return eslOK;
3296 }
3297
3298
3299 /* Function: esl_msa_Sample()
3300 * Synopsis: Sample a random, ugly <ESL_MSA> for test purposes.
3301 * Incept: SRE, Fri Apr 21 09:51:45 2017 [Culprit 1, Strings Outro]
3302 *
3303 * Purpose: Sample a random digital MSA with a random depth 1..<max_nseq>
3304 * random sequences and a random alignment length
3305 * 1..<alen>. Return the MSA via <*ret_msa>. Caller is
3306 * responsible for free'ing it with <esl_msa_Destroy()>.
3307 *
3308 * Currently generates aligned sequences <ax>, names
3309 * <sqname> plus a randomly generated reference/consensus
3310 * annotation line. Sets mandatory weights to default all
3311 * 1.0.
3312 *
3313 * Returns: <eslOK> on success, and <*ret_msa> is the sampled MSA.
3314 *
3315 * Throws: <eslEMEM> on allocation failure, and <*ret_msa> is <NULL>.
3316 *
3317 * Notes: I wrote this for A2M format unit tests, which is why it's
3318 * not sampling random weights (A2M doesn't store weights),
3319 * and why it samples a reference annotation line (A2M
3320 * always implies one). If you extend this for other
3321 * purposes, make sure you don't break the A2M format
3322 * tests. We may even want to pull this out into its own
3323 * module, so we can write something a bit for flexible for
3324 * passing options to it, to control what it does and
3325 * doesn't generate.
3326 */
3327 int
3328 esl_msa_Sample(ESL_RANDOMNESS *rng, const ESL_ALPHABET *abc, int max_nseq, int max_alen, ESL_MSA **ret_msa)
3329 {
3330 ESL_MSA *msa = NULL;
3331 int nseq = 1 + esl_rnd_Roll(rng, max_nseq); // 1..max_nseq
3332 int alen = 1 + esl_rnd_Roll(rng, max_alen); // 1..max_alen
3333 int maxn = 30;
3334 double pgap = 0.1;
3335 double pdegen = 0.02;
3336 double pcons = 0.7;
3337 char *buf = NULL;
3338 int n;
3339 int i,pos;
3340 int status;
3341
3342 if ((msa = esl_msa_CreateDigital(abc, nseq, alen)) == NULL) { status = eslEMEM; goto ERROR; }
3343
3344 /* Randomized digital sequence alignment */
3345 for (i = 0; i < nseq; i++)
3346 {
3347 msa->ax[i][0] = msa->ax[i][alen+1] = eslDSQ_SENTINEL;
3348 for (pos = 1; pos <= alen; pos++)
3349 {
3350 if (esl_random(rng) < pgap) msa->ax[i][pos] = abc->K;
3351 else if (esl_random(rng) < pdegen) msa->ax[i][pos] = (abc->K+1) + esl_rnd_Roll(rng, abc->Kp-abc->K-3);
3352 else msa->ax[i][pos] = esl_rnd_Roll(rng, abc->K);
3353 }
3354 }
3355
3356 /* Random names */
3357 ESL_ALLOC(buf, sizeof(char) * (maxn+1));
3358 for (i = 0; i < nseq; i++)
3359 {
3360 do {
3361 n = 1 + esl_rnd_Roll(rng, maxn); // 1..maxn
3362 esl_rsq_Sample(rng, eslRSQ_SAMPLE_GRAPH, n, &buf); // one word, no space
3363 } while (ispunct(buf[0])); // #, // are bad things for names to start with
3364 esl_msa_SetSeqName(msa, i, buf, n);
3365 }
3366
3367 /* Random reference/consensus line */
3368 ESL_ALLOC(msa->rf, sizeof(char) * (alen+1));
3369 for (pos = 0; pos < alen; pos++)
3370 msa->rf[pos] = (esl_random(rng) < pcons ? 'x' : '.');
3371 msa->rf[alen] = '\0';
3372
3373 /* Set weights to default 1.0 */
3374 esl_msa_SetDefaultWeights(msa);
3375
3376 free(buf);
3377 *ret_msa = msa;
3378 return eslOK;
3379
3380 ERROR:
3381 if (buf) free(buf);
3382 esl_msa_Destroy(msa);
3383 *ret_msa = NULL;
3384 return status;
3385 }
3386 /*---------------- end of debugging/development routines -------------------*/
3387
3388
3389 /******************************************************************************
3390 * 15. Unit tests
3391 *****************************************************************************/
3392 #ifdef eslMSA_TESTDRIVE
3393 #include "esl_msafile.h"
3394
3395 /* write_known_msa()
3396 * Write a known MSA to a tmpfile in Stockholm format.
3397 */
3398 static void
3399 write_known_msa(FILE *ofp)
3400 {
3401 fprintf(ofp, "# STOCKHOLM 1.0\n");
3402 fprintf(ofp, "seq1 --ACDEFGHIK~LMNPQRS-TVWY\n");
3403 fprintf(ofp, "seq2 aaACDEFGHIK~LMNPQRS-TVWY\n");
3404 fprintf(ofp, "seq3 aaACDEFGHIK~LMNPQRS-TVWY\n");
3405 fprintf(ofp, "\n");
3406 fprintf(ofp, "seq1 ACDEFGHIKLMNPQRSTVWY~~~\n");
3407 fprintf(ofp, "seq2 ACDEFGHIKLMNPQRSTVWYyyy\n");
3408 fprintf(ofp, "seq3 ACDEFGHIKLMNPQRSTVWYyyy\n");
3409 fprintf(ofp, "//\n");
3410 return;
3411 }
3412
3413
3414 /* compare_to_known()
3415 * SRE, Thu Sep 7 09:52:07 2006 [Janelia]
3416 * Spotcheck an ESL_MSA to make sure it matches the test known alignment.
3417 */
3418 static void
3419 compare_to_known(ESL_MSA *msa)
3420 {
3421 if (msa->alen != 47) esl_fatal("bad alen");
3422 if (msa->nseq != 3) esl_fatal("bad nseq");
3423 if (strcmp(msa->sqname[1], "seq2") != 0) esl_fatal("bad sqname");
3424
3425 if (msa->flags & eslMSA_DIGITAL)
3426 {
3427 if (! esl_abc_XIsGap(msa->abc, msa->ax[0][2])) esl_fatal("no gap where expected");
3428 if (! esl_abc_XIsMissing(msa->abc, msa->ax[0][47])) esl_fatal("no missing-data symbol where expected");
3429 if (msa->ax[1][1] != 0) esl_fatal("spotcheck on ax failed"); /* 0=A */
3430 if (msa->ax[1][47] != 19) esl_fatal("spotcheck on ax failed"); /*19=Y */
3431 }
3432
3433 if (! (msa->flags & eslMSA_DIGITAL))
3434 {
3435 if (strcasecmp(msa->aseq[0], "--ACDEFGHIK~LMNPQRS-TVWYACDEFGHIKLMNPQRSTVWY~~~") != 0) esl_fatal("aseq 0 is bad");
3436 if (strcasecmp(msa->aseq[1], "aaACDEFGHIK~LMNPQRS-TVWYACDEFGHIKLMNPQRSTVWYyyy") != 0) esl_fatal("aseq 1 is bad");
3437 if (strcasecmp(msa->aseq[2], "aaACDEFGHIK~LMNPQRS-TVWYACDEFGHIKLMNPQRSTVWYyyy") != 0) esl_fatal("aseq 2 is bad");
3438 }
3439 return;
3440 }
3441
3442 /* Unit tests for every function in the exposed API
3443 */
3444 static void
3445 utest_Create(void)
3446 {
3447 ESL_MSA *msa = NULL;
3448
3449 msa = esl_msa_Create(16, -1); /* nseq blocksize 16, growable */
3450 esl_msa_Destroy(msa);
3451 msa = esl_msa_Create(16, 100); /* nseq=16, alen=100, not growable */
3452 esl_msa_Destroy(msa);
3453
3454 return;
3455 }
3456
3457 static void
3458 utest_Sizeof(ESL_RANDOMNESS *rng)
3459 {
3460 const char msg[] = "utest_Sizeof() failed";
3461 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
3462 ESL_MSA *msa = NULL;
3463 int nseq = 100;
3464 int alen = 200;
3465 size_t n = 0;
3466
3467 if (esl_msa_Sample(rng, abc, nseq, alen, &msa) != eslOK) esl_fatal(msg);
3468 if ((n = esl_msa_Sizeof(msa)) <= 0) esl_fatal(msg);
3469
3470 esl_msa_Destroy(msa);
3471 esl_alphabet_Destroy(abc);
3472 }
3473
3474 static void
3475 utest_Destroy(void)
3476 {
3477 ESL_ALPHABET *abc = NULL;
3478 ESL_MSA *msa = NULL;
3479
3480 msa = esl_msa_Create(16, -1);
3481 esl_msa_Destroy(msa); /* normal usage */
3482
3483 abc = esl_alphabet_Create(eslRNA);
3484 msa = esl_msa_CreateDigital(abc, 16, 100);
3485 esl_msa_Destroy(msa); /* normal usage, digital mode */
3486 esl_alphabet_Destroy(abc);
3487
3488 esl_msa_Destroy(NULL); /* should tolerate NULL argument */
3489 return;
3490 }
3491
3492 static void
3493 utest_Expand(void)
3494 {
3495 ESL_ALPHABET *abc = NULL;
3496 ESL_MSA *msa = NULL;
3497
3498 msa = esl_msa_Create(16, -1); /* growable */
3499 if (esl_msa_Expand(msa) != eslOK) esl_fatal("Expand failed"); /* expand by 2x in nseq */
3500 esl_msa_Destroy(msa);
3501
3502 msa = esl_msa_Create(16, 100); /* not growable */
3503 #ifdef eslTEST_THROWING
3504 if (esl_msa_Expand(msa) != eslEINVAL) esl_fatal("Expand should have failed but didn't"); /* should fail w/ EINVAL*/
3505 #endif
3506 esl_msa_Destroy(msa);
3507
3508 abc = esl_alphabet_Create(eslDNA);
3509 msa = esl_msa_CreateDigital(abc, 16, -1); /* growable */
3510 if (esl_msa_Expand(msa) != eslOK) esl_fatal("Expand failed"); /* expand by 2x in nseq */
3511 esl_msa_Destroy(msa);
3512
3513 msa = esl_msa_CreateDigital(abc, 16, 100); /* not growable */
3514 #ifdef eslTEST_THROWING
3515 if (esl_msa_Expand(msa) != eslEINVAL) esl_fatal("Expand should have failed but didn't"); /* should fail w/ EINVAL*/
3516 #endif /* eslTEST_THROWING*/
3517 esl_msa_Destroy(msa);
3518 esl_alphabet_Destroy(abc);
3519 return;
3520 }
3521
3522
3523 static void
3524 utest_CreateDigital(ESL_ALPHABET *abc)
3525 {
3526 char *msg = "CreateDigital() unit test failure";
3527 ESL_MSA *msa = NULL;
3528
3529 msa = esl_msa_CreateDigital(abc, 16, -1); /* nseq blocksize 16, growable */
3530 if (! (msa->flags & eslMSA_DIGITAL)) esl_fatal(msg);
3531 if (msa->ax == NULL) esl_fatal(msg);
3532 if (msa->aseq != NULL) esl_fatal(msg);
3533 if (esl_msa_Expand(msa) != eslOK) esl_fatal(msg);
3534 esl_msa_Destroy(msa);
3535
3536 msa = esl_msa_CreateDigital(abc, 16, 100); /* nseq=16, alen=100, not growable */
3537 #ifdef eslTEST_THROWING
3538 if (esl_msa_Expand(msa) != eslEINVAL) esl_fatal(msg); /* shouldn't grow */
3539 #endif
3540 esl_msa_Destroy(msa);
3541
3542 return;
3543 }
3544
3545
3546 static void
3547 utest_Digitize(ESL_ALPHABET *abc, char *filename)
3548 {
3549 char *msg = "Digitize() unit test failure";
3550 ESL_MSAFILE *mfp = NULL;
3551 ESL_MSA *msa = NULL;
3552 int c, i, pos;
3553
3554 /* Get ourselves a copy of the known alignment that we can muck with */
3555 if (esl_msafile_Open(NULL, filename, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3556 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3557 esl_msafile_Close(mfp);
3558
3559 /* Deliberately corrupt it with inval character in the middle */
3560 i = msa->nseq / 2;
3561 pos = msa->alen / 2;
3562 c = msa->aseq[i][pos];
3563 msa->aseq[i][pos] = '%';
3564 if (esl_msa_Digitize(abc, msa, NULL) != eslEINVAL) esl_fatal(msg); /* should detect corruption as normal error */
3565 msa->aseq[i][pos] = c; /* restore original */
3566 compare_to_known(msa);
3567 if (esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg); /* should be fine now */
3568 compare_to_known(msa);
3569
3570 esl_msa_Destroy(msa);
3571 return;
3572 }
3573
3574
3575 static void
3576 utest_Textize(ESL_ALPHABET *abc, char *filename)
3577 {
3578 char *msg = "Textize() unit test failure";
3579 ESL_MSAFILE *mfp = NULL;
3580 ESL_MSA *msa = NULL;
3581
3582 if (esl_msafile_Open(&abc, filename, NULL, eslMSAFILE_UNKNOWN, NULL, &mfp) != eslOK) esl_fatal(msg);
3583 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3584 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
3585 compare_to_known(msa);
3586
3587 esl_msafile_Close(mfp);
3588 esl_msa_Destroy(msa);
3589 return;
3590 }
3591
3592
3593 static void
3594 utest_SequenceSubset(ESL_MSA *m1)
3595 {
3596 char *msg = "SequenceSubset() unit test failure";
3597 ESL_MSA *m2 = NULL;
3598 int *useme = NULL;
3599 int i,j;
3600 int n2;
3601
3602 /* Make every other sequence (1,3..) get excluded from the subset */
3603 useme = malloc(m1->nseq * sizeof(int));
3604 for (i = 0, n2 = 0; i < m1->nseq; i++)
3605 if (i%2 == 0) { useme[i] = TRUE; n2++; }
3606 else useme[i] = FALSE;
3607
3608 if (esl_msa_SequenceSubset(m1, useme, &m2) != eslOK) esl_fatal(msg);
3609 if (m2->nseq != n2) esl_fatal(msg);
3610
3611 for (i = 0, j = 0; i < m1->nseq; i++)
3612 {
3613 if (useme[i])
3614 {
3615 if (strcmp(m1->sqname[i], m2->sqname[j]) != 0) esl_fatal(msg);
3616 if (! (m1->flags & eslMSA_DIGITAL) && (strcmp(m1->aseq[i], m2->aseq[j]) != 0)) esl_fatal(msg);
3617
3618 if ( (m1->flags & eslMSA_DIGITAL) && memcmp(m1->ax[i], m2->ax[j], sizeof(ESL_DSQ) * (m1->alen+2)) != 0) esl_fatal(msg);
3619 j++;
3620 }
3621 }
3622 esl_msa_Destroy(m2);
3623 free(useme);
3624 return;
3625 }
3626
3627 static void
3628 utest_MinimGaps(char *tmpfile)
3629 {
3630 char *msg = "MinimGaps() unit test failure";
3631 ESL_MSAFILE *mfp = NULL;
3632 ESL_MSA *msa = NULL;
3633 ESL_ALPHABET *abc = NULL;
3634
3635 if (esl_msafile_Open(NULL, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3636 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3637 esl_msafile_Close(mfp);
3638 if (esl_msa_MinimGaps(msa, NULL, "-~", FALSE) != eslOK) esl_fatal(msg);
3639 if (msa->alen != 45) esl_fatal(msg); /* orig =47, with one all - column and one all ~ column */
3640 if (msa->aseq[0][11] != 'L') esl_fatal(msg); /* L shifted from column 13->12 */
3641 if (msa->aseq[0][18] != 'T') esl_fatal(msg); /* T shifted from column 21->19 */
3642 esl_msa_Destroy(msa);
3643
3644 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal(msg);
3645 if (esl_msafile_Open(&abc, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3646 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3647 esl_msafile_Close(mfp);
3648 if (esl_msa_MinimGaps(msa, NULL, NULL, FALSE) != eslOK) esl_fatal(msg);
3649 if (msa->alen != 45) esl_fatal(msg); /* orig =47, with one all - column and one all ~ column */
3650 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
3651 if (msa->aseq[0][11] != 'L') esl_fatal(msg); /* L shifted from column 13->12 */
3652 if (msa->aseq[0][18] != 'T') esl_fatal(msg); /* T shifted from column 21->19 */
3653 esl_msa_Destroy(msa);
3654 esl_alphabet_Destroy(abc);
3655 return;
3656 }
3657
3658 static void
3659 utest_NoGaps(char *tmpfile)
3660 {
3661 char *msg = "NoGaps() unit test failure";
3662 ESL_MSAFILE *mfp = NULL;
3663 ESL_MSA *msa = NULL;
3664 ESL_ALPHABET *abc = NULL;
3665
3666 if (esl_msafile_Open(NULL, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3667 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3668 esl_msafile_Close(mfp);
3669 if (esl_msa_NoGaps(msa, NULL, "-~") != eslOK) esl_fatal(msg);
3670 if (msa->alen != 40) esl_fatal(msg); /* orig =47, w/ 7 columns with gaps */
3671 if (msa->aseq[0][9] != 'L') esl_fatal(msg); /* L shifted from column 13->10 */
3672 if (msa->aseq[0][16] != 'T') esl_fatal(msg); /* T shifted from column 21->17 */
3673 if (msa->aseq[0][39] != 'Y') esl_fatal(msg); /* Y shifted from column 47->40 */
3674 esl_msa_Destroy(msa);
3675
3676 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal(msg);
3677 if (esl_msafile_Open(&abc, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3678 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3679 esl_msafile_Close(mfp);
3680 if (esl_msa_NoGaps(msa, NULL, NULL) != eslOK) esl_fatal(msg);
3681 if (msa->alen != 40) esl_fatal(msg); /* orig =47, with one all - column and one all ~ column */
3682 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
3683 if (msa->aseq[0][9] != 'L') esl_fatal(msg); /* L shifted from column 13->10 */
3684 if (msa->aseq[0][16] != 'T') esl_fatal(msg); /* T shifted from column 21->17 */
3685 if (msa->aseq[0][39] != 'Y') esl_fatal(msg); /* Y shifted from column 47->40 */
3686 esl_msa_Destroy(msa);
3687 esl_alphabet_Destroy(abc);
3688 return;
3689 }
3690
3691
3692
3693 static void
3694 utest_MarkFragments(void)
3695 {
3696 char msg[] = "esl_msa MarkFragments utest failed";
3697 ESL_BITFIELD *fragassign = NULL;
3698 ESL_ALPHABET *abc = esl_alphabet_Create(eslRNA);
3699 int i;
3700 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n"
3701 "seq1 AAAAAAAAAAAAAAAAAAAA\n"
3702 "seq2 .........AAAAAAAAAAA\n"
3703 "seq3 ..........AAAAAAAAAA\n"
3704 "seq4 ...........AAAAAAAAA\n"
3705 "//\n", eslMSAFILE_STOCKHOLM);
3706
3707 while (1) // first pass: text mode. second pass: digital mode.
3708 {
3709 /* At fragthresh of 0.5, seqs with aspan/alen >= 10/20 cols are "full length"
3710 * ... that's seq1, seq2, seq3.
3711 */
3712 if ( esl_msa_MarkFragments(msa, 0.5, &fragassign) != eslOK) esl_fatal(msg);
3713 if ( esl_bitfield_IsSet(fragassign, 0)) esl_fatal(msg);
3714 if ( esl_bitfield_IsSet(fragassign, 1)) esl_fatal(msg);
3715 if ( esl_bitfield_IsSet(fragassign, 2)) esl_fatal(msg);
3716 if (!esl_bitfield_IsSet(fragassign, 3)) esl_fatal(msg);
3717 esl_bitfield_Destroy(fragassign);
3718
3719 /* At fragthresh of 0, all seqs are "full length" */
3720 if ( esl_msa_MarkFragments(msa, 0., &fragassign) != eslOK) esl_fatal(msg);
3721 for (i = 0; i < msa->nseq; i++)
3722 if (esl_bitfield_IsSet(fragassign, i)) esl_fatal(msg);
3723 esl_bitfield_Destroy(fragassign);
3724
3725 /* At fragthresh of 1, only seq1 is "full length" */
3726 if ( esl_msa_MarkFragments(msa, 1.0, &fragassign) != eslOK) esl_fatal(msg);
3727 if ( esl_bitfield_IsSet(fragassign, 0)) esl_fatal(msg);
3728 for (i = 1; i < msa->nseq; i++)
3729 if (! esl_bitfield_IsSet(fragassign, i)) esl_fatal(msg);
3730 esl_bitfield_Destroy(fragassign);
3731
3732 if (msa->flags & eslMSA_DIGITAL) break;
3733 if ( esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg);
3734 }
3735
3736 esl_alphabet_Destroy(abc);
3737 esl_msa_Destroy(msa);
3738 }
3739
3740 static void
3741 utest_SymConvert(char *tmpfile)
3742 {
3743 char *msg = "SymConvert() unit test failure";
3744 ESL_MSAFILE *mfp = NULL;
3745 ESL_MSA *msa = NULL;
3746 ESL_ALPHABET *abc = NULL;
3747
3748 if (esl_msafile_Open(NULL, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3749 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3750 esl_msafile_Close(mfp);
3751
3752 /* many->one version */
3753 if (esl_msa_SymConvert(msa, "VWY", "-") != eslOK) esl_fatal(msg); /* 6 columns convert to all-gap: now 8/47 */
3754 if (esl_msa_MinimGaps(msa, NULL, "-~", FALSE) != eslOK) esl_fatal(msg); /* now we're 39 columns long */
3755 if (msa->alen != 39) esl_fatal(msg);
3756
3757 /* many->many version */
3758 if (esl_msa_SymConvert(msa, "DEF", "VWY") != eslOK) esl_fatal(msg);
3759 if (msa->aseq[0][4] != 'V') esl_fatal(msg);
3760 if (msa->aseq[0][5] != 'W') esl_fatal(msg);
3761 if (msa->aseq[0][23] != 'Y') esl_fatal(msg); /* F in orig col 29; -5; converted to Y */
3762
3763 /* bad calls */
3764 #ifdef eslTEST_THROWING
3765 if (esl_msa_SymConvert(msa, "XXX", "XX") != eslEINVAL) esl_fatal(msg); /* check for clean fail on mismatched args */
3766 #endif
3767 esl_msa_Destroy(msa);
3768
3769 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal(msg);
3770 if (esl_msafile_Open(&abc, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3771 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal(msg);
3772 esl_msafile_Close(mfp);
3773 #ifdef eslTEST_THROWING
3774 if (esl_msa_SymConvert(msa, "Tt", "Uu") != eslEINVAL) esl_fatal(msg); /* must cleanly fail on digital mode msa */
3775 #endif
3776 esl_msa_Destroy(msa);
3777 esl_alphabet_Destroy(abc);
3778 return;
3779 }
3780
3781 /* Exercise a boundary case: zero length MSA (alen=0) */
3782 /* Given an input *digital* MSA as a starting point, we clone it,
3783 * column subset it to zero length, then make sure that
3784 * various MSA functions operate correctly on it;
3785 * then we textize it and test it in text mode; then we
3786 * digitize it again, and throw it away.
3787 * (The input <msa> is unchanged.)
3788 */
3789 static void
3790 utest_ZeroLengthMSA(const char *tmpfile)
3791 {
3792 char *msg = "zero length msa unit test failed";
3793 ESL_ALPHABET *abc = NULL;
3794 ESL_MSAFILE *mfp = NULL;
3795 ESL_MSA *z1 = NULL;
3796 ESL_MSA *z2 = NULL;
3797 ESL_MSA *z3 = NULL;
3798 int *useme = NULL;
3799 int nuseme = 0;
3800 int i;
3801 char errbuf[eslERRBUFSIZE];
3802
3803 /* Read a text mode alignment from the tmpfile */
3804 if (esl_msafile_Open(NULL, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3805 if (esl_msafile_Read(mfp, &z1) != eslOK) esl_fatal(msg);
3806 esl_msafile_Close(mfp);
3807
3808 /* make an alen=0 text alignment by column subsetting */
3809 nuseme = ESL_MAX(z1->alen, z1->nseq);
3810 if ((useme = malloc(sizeof(int) * nuseme)) == NULL) esl_fatal(msg);
3811 for (i = 0; i < z1->alen; i++) useme[i] = 0;
3812 if (esl_msa_ColumnSubset(z1, errbuf, useme) != eslOK) esl_fatal(msg);
3813
3814 /* These should all no-op if alen=0*/
3815 if (esl_msa_MinimGaps(z1, NULL, "-", FALSE) != eslOK) esl_fatal(msg);
3816 if (esl_msa_NoGaps(z1, NULL, "-") != eslOK) esl_fatal(msg);
3817 if (esl_msa_SymConvert(z1,"RY","NN") != eslOK) esl_fatal(msg);
3818
3819 /* test sequence subsetting by removing the first sequence */
3820 for (i = 1; i < z1->nseq; i++) useme[i] = 1;
3821 if (esl_msa_SequenceSubset(z1, useme, &z2) != eslOK) esl_fatal(msg);
3822 esl_msa_Destroy(z1);
3823 z1 = NULL; // we may reuse z1 below.
3824 /* keep z2; we'll compare it to z3 in the end */
3825
3826 /* Now read the same alignment, in digital mode */
3827 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal(msg);
3828 if (esl_msafile_Open(&abc, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal(msg);
3829 if (esl_msafile_Read(mfp, &z1) != eslOK) esl_fatal(msg);
3830 esl_msafile_Close(mfp);
3831
3832 /* Now make an alen=0 alignment in digital mode */
3833 for (i = 0; i < z1->alen; i++) useme[i] = 0;
3834 if (esl_msa_ColumnSubset(z1, errbuf, useme) != eslOK) esl_fatal(msg);
3835
3836 /* again these should all no-op if alen=0*/
3837 if (esl_msa_MinimGaps(z1, NULL, NULL, FALSE) != eslOK) esl_fatal(msg);
3838 if (esl_msa_NoGaps(z1, NULL, NULL) != eslOK) esl_fatal(msg);
3839 /* SymConvert throws EINVAL on a digital mode alignment */
3840
3841 /* test sequence subsetting by removing the first sequence */
3842 for (i = 1; i < z1->nseq; i++) useme[i] = 1;
3843 if (esl_msa_SequenceSubset(z1, useme, &z3) != eslOK) esl_fatal(msg);
3844 esl_msa_Destroy(z1);
3845
3846 if ((z1 = esl_msa_Clone(z3)) == NULL) esl_fatal(msg); /* z1 is now alen=0, digital */
3847 if (esl_msa_Textize(z3) != eslOK) esl_fatal(msg); /* convert z3 back to text mode */
3848 if (esl_msa_Compare(z2, z3) != eslOK) esl_fatal(msg); /* compare in text mode */
3849 if (esl_msa_Digitize(abc, z2, NULL) != eslOK) esl_fatal(msg); /* now z2 is digital */
3850 if (esl_msa_Compare(z1, z2) != eslOK) esl_fatal(msg); /* compare digital mode z1,z2 */
3851
3852 esl_alphabet_Destroy(abc);
3853 esl_msa_Destroy(z1);
3854 esl_msa_Destroy(z3);
3855
3856 esl_msa_Destroy(z2);
3857 free(useme);
3858 }
3859
3860 static void
3861 utest_Sample(ESL_RANDOMNESS *rng)
3862 {
3863 char msg[] = "esl_msa sample unit test failed";
3864 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
3865 ESL_MSA *msa = NULL;
3866
3867 if (esl_msa_Sample(rng, abc, 100, 100, &msa) != eslOK) esl_fatal(msg);
3868 if (esl_msa_Validate(msa, NULL) != eslOK) esl_fatal(msg);
3869
3870 esl_msa_Destroy(msa);
3871 esl_alphabet_Destroy(abc);
3872 }
3873
3874
3875 #endif /*eslMSA_TESTDRIVE*/
3876 /*------------------------ end of unit tests --------------------------------*/
3877
3878
3879 /*****************************************************************************
3880 * 7. Test driver
3881 *****************************************************************************/
3882 #ifdef eslMSA_TESTDRIVE
3883 #include <stdlib.h>
3884 #include <stdio.h>
3885
3886 #include "easel.h"
3887 #include "esl_alphabet.h"
3888 #include "esl_getopts.h"
3889 #include "esl_keyhash.h"
3890 #include "esl_random.h"
3891 #include "esl_randomseq.h"
3892 #include "esl_ssi.h"
3893 #include "esl_msa.h"
3894
3895 static ESL_OPTIONS options[] = {
3896 /* name type default env range togs reqs incomp help docgrp */
3897 {"-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0},
3898 {"-s", eslARG_INT, "0", NULL, NULL, NULL, NULL, NULL, "set random number seed to <n>", 0},
3899 { 0,0,0,0,0,0,0,0,0,0},
3900 };
3901 static char usage[] = "[-options]";
3902 static char banner[] = "test driver for msa module";
3903
3904 int
3905 main(int argc, char **argv)
3906 {
3907 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
3908 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
3909 ESL_MSAFILE *mfp = NULL;
3910 ESL_MSA *msa = NULL;
3911 FILE *fp = NULL;
3912 char tmpfile[16] = "esltmpXXXXXX"; /* tmpfile template */
3913 ESL_ALPHABET *abc = NULL;
3914
3915 fprintf(stderr, "## %s\n", argv[0]);
3916 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
3917
3918 #ifdef eslTEST_THROWING
3919 esl_exception_SetHandler(&esl_nonfatal_handler);
3920 #endif
3921
3922 /* Create a known Stockholm test alignment in a tempfile.
3923 */
3924 if (esl_tmpfile_named(tmpfile, &fp) != eslOK) esl_fatal("failed to create tmpfile");
3925 write_known_msa(fp);
3926 fclose(fp);
3927
3928 /* Read it back in for use in tests.
3929 */
3930 if (esl_msafile_Open(NULL, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal("Failed to open MSA tmp file");
3931 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal("Failed to read MSA tmp file");
3932 esl_msafile_Close(mfp);
3933
3934 /* Unit tests
3935 */
3936 utest_Create();
3937 utest_Sizeof(rng);
3938 utest_Destroy();
3939 utest_Expand();
3940 utest_SequenceSubset(msa);
3941 utest_MinimGaps(tmpfile);
3942 utest_NoGaps(tmpfile);
3943 utest_MarkFragments();
3944 utest_SymConvert(tmpfile);
3945 utest_ZeroLengthMSA(tmpfile);
3946 utest_Sample(rng);
3947
3948 esl_msa_Destroy(msa);
3949
3950 if ((abc = esl_alphabet_Create(eslAMINO)) == NULL) esl_fatal("alphabet creation failed");
3951 if (esl_msafile_Open(&abc, tmpfile, NULL, eslMSAFILE_STOCKHOLM, NULL, &mfp) != eslOK) esl_fatal("MSA digital open failed");
3952 if (esl_msafile_Read(mfp, &msa) != eslOK) esl_fatal("MSA digital read failed");
3953 esl_msafile_Close(mfp);
3954
3955 utest_CreateDigital(abc);
3956 utest_Digitize(abc, tmpfile);
3957 utest_Textize(abc, tmpfile);
3958
3959 fprintf(stderr, "# status = ok\n");
3960
3961 esl_msa_Destroy(msa);
3962 esl_alphabet_Destroy(abc);
3963 esl_randomness_Destroy(rng);
3964 esl_getopts_Destroy(go);
3965 remove(tmpfile);
3966 exit(0); /* success */
3967 }
3968 #endif /*eslMSA_TESTDRIVE*/
3969 /*-------------------- end of test driver ---------------------*/
3970