Debian Codegraph @

easel/esl_msaweight.c

raw symbols SCIP
1 /* Sequence weighting algorithms.
2 *
3 * Implementations of ad hoc sequence weighting algorithms for multiple
4 * sequence alignments:
5 * PB weights: Henikoff and Henikoff, JMB 243:574-578, 1994.
6 * GSC weights: Gerstein et al., JMB 236:1067-1078, 1994.
7 * BLOSUM weights: Henikoff and Henikoff, PNAS 89:10915-10919, 1992.
8 *
9 * and also, filtering an alignment to remove "redundant" sequences >=
10 * a given pairwise % identity cutoff, which is sort of a weighting
11 * method.
12 *
13 * The most work has gone into PB weights, the default in HMMER and
14 * Infernal. PB weights are the only one of the weighting schemes that
15 * scales practically to deep alignments.
16 *
17 * Contents:
18 * 1. Position-based (PB) weighting
19 * 2. Optional config, stats collection for advanced PB weighting
20 * 3. Other weighting algorithms (GSC, BLOSUM)
21 * 4. %id filtering
22 * 5. Benchmark
23 * 6. Stats driver
24 * 7. Unit tests
25 * 8. Test driver
26 * 9. Example
27 */
28 #include <esl_config.h>
29
30 #include <math.h>
31 #include <string.h>
32 #include <ctype.h>
33
34 #include "easel.h"
35 #include "esl_alphabet.h"
36 #include "esl_distance.h"
37 #include "esl_dmatrix.h"
38 #include "esl_matrixops.h"
39 #include "esl_msa.h"
40 #include "esl_msacluster.h"
41 #include "esl_quicksort.h"
42 #include "esl_tree.h"
43 #include "esl_vectorops.h"
44
45 #include "esl_msaweight.h"
46
47
48 /*****************************************************************
49 * 1. Position-based (PB) weighting
50 *****************************************************************/
51 /* Mar 2019: PB weighting algorithm revised to use only consensus
52 * columns, not all columns. HMMER benchmarks show improved
53 * discrimination especially with deep alignments. Also optimized
54 * order of access, trading off O(K) -> O(KL) memory in return for
55 * ~40x acceleration. These changes were only introduced for digital
56 * mode alignments; text mode PB algorithm remains as it was.
57 */
58
59 static int consensus_by_rf (const ESL_MSA *msa, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat);
60 static int consensus_by_sample(const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, int **ct, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat);
61 static int consensus_by_all (const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, int **ct, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat);
62 static int collect_counts (const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, const int *conscols, int ncons, int **ct, ESL_MSAWEIGHT_DAT *dat);
63 static int msaweight_PB_txt(ESL_MSA *msa);
64
65 /* Function: esl_msaweight_PB()
66 * Synopsis: PB (position-based) weights.
67 *
68 * Purpose: Given a multiple alignment <msa>, calculate sequence
69 * weights according to the position-based weighting
70 * algorithm (Henikoff and Henikoff, JMB 243:574-578,
71 * 1994). These weights are stored internally in the <msa>
72 * object, replacing any weights that may have already been
73 * there. Weights are $\geq 0$ and they sum to <msa->nseq>.
74 *
75 * The Henikoffs' algorithm is defined for ungapped
76 * alignments. It does not give rules for dealing with
77 * gaps, nor for degenerate residue symbols. The rule here
78 * is to ignore these, and moreover (in digital mode
79 * alignments, in order to deal with deep gappy alignments)
80 * to only consider alignment columns that are "consensus"
81 * (defined below). This means that longer sequences
82 * initially get more weight; hence we do a "double
83 * normalization" in which the weights are first divided by
84 * sequence length in canonical residues (to get the
85 * average weight per residue, to compensate for that
86 * effect), then normalized to sum to nseq.
87
88 * The <msa> may be in either digitized or text mode. The
89 * weighting algorithm is subtly different depending on
90 * this mode. Digital mode is preferred. The digital mode
91 * algorithm handles deep gappy alignments better (it only
92 * considers consensus columns, not all columns), it deals
93 * with degenerate residue symbols (by ignoring them, like
94 * it ignores gaps), and it's much faster. In text mode,
95 * the algorithm simply uses the 26 letters as "residues"
96 * (case-insensitively), and ignores all other residues as
97 * gaps.
98 *
99 * PB weights require $O(NL)$ time and $O(LK)$ memory, for
100 * an alignment of $L$ columns, $N$ sequences, and alphabet
101 * size $K$.
102 *
103 * Consensus columns (for the digital alignment version)
104 * are determined as follows:
105 *
106 * 1. if the MSA has RF consensus column annotation, use it.
107 *
108 * 2. else, use HMMER's rules (fragthresh, symfrac):
109 * - define sequence fragments as those with aligned
110 * lengths where fractional span (l-r+1)/L < fragthresh
111 * for leftmost residue position l and rightmost r;
112 * - count % residue occupancy per column ignoring
113 * external gaps for fragments;
114 * - define consensus columns as those with $\geq$
115 * symfrac residue occupancy.
116 * Defaults are fragthresh = 0.5, symfrac = 0.5.
117 *
118 * 3. if all else fails, use all columns.
119 *
120 * Additionally, at step 2, if the alignment is very deep
121 * (>50000 sequences by default), we attempt to define
122 * consensus columns from a statistical sample (of 10,000
123 * seqs by default). This is a speed optimization. It can
124 * fail in a pathological case where the alignment contains
125 * a ridiculous number of fragments piled up on one
126 * subsequence. (Some DNA repeats can be this way.) If we
127 * get >5000 fragments in the sample (by default), we use
128 * all sequences, not a subsample.
129 *
130 * All the parameters mentioned with default parameters can
131 * be changed using the <esl_msaweight_PB_adv()> "advanced"
132 * version.
133 *
134 * Using RF-annotated consensus columns by default is not
135 * always desirable. In HMMER and Infernal, default "fast"
136 * model construction may define a different set of
137 * consensus columns than Easel does, which means that the
138 * same MSA can give different parameterizations, depending
139 * on whether that MSA has RF annotation or not. We decided
140 * this is undesirable [HMMER iss #180]. Both HMMER and
141 * Infernal use esl_msaweight_PB_adv(), using a
142 * ESL_MSAWEIGHT_CFG that sets ignore_rf to TRUE in
143 * default, FALSE with --hand.
144 *
145 * Returns: <eslOK> on success. <msa->wgt[]> now contains weights for
146 * each sequence. <eslMSA_HASWGTS> flag is raised in
147 * <msa->flags>.
148 *
149 * Throws: <eslEMEM> on allocation error, in which case <msa> is
150 * returned unmodified.
151 *
152 * Xref: [Henikoff94b]; squid::weight.c::PositionBasedWeights().
153 */
154 int
155 esl_msaweight_PB(ESL_MSA *msa)
156 {
157 if (msa->flags & eslMSA_DIGITAL) return esl_msaweight_PB_adv(NULL, msa, NULL);
158 else return msaweight_PB_txt(msa);
159 }
160
161
162 /* Function: esl_msaweight_PB_adv()
163 * Synopsis: Advanced version of PB weights; digital MSAs only.
164 * Incept: SRE, Wed 20 Mar 2019
165 *
166 * Purpose: Same as <esl_msaweight_PB()> but only takes digital-mode
167 * MSAs, and can optionally take customized parameters
168 * <cfg>, and optionally collect data about the computation
169 * in <dat>.
170 *
171 * Args: cfg - optional customized parameters, or NULL to use defaults.
172 * msa - MSA to weight; weights stored in msa->wgt[]
173 * dat - optional data collection, or NULL.
174 *
175 * Returns: <eslOK> on success. <msa->wgt[]> now contains weights for
176 * each sequence. <eslMSA_HASWGTS> flag is raised in
177 * <msa->flags>. <dat>, if provided, contains data about
178 * stuff that happened during the weight computation.
179 *
180 * Throws: (no abnormal error conditions)
181 */
182 int
183 esl_msaweight_PB_adv(const ESL_MSAWEIGHT_CFG *cfg, ESL_MSA *msa, ESL_MSAWEIGHT_DAT *dat)
184 {
185 int ignore_rf = (cfg? cfg->ignore_rf : eslMSAWEIGHT_IGNORE_RF); // default is FALSE: use RF annotation as consensus definition, if RF is present
186 int allow_samp = (cfg? cfg->allow_samp : eslMSAWEIGHT_ALLOW_SAMP); // default is TRUE: allow subsampling speed optimization
187 int sampthresh = (cfg? cfg->sampthresh : eslMSAWEIGHT_SAMPTHRESH); // if nseq > sampthresh, try to determine consensus on a subsample of seqs
188 int **ct = NULL; // matrix of symbol counts in each column. ct[apos=(0).1..alen][a=0..Kp-1]
189 int *r = NULL; // number of different canonical residues used in each consensus column. r[j=0..ncons-1]
190 int *conscols = NULL; // list of consensus column indices [0..ncons-1]
191 int ncons = 0; // number of consensus column indices in <conscols> list
192 int idx, apos, j, a; // indices over sequences, original columns, consensus columns, symbols
193 int rlen; // number of canonical residues in a seq; used for first PB normalization
194 int status = eslOK;
195
196 /* Contract checks & bailouts */
197 ESL_DASSERT1(( msa->nseq >= 1 && msa->alen >= 1));
198 ESL_DASSERT1(( msa->flags & eslMSA_DIGITAL ));
199 if (msa->nseq == 1) { msa->wgt[0] = 1.0; return eslOK; }
200
201 /* Allocations */
202 ct = esl_mat_ICreate( msa->alen+1, msa->abc->Kp ); // (0).1..alen; 0..Kp-1
203 ESL_ALLOC(conscols, sizeof(int) * msa->alen);
204
205 /* Determine consensus columns early if we can. (ncons stays = 0 if neither way gets used.) */
206 if (! ignore_rf && msa->rf) consensus_by_rf(msa, conscols, &ncons, dat);
207 else if (allow_samp && msa->nseq > sampthresh) consensus_by_sample(cfg, msa, ct, conscols, &ncons, dat);
208
209 /* Collect count matrix ct[apos][a] (either all columns, or if we have consensus already, only consensus columns) */
210 collect_counts(cfg, msa, conscols, ncons, ct, dat);
211
212 /* If we still haven't determined consensus columns yet, do it now, using <ct> */
213 if (! ncons) consensus_by_all(cfg, msa, ct, conscols, &ncons, dat);
214
215 /* If we *still* have no consensus columns, that's pretty pathological -- use 'em all */
216 if (! ncons)
217 {
218 for (apos = 1; apos <= msa->alen; apos++) conscols[apos-1] = apos;
219 ncons = msa->alen;
220 if (dat) dat->cons_allcols = TRUE;
221 }
222
223 /* Count how many different canonical residues are used in each consensus column: r[j] */
224 ESL_ALLOC(r, sizeof(int) * ncons);
225 esl_vec_ISet(r, ncons, 0);
226 for (j = 0; j < ncons; j++)
227 {
228 apos = conscols[j];
229 for (a = 0; a < msa->abc->K; a++)
230 if (ct[apos][a] > 0) r[j]++;
231 }
232
233 /* Bump sequence weights using PB weighting rule */
234 esl_vec_DSet(msa->wgt, msa->nseq, 0.0);
235 for (idx = 0; idx < msa->nseq; idx++)
236 {
237 rlen = 0;
238 for (j = 0; j < ncons; j++)
239 {
240 apos = conscols[j];
241 a = msa->ax[idx][apos];
242 msa->wgt[idx] += (a >= msa->abc->K ? 0. : 1. / (double) (r[j] * ct[apos][a])); // <= This is the PB weight rule.
243 rlen += (a >= msa->abc->K ? 0 : 1); // (ternary is faster than an if)
244 }
245 if (rlen > 0) msa->wgt[idx] /= (double) rlen; // first normalization, by unaligned seq length
246 }
247
248 /* Normalize weights to sum to N */
249 esl_vec_DNorm(msa->wgt, msa->nseq);
250 esl_vec_DScale(msa->wgt, msa->nseq, (double) msa->nseq);
251 msa->flags |= eslMSA_HASWGTS;
252
253 ERROR:
254 esl_mat_IDestroy(ct);
255 free(r);
256 if (dat) dat->ncons = ncons;
257 if (dat) dat->conscols = conscols; else free(conscols);
258 return status;
259 }
260
261 /* consensus_by_rf()
262 * Use RF annotation to define consensus columns.
263 *
264 * <conscols> is allocated for up to <msa->alen> indices of consensus columns.
265 * Upon return, it contains a list of indices, each 1..alen, and
266 * <ret_ncons> is the length of the list (the number of consensus cols).
267 * (1-based, not 0-, because it's a consensus for a digital mode alignment).
268 *
269 * Returns <eslOK> on success.
270 */
271 static int
272 consensus_by_rf(const ESL_MSA *msa, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat)
273 {
274 int ncons = 0;
275 int apos;
276
277 for (apos = 1; apos <= msa->alen; apos++)
278 {
279 if (esl_abc_CIsGap(msa->abc, msa->rf[apos-1])) continue;
280 conscols[ncons] = apos;
281 ncons++;
282 }
283 if (dat) dat->cons_by_rf = TRUE;
284 *ret_ncons = ncons;
285 return eslOK;
286 }
287
288 /* consensus_by_sample()
289 * Use a statistical sample of seqs to define consensus columns.
290 *
291 * On deep alignments, it's usually overkill to look at all sequences
292 * just to determine which columns to call consensus. We can speed the
293 * decision up by looking at a subsample instead.
294 *
295 * We want results to be reproducible; by default, the random number
296 * generator (used for taking the sample) uses a fixed seed.
297 *
298 * We have to watch out for a pathological case where there could be a
299 * ridiculous number of fragments piled up on just one piece of the
300 * alignment. This can happen with some DNA repeat elements, for
301 * example. If the sample contains too many fragments, reject this
302 * approach, the caller will have to determine consensus on all
303 * sequences instead.
304 *
305 * In: cfg - optional configuration options, or NULL to use all defaults
306 * msa - MSA to determine consensus for
307 * ct - allocated space for [(0).1..alen][0..Kp-1] observed symbol counts; contents irrelevant
308 * conscols - allocated space for up to <alen> consensus column indices
309 *
310 * Out: ct - [apos=1..alen][a=0..Kp-1] are counts of observed symbol <a> in column <alen> in sample. [0][] are all 0's.
311 * conscols - [0..ncons-1] list of consensus column indices 1..alen
312 * ncons - number of consensus columns in <conscols>, or 0 if consensus determination was rejected or failed
313 *
314 * Returns <eslOK> on success.
315 *
316 * Returns <eslFAIL> if there were too many fragments. Now <ct> still has the counts
317 * observed in the sample, but <conscols> has no valid indices and <ncons> is 0.
318 *
319 * Throws <eslEMEM> on allocation failure.
320 */
321 static int
322 consensus_by_sample(const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, int **ct, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat)
323 {
324 float fragthresh = (cfg? cfg->fragthresh : eslMSAWEIGHT_FRAGTHRESH);
325 float symfrac = (cfg? cfg->symfrac : eslMSAWEIGHT_SYMFRAC);
326 int nsamp = (cfg? cfg->nsamp : eslMSAWEIGHT_NSAMP);
327 int maxfrag = (cfg? cfg->maxfrag : eslMSAWEIGHT_MAXFRAG);
328 ESL_RAND64 *rng = (cfg? esl_rand64_Create(cfg->seed) : esl_rand64_Create(eslMSAWEIGHT_RNGSEED)); // fixed seed for default reproducibility
329 int64_t *sampidx = NULL;
330 int nfrag = 0; // number of fragments in sample
331 int ncons = 0; // number of consensus columns defined
332 int tot; // total # of residues+gaps in a column
333 int minspan;
334 int apos, a;
335 int lpos, rpos;
336 int i, idx;
337 int status = eslOK;
338
339 ESL_ALLOC(sampidx, sizeof(int64_t) * nsamp);
340 esl_mat_ISet(ct, msa->alen+1, msa->abc->Kp, 0);
341 if (dat) dat->seed = esl_rand64_GetSeed(rng);
342
343 esl_rand64_Deal(rng, nsamp, (int64_t) msa->nseq, sampidx); // <sampidx> is now an ordered list of <nsamp> indices in range 0..nseq-1
344
345 minspan = (int) ceil( fragthresh * (float) msa->alen ); // define alispan as aligned length from first to last non-gap. If alispan < minspan, define seq as a fragment
346 for (i = 0; i < nsamp; i++)
347 {
348 idx = (int) sampidx[i];
349
350 for (lpos = 1; lpos <= msa->alen; lpos++) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][lpos])) break;
351 for (rpos = msa->alen; rpos >= 1; rpos--) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][rpos])) break;
352 if (rpos - lpos + 1 < minspan) nfrag++; else { lpos = 1; rpos = msa->alen; }
353
354 for (apos = lpos; apos <= rpos; apos++)
355 ct[apos][msa->ax[idx][apos]]++;
356 }
357
358 if (dat) dat->samp_nfrag = nfrag;
359
360 if (nfrag <= maxfrag)
361 {
362 for (apos = 1; apos <= msa->alen; apos++)
363 {
364 for (tot = 0, a = 0; a < msa->abc->Kp-2; a++) tot += ct[apos][a]; // i.e. <tot> symbols over esl_abc_XIsResidue() || esl_abc_XIsGap(); inclusive of degeneracies, exclusive of missing | nonresidue.
365 if ( ((float) ct[apos][msa->abc->K] / (float) tot) < symfrac) // This is the rule for determining a consensus column: if the frequency of residues/(residues+gaps) >= symfrac
366 conscols[ncons++] = apos;
367 }
368 if (dat) dat->cons_by_sample = TRUE;
369 }
370 else
371 {
372 if (dat) dat->rejected_sample = TRUE;
373 status = eslFAIL;
374 }
375
376 ERROR:
377 free(sampidx);
378 esl_rand64_Destroy(rng);
379 *ret_ncons = ncons; // will be 0 if we saw too many fragments.
380 return status;
381 }
382
383
384 /* consensus_by_all()
385 * Use counts from all sequences to determine consensus.
386 *
387 * If we weren't able to define a consensus before collecting observed
388 * counts in just those columns, then we had to collect observed
389 * counts on all columns, and now we define the consensus.
390 *
391 * Because we do this from counts, not the MSA, <msa> here is only
392 * used for dimensions <alen> and <Kp>.
393 *
394 * Returns <eslOK> on success.
395 *
396 * Obscure C note: <ct> is input only here, so it might look like
397 * you can declare it <const int **ct>, but don't. <const> syntax
398 * is arcane and confusing with double indirection.
399 */
400 static int
401 consensus_by_all(const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, int **ct, int *conscols, int *ret_ncons, ESL_MSAWEIGHT_DAT *dat)
402 {
403 float symfrac = (cfg? cfg->symfrac : eslMSAWEIGHT_SYMFRAC);
404 int ncons = 0;
405 int apos;
406 int tot;
407 int a;
408
409 for (apos = 1; apos <= msa->alen; apos++)
410 {
411 tot = 0;
412 for (a = 0; a < msa->abc->Kp-2; a++) // i.e. over esl_abc_XIsResidue() || esl_abc_XIsGap()
413 tot += ct[apos][a];
414 if ( ((float) ct[apos][msa->abc->K] / (float) tot) < symfrac)
415 conscols[ncons++] = apos;
416 }
417 if (dat) dat->cons_by_all = TRUE;
418 *ret_ncons = ncons;
419 return eslOK;
420 }
421
422
423 /* collect_counts()
424 * Collect a matrix of observed symbol counts in each column: ct[apos=1..alen][a=0..Kp-1].
425 * - use HMMER's fragment-definition rule, and don't count external gaps of fragments.
426 * - This matrix is O(KL) for alignment length L, alphabet size K.
427 * It's responsible for the asymptotic memory complexity of PB weights.
428 * - "What if I've already marked fragments", you say (maybe in hmmbuild), "can I
429 * save some time here?" Not really. Even if you know a seq is a fragment, you'd
430 * need to run the lpos and rpos loops to find its start/end.
431 * - If we already know what the consensus columns are, only collect counts in them,
432 * leaving counts in nonconsensus columns zero. This is a time optimization.
433 */
434 static int
435 collect_counts(const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, const int *conscols, int ncons, int **ct, ESL_MSAWEIGHT_DAT *dat)
436 {
437 float fragthresh = (cfg? cfg->fragthresh : eslMSAWEIGHT_FRAGTHRESH); // seq is fragment if (length from 1st to last aligned residue)/alen < fragthresh (i.e. span < minspan)
438 int minspan = (int) ceil( fragthresh * (float) msa->alen ); // precalculated span length threshold using <fragthresh>
439 int lpos, rpos; // leftmost, rightmost aligned residue (1..alen)
440 int idx, apos, j;
441
442
443 esl_mat_ISet(ct, msa->alen+1, msa->abc->Kp, 0);
444 for (idx = 0; idx < msa->nseq; idx++)
445 {
446 // HMMER mark_fragments() rule. Count "span" from first to last aligned residue. If alispan/alen < fragthresh, it's a fragment.
447 for (lpos = 1; lpos <= msa->alen; lpos++) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][lpos])) break;
448 for (rpos = msa->alen; rpos >= 1; rpos--) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][rpos])) break;
449 // L=0 seq or alen=0? then lpos == msa->alen+1, rpos == 0 => lpos > rpos. rpos-lpos-1 <= 0 but test below still works.
450 if (rpos - lpos + 1 >= minspan) { lpos = 1; rpos = msa->alen; } else if (dat) dat->all_nfrag++; // full len seqs count cols 1..alen; fragments only count lpos..rpos.
451
452 if (ncons) // if we have consensus columns already, only count symbols in those columns (faster)...
453 {
454 for (j = 0; j < ncons && conscols[j] <= rpos; j++)
455 {
456 apos = conscols[j];
457 if (apos < lpos) continue;
458 ct[apos][msa->ax[idx][apos]]++;
459 }
460 }
461 else // ... else, count symbols in all columns.
462 {
463 for (apos = lpos; apos <= rpos; apos++)
464 ct[apos][msa->ax[idx][apos]]++;
465 }
466 }
467 return eslOK;
468 }
469
470
471 /* msaweight_PB_txt()
472 * PB weighting for text-mode alignment.
473 *
474 * All columns are counted. Symbols [a-zA-Z] are counted as
475 * "residues"; anything else is ignored.
476 *
477 * O(LN) time for alignment length L, number of sequences N.
478 * O(K) memory for K=26 residues.
479 *
480 * You should use digital mode PB weights if at all possible. They're
481 * better (with improved methods for gappy alignments), faster
482 * (because the implementation is optimized for access patterns), and
483 * have more options for customization and monitoring (via the
484 * ESL_MSAWEIGHT_CFG and ESL_MSAWEIGHT_STATS optional objects).
485 */
486 static int
487 msaweight_PB_txt(ESL_MSA *msa)
488 {
489 int *ct = NULL; // counts of each residue observed in a column
490 int K = 26; // alphabet size. In text mode, we count [a-zA-z] as "residues"
491 int r; // number of different symbols observed in a column
492 int idx, apos, a, rlen;
493 int status = eslOK;
494
495 ESL_DASSERT1( (msa->nseq >= 1) );
496 ESL_DASSERT1( (msa->alen >= 1) );
497 ESL_DASSERT1( (! (msa->flags & eslMSA_DIGITAL )));
498 if (msa->nseq == 1) { msa->wgt[0] = 1.0; return eslOK; }
499
500 ESL_ALLOC(ct, sizeof(int) * K);
501 esl_vec_DSet(msa->wgt, msa->nseq, 0.0);
502
503 for (apos = 0; apos < msa->alen; apos++)
504 {
505 /* Collect # of letters A..Z (case insensitively) in this column, and total */
506 esl_vec_ISet(ct, K, 0.);
507 for (idx = 0; idx < msa->nseq; idx++)
508 if (isalpha((int) msa->aseq[idx][apos]))
509 ct[toupper((int) msa->aseq[idx][apos]) - 'A'] ++;
510 for (r = 0, a = 0; a < K; a++) if (ct[a] > 0) r++;
511
512 /* Bump weight on each seq by PB rule */
513 if (r > 0) {
514 for (idx = 0; idx < msa->nseq; idx++) {
515 if (isalpha((int) msa->aseq[idx][apos]))
516 msa->wgt[idx] += 1. /
517 (double) (r * ct[toupper((int) msa->aseq[idx][apos]) - 'A'] );
518 }
519 }
520 }
521
522 /* first normalization by # of residues counted in each seq */
523 for (idx = 0; idx < msa->nseq; idx++) {
524 for (rlen = 0, apos = 0; apos < msa->alen; apos++)
525 if (isalpha((int) msa->aseq[idx][apos])) rlen++;
526 if (rlen > 0) msa->wgt[idx] /= (double) rlen;
527 /* if rlen == 0 for this seq, its weight is still 0.0, as initialized. */
528 }
529
530 /* Make weights normalize up to nseq, and return. In pathological
531 * case where all wgts were 0 (no seqs contain any unambiguous
532 * residues), weights become 1.0.
533 */
534 esl_vec_DNorm(msa->wgt, msa->nseq);
535 esl_vec_DScale(msa->wgt, msa->nseq, (double) msa->nseq);
536 msa->flags |= eslMSA_HASWGTS;
537
538 ERROR:
539 free(ct);
540 return status;
541 }
542
543
544
545
546
547 /*****************************************************************
548 * 2. Optional config, stats collection for advanced PB weighting
549 *****************************************************************/
550
551 /* Function: esl_msaweight_cfg_Create()
552 * Synopsis: Create config options structure for PB weights, %id filter
553 * Incept: SRE, Thu 21 Mar 2019 [Drive By Truckers, Guns of Umpqua]
554 */
555 ESL_MSAWEIGHT_CFG *
556 esl_msaweight_cfg_Create(void)
557 {
558 ESL_MSAWEIGHT_CFG *cfg = NULL;
559 int status;
560
561 ESL_ALLOC(cfg, sizeof(ESL_MSAWEIGHT_CFG));
562
563 cfg->fragthresh = eslMSAWEIGHT_FRAGTHRESH;
564 cfg->symfrac = eslMSAWEIGHT_SYMFRAC;
565 cfg->ignore_rf = eslMSAWEIGHT_IGNORE_RF;
566 cfg->allow_samp = eslMSAWEIGHT_ALLOW_SAMP;
567 cfg->sampthresh = eslMSAWEIGHT_SAMPTHRESH;
568 cfg->nsamp = eslMSAWEIGHT_NSAMP;
569 cfg->maxfrag = eslMSAWEIGHT_MAXFRAG;
570 cfg->seed = eslMSAWEIGHT_RNGSEED;
571 cfg->filterpref = eslMSAWEIGHT_FILT_CONSCOVER;
572
573 ERROR:
574 return cfg;
575 }
576
577 /* Function: esl_msaweight_cfg_Destroy()
578 * Synopsis: Destroy an <ESL_MSAWEIGHT_CFG>
579 */
580 void
581 esl_msaweight_cfg_Destroy(ESL_MSAWEIGHT_CFG *cfg)
582 {
583 free(cfg);
584 }
585
586
587 /* Function: esl_msaweight_dat_Create()
588 * Synopsis: Create data collection structure for PB weighting
589 * Incept: SRE, Thu 21 Mar 2019
590 */
591 ESL_MSAWEIGHT_DAT *
592 esl_msaweight_dat_Create(void)
593 {
594 ESL_MSAWEIGHT_DAT *dat = NULL;
595 int status;
596
597 ESL_ALLOC(dat, sizeof(ESL_MSAWEIGHT_DAT));
598
599 dat->seed = eslMSAWEIGHT_RNGSEED;
600
601 dat->cons_by_rf = FALSE;
602 dat->cons_by_sample = FALSE;
603 dat->cons_by_all = FALSE;
604 dat->cons_allcols = FALSE;
605 dat->rejected_sample = FALSE;
606
607 dat->ncons = 0;
608 dat->conscols = NULL;
609
610 dat->all_nfrag = 0;
611 dat->samp_nfrag = 0;
612
613 ERROR:
614 return dat;
615 }
616
617 /* Function: esl_msaweight_dat_Reuse()
618 * Synopsis: Reuse an <ESL_MSAWEIGHT_DAT> structure.
619 */
620 int
621 esl_msaweight_dat_Reuse(ESL_MSAWEIGHT_DAT *dat)
622 {
623 if (dat->conscols) { free(dat->conscols); }
624 dat->seed = eslMSAWEIGHT_RNGSEED;
625 dat->cons_by_rf = FALSE;
626 dat->cons_by_sample = FALSE;
627 dat->cons_by_all = FALSE;
628 dat->cons_allcols = FALSE;
629 dat->rejected_sample = FALSE;
630 dat->ncons = 0;
631 dat->conscols = NULL;
632 dat->all_nfrag = 0;
633 dat->samp_nfrag = 0;
634 return eslOK;
635 }
636
637
638 /* Function: esl_msaweight_dat_Destroy()
639 * Synopsis: Free an <ESL_MSAWEIGHT_DAT> structure.
640 */
641 void
642 esl_msaweight_dat_Destroy(ESL_MSAWEIGHT_DAT *dat)
643 {
644 if (dat)
645 {
646 if (dat->conscols) free(dat->conscols);
647 free(dat);
648 }
649 }
650
651
652 /*****************************************************************
653 * 3. Other weighting algorithms
654 *****************************************************************/
655
656 /* Function: esl_msaweight_GSC()
657 * Synopsis: GSC weights.
658 * Incept: SRE, Fri Nov 3 13:31:14 2006 [Janelia]
659 *
660 * Purpose: Given a multiple sequence alignment <msa>, calculate
661 * sequence weights according to the
662 * Gerstein/Sonnhammer/Chothia algorithm. These weights
663 * are stored internally in the <msa> object, replacing
664 * any weights that may have already been there. Weights
665 * are $\geq 0$ and they sum to <msa->nseq>.
666 *
667 * The <msa> may be in either digitized or text mode.
668 * Digital mode is preferred, so that distance calculations
669 * used by the GSC algorithm are robust against degenerate
670 * residue symbols.
671 *
672 * This is an implementation of Gerstein et al., "A method to
673 * weight protein sequences to correct for unequal
674 * representation", JMB 236:1067-1078, 1994.
675 *
676 * The algorithm is $O(N^2)$ memory (it requires a pairwise
677 * distance matrix) and $O(N^3 + LN^2)$ time ($N^3$ for a UPGMA
678 * tree building step, $LN^2$ for distance matrix construction)
679 * for an alignment of N sequences and L columns.
680 *
681 * In the current implementation, the actual memory
682 * requirement is dominated by two full NxN distance
683 * matrices (one tmp copy in UPGMA, and one here): for
684 * 8-byte doubles, that's $16N^2$ bytes. To keep the
685 * calculation under memory limits, don't process large
686 * alignments: max 1400 sequences for 32 MB, max 4000
687 * sequences for 256 MB, max 8000 seqs for 1 GB. Watch
688 * out, because Pfam alignments can easily blow this up.
689 *
690 * Note: Memory usage could be improved. UPGMA consumes a distance
691 * matrix, but that can be D itself, not a copy, if the
692 * caller doesn't mind the destruction of D. Also, D is
693 * symmetrical, so we could use upper or lower triangular
694 * matrices if we rewrote dmatrix to allow them.
695 *
696 * I also think UPGMA can be reduced to O(N^2) time, by
697 * being more tricky about rapidly identifying the minimum
698 * element: could keep min of each row, and update that,
699 * I think.
700 *
701 * Returns: <eslOK> on success, and the weights inside <msa> have been
702 * modified.
703 *
704 * Throws: <eslEINVAL> if the alignment data are somehow invalid and
705 * distance matrices can't be calculated. <eslEMEM> on an
706 * allocation error. In either case, the original <msa> is
707 * left unmodified.
708 *
709 * Xref: [Gerstein94]; squid::weight.c::GSCWeights(); STL11/81.
710 */
711 int
712 esl_msaweight_GSC(ESL_MSA *msa)
713 {
714 ESL_DMATRIX *D = NULL; /* distance matrix */
715 ESL_TREE *T = NULL; /* UPGMA tree */
716 double *x = NULL; /* storage per node, 0..N-2 */
717 double lw, rw; /* total branchlen on left, right subtrees */
718 double lx, rx; /* distribution of weight to left, right side */
719 int i; /* counter over nodes */
720 int status;
721
722 /* Contract checks
723 */
724 ESL_DASSERT1( (msa != NULL) );
725 ESL_DASSERT1( (msa->nseq >= 1) );
726 ESL_DASSERT1( (msa->alen >= 1) );
727 ESL_DASSERT1( (msa->wgt != NULL) );
728 if (msa->nseq == 1) { msa->wgt[0] = 1.0; return eslOK; }
729
730 /* GSC weights use a rooted tree with "branch lengths" calculated by
731 * UPGMA on a fractional difference matrix - pretty crude.
732 */
733 if (! (msa->flags & eslMSA_DIGITAL))
734 {
735 if ((status = esl_dst_CDiffMx(msa->aseq, msa->nseq, &D)) != eslOK) goto ERROR;
736 }
737 else
738 {
739 if ((status = esl_dst_XDiffMx(msa->abc, msa->ax, msa->nseq, &D)) != eslOK) goto ERROR;
740 }
741
742 /* oi, look out here. UPGMA is correct, but old squid library uses
743 * single linkage, so for regression tests ONLY, we use single link.
744 */
745 #ifdef eslMSAWEIGHT_REGRESSION
746 if ((status = esl_tree_SingleLinkage(D, &T)) != eslOK) goto ERROR;
747 #else
748 if ((status = esl_tree_UPGMA(D, &T)) != eslOK) goto ERROR;
749 #endif
750 esl_tree_SetCladesizes(T);
751
752 ESL_ALLOC(x, sizeof(double) * (T->N-1));
753
754 /* Postorder traverse (leaves to root) to calculate the total branch
755 * length under each internal node; store this in x[]. Remember the
756 * total branch length (x[0]) for a future sanity check.
757 */
758 for (i = T->N-2; i >= 0; i--)
759 {
760 x[i] = T->ld[i] + T->rd[i];
761 if (T->left[i] > 0) x[i] += x[T->left[i]];
762 if (T->right[i] > 0) x[i] += x[T->right[i]];
763 }
764
765 /* Preorder traverse (root to leaves) to calculate the weights. Now
766 * we use x[] to mean, the total weight *above* this node that we will
767 * apportion to the node's left and right children. The two
768 * meanings of x[] never cross: every x[] beneath x[i] is still a
769 * total branch length.
770 *
771 * Because the API guarantees that msa is returned unmodified in case
772 * of an exception, and we're touching msa->wgt here, no exceptions
773 * may be thrown from now on in this function.
774 */
775 x[0] = 0; /* initialize: no branch to the root. */
776 for (i = 0; i <= T->N-2; i++)
777 {
778 lw = T->ld[i]; if (T->left[i] > 0) lw += x[T->left[i]];
779 rw = T->rd[i]; if (T->right[i] > 0) rw += x[T->right[i]];
780
781 if (lw+rw == 0.)
782 {
783 /* A special case arises in GSC weights when all branch lengths in a subtree are 0.
784 * In this case, all seqs in this clade should get equal weights, sharing x[i] equally.
785 * So, split x[i] in proportion to cladesize, not to branch weight.
786 */
787 if (T->left[i] > 0) lx = x[i] * ((double) T->cladesize[T->left[i]] / (double) T->cladesize[i]);
788 else lx = x[i] / (double) T->cladesize[i];
789
790 if (T->right[i] > 0) rx = x[i] * ((double) T->cladesize[T->right[i]] / (double) T->cladesize[i]);
791 else rx = x[i] / (double) T->cladesize[i];
792 }
793 else /* normal case: x[i] split in proportion to branch weight. */
794 {
795 lx = x[i] * lw/(lw+rw);
796 rx = x[i] * rw/(lw+rw);
797 }
798
799 if (T->left[i] <= 0) msa->wgt[-(T->left[i])] = lx + T->ld[i];
800 else x[T->left[i]] = lx + T->ld[i];
801
802 if (T->right[i] <= 0) msa->wgt[-(T->right[i])] = rx + T->rd[i];
803 else x[T->right[i]] = rx + T->rd[i];
804 }
805
806 /* Renormalize weights to sum to N.
807 */
808 esl_vec_DNorm(msa->wgt, msa->nseq);
809 esl_vec_DScale(msa->wgt, msa->nseq, (double) msa->nseq);
810 msa->flags |= eslMSA_HASWGTS;
811
812 free(x);
813 esl_tree_Destroy(T);
814 esl_dmatrix_Destroy(D);
815 return eslOK;
816
817 ERROR:
818 if (x != NULL) free(x);
819 if (T != NULL) esl_tree_Destroy(T);
820 if (D != NULL) esl_dmatrix_Destroy(D);
821 return status;
822 }
823
824
825
826 /* Function: esl_msaweight_BLOSUM()
827 * Synopsis: BLOSUM weights.
828 * Incept: SRE, Sun Nov 5 09:52:41 2006 [Janelia]
829 *
830 * Purpose: Given a multiple sequence alignment <msa> and an identity
831 * threshold <maxid>, calculate sequence weights using the
832 * BLOSUM algorithm (Henikoff and Henikoff, PNAS
833 * 89:10915-10919, 1992). These weights are stored
834 * internally in the <msa> object, replacing any weights
835 * that may have already been there. Weights are $\geq 0$
836 * and they sum to <msa->nseq>.
837 *
838 * The algorithm does a single linkage clustering by
839 * fractional id, defines clusters such that no two clusters
840 * have a pairwise link $\geq$ <maxid>), and assigns
841 * weights of $\frac{1}{M_i}$ to each of the $M_i$
842 * sequences in each cluster $i$. The <maxid> threshold
843 * is a fractional pairwise identity, in the range
844 * $0..1$.
845 *
846 * The <msa> may be in either digitized or text mode.
847 * Digital mode is preferred, so that the pairwise identity
848 * calculations deal with degenerate residue symbols
849 * properly.
850 *
851 * Returns: <eslOK> on success, and the weights inside <msa> have been
852 * modified.
853 *
854 * Throws: <eslEMEM> on allocation error. <eslEINVAL> if a pairwise
855 * identity calculation fails because of corrupted sequence
856 * data. In either case, the <msa> is unmodified.
857 *
858 * Xref: [Henikoff92]; squid::weight.c::BlosumWeights().
859 */
860 int
861 esl_msaweight_BLOSUM(ESL_MSA *msa, double maxid)
862 {
863 int *c = NULL; /* cluster assignments for each sequence */
864 int *nmem = NULL; /* number of seqs in each cluster */
865 int nc; /* number of clusters */
866 int i; /* loop counter */
867 int status;
868
869 /* Contract checks
870 */
871 ESL_DASSERT1( (maxid >= 0. && maxid <= 1.) );
872 ESL_DASSERT1( (msa->nseq >= 1) );
873 ESL_DASSERT1( (msa->alen >= 1) );
874 if (msa->nseq == 1) { msa->wgt[0] = 1.0; return eslOK; }
875
876 if ((status = esl_msacluster_SingleLinkage(msa, maxid, &c, NULL, &nc)) != eslOK) goto ERROR;
877 ESL_ALLOC(nmem, sizeof(int) * nc);
878 esl_vec_ISet(nmem, nc, 0);
879 for (i = 0; i < msa->nseq; i++) nmem[c[i]]++;
880 for (i = 0; i < msa->nseq; i++) msa->wgt[i] = 1. / (double) nmem[c[i]];
881
882 /* Make weights normalize up to nseq, and return.
883 */
884 esl_vec_DNorm(msa->wgt, msa->nseq);
885 esl_vec_DScale(msa->wgt, msa->nseq, (double) msa->nseq);
886 msa->flags |= eslMSA_HASWGTS;
887
888 free(nmem);
889 free(c);
890 return eslOK;
891
892 ERROR:
893 if (c != NULL) free(c);
894 if (nmem != NULL) free(nmem);
895 return status;
896 }
897
898
899
900 /*****************************************************************
901 * 4. %id filtering
902 *****************************************************************/
903 /* Mar 2019: After revising the PB weighting algorithm, I also went
904 * ahead and revised ER's %id filtering along related lines, because TAJ
905 * coincidentally complained about how filtering could keep a fragment
906 * and throw out a closer-to-consensus sequence.
907 */
908
909 /* In addition to some of the internal functions used by PB weighting above... */
910 static int sort_doubles_decreasing(const void *data, int e1, int e2);
911 static int set_preference_conscover(const ESL_MSA *msa, const int *conscols, int ncons, double *sortwgt);
912 static int set_preference_randomly(const ESL_MSAWEIGHT_CFG *cfg, int nseq, double *sortwgt);
913 static int set_preference_origorder(int nseq, double *sortwgt);
914 static int msaweight_IDFilter_txt(const ESL_MSA *msa, double maxid, ESL_MSA **ret_newmsa);
915
916 /* Function: esl_msaweight_IDFilter()
917 * Synopsis: Filter by %ID.
918 * Incept: ER, Wed Oct 29 10:06:43 2008 [Janelia]
919 *
920 * Purpose: Remove sequences in <msa> that are $\geq$ <maxid>
921 * fractional identity to another aligned sequence. Return
922 * the filtered alignment in <*ret_newmsa>. The original
923 * <msa> is not changed.
924 *
925 * When a pair of sequences has $\geq$ <maxid> fractional
926 * identity, the default rule for which of them we keep
927 * differs depending on whether the <msa> is in digital or
928 * text mode. We typically manipulate biosequence
929 * alignments in digital mode. In digital mode, the default
930 * rule (called "conscover") is to prefer the sequence with
931 * an alignment span that covers more consensus columns.
932 * (Where "span" is defined by the column coordinates of
933 * the leftmost and rightmost aligned residues of the
934 * sequence; fragment definition rules also use the concept
935 * of "span".) In the simpler text mode, the rule is to
936 * keep the earlier sequence and discard the later, in the
937 * order the seqs come in the alignment. The conscover rule
938 * is designed to avoid keeping fragments, while trying not
939 * to bias the insertion/deletion statistics of the
940 * filtered alignment. To use different preference rules in
941 * digital mode alignments, see the more customizable
942 * <esl_msaweight_IDFilter_adv()>.
943 *
944 * Fractional identity is calculated by
945 * <esl_dst_{CX}PairID()>, which defines the denominator of
946 * the calculation as MIN(rlen1, rlen2).
947 *
948 * Unparsed Stockholm markup is not propagated into the new
949 * filtered alignment.
950 *
951 * Return: <eslOK> on success, and <*ret_newmsa> is the filtered
952 * alignment.
953 *
954 * Throws: <eslEMEM> on allocation error. <eslEINVAL> if a pairwise
955 * identity calculation fails because of corrupted sequence
956 * data. In either case, the <msa> is unmodified.
957 *
958 * Xref: squid::weight.c::FilterAlignment().
959 */
960 int
961 esl_msaweight_IDFilter(const ESL_MSA *msa, double maxid, ESL_MSA **ret_newmsa)
962 {
963 if (msa->flags & eslMSA_DIGITAL) return esl_msaweight_IDFilter_adv(NULL, msa, maxid, ret_newmsa);
964 else return msaweight_IDFilter_txt ( msa, maxid, ret_newmsa);
965 }
966
967
968 /* Function: esl_msaweight_IDFilter_adv()
969 * Synopsis: Advanced version of %id filtering; digital MSAs only.
970 * Incept: SRE, Sat 30 Mar 2019
971 *
972 * Purpose: Same as <esl_msaweight_IDFilter()> but customizable with
973 * optional custom parameters in <cfg>. Requires digital
974 * mode alignment.
975 *
976 * In particular, <cfg> can be used to select two other
977 * rules for sequence preference, besides the default
978 * "conscover" rule: random preference, or preferring the
979 * lower-index sequence (same as the rule used in text mode
980 * alignments).
981 *
982 * For the "conscover" rule, consensus column determination
983 * can be customized the same way as in PB weighting.
984 */
985 int
986 esl_msaweight_IDFilter_adv(const ESL_MSAWEIGHT_CFG *cfg, const ESL_MSA *msa, double maxid, ESL_MSA **ret_newmsa)
987 {
988 int ignore_rf = (cfg? cfg->ignore_rf : eslMSAWEIGHT_IGNORE_RF); // default is FALSE: use RF annotation as consensus definition, if RF is present
989 int allow_samp = (cfg? cfg->allow_samp : eslMSAWEIGHT_ALLOW_SAMP); // default is TRUE: allow subsampling speed optimization
990 int sampthresh = (cfg? cfg->sampthresh : eslMSAWEIGHT_SAMPTHRESH); // if nseq > sampthresh, try to determine consensus on a subsample of seqs
991 int filterpref = (cfg? cfg->filterpref : eslMSAWEIGHT_FILT_CONSCOVER); // default preference rule is "conscover"
992 int **ct = NULL; // matrix of symbol counts in each column. ct[apos=(0).1..alen][a=0..Kp-1]
993 int *conscols = NULL; // list of consensus column indices [0..ncons-1]
994 double *sortwgt = NULL; // when pair of seqs is >= maxid, retain seq w/ higher <sortwgt>
995 int *ranked_at = NULL; // sorted seq indices 0..nseq-1
996 int *list = NULL; // array of seq indices in new msa
997 int *useme = NULL; // useme[i] is TRUE if seq[i] is kept in new msa
998 int ncons = 0; // number of consensus column indices in <conscols> list
999 int nnew = 0; // how many seqs have been added to <list> and <useme> so far
1000 int apos, r, i; // index over columns, ranked seq indices, seqs in <list>
1001 double ident; // pairwise fractional id (0..1)
1002 int status = eslOK;
1003
1004 ESL_DASSERT1(( msa->nseq >= 1 && msa->alen >= 1));
1005 ESL_DASSERT1(( msa->flags & eslMSA_DIGITAL ));
1006
1007 /* Allocations that we always need*/
1008 ESL_ALLOC(sortwgt, sizeof(double) * msa->nseq);
1009 ESL_ALLOC(ranked_at, sizeof(double) * msa->nseq);
1010 ESL_ALLOC(list, sizeof(int) * msa->nseq);
1011 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1012 esl_vec_ISet(useme, msa->nseq, 0); /* initialize array */
1013
1014 /* Determine consensus columns with same procedure as advanced PB weights.
1015 * 1. If RF annotation is provided, use it.
1016 * (...unless cfg->ignore_rf has been set TRUE)
1017 * 2. If it's a deep alignment, subsample and apply fragthresh/symfrac rules to the sample.
1018 * (...unless cfg->allow_samp has been set FALSE)
1019 * 3. Otherwise, use standard rule on all sequences:
1020 * collect observed counts in <ct> (applying fragthresh rule) and
1021 * determine consensus (applying symfrac rule)
1022 * 4. If all else fails, define all columns as consensus.
1023 *
1024 * We only need to do this if we're using the default "conscover" rule.
1025 */
1026 if (filterpref == eslMSAWEIGHT_FILT_CONSCOVER)
1027 {
1028 /* allocations only needed for consensus determination */
1029 ct = esl_mat_ICreate( msa->alen+1, msa->abc->Kp ); // (0).1..alen; 0..Kp-1
1030 ESL_ALLOC(conscols, sizeof(int) * msa->alen);
1031
1032 if (! ignore_rf && msa->rf) consensus_by_rf(msa, conscols, &ncons, NULL);
1033 else if (allow_samp && msa->nseq > sampthresh) consensus_by_sample(cfg, msa, ct, conscols, &ncons, NULL);
1034 else {
1035 collect_counts(cfg, msa, conscols, ncons, ct, NULL);
1036 consensus_by_all(cfg, msa, ct, conscols, &ncons, NULL);
1037 }
1038 if (!ncons) {
1039 for (apos = 1; apos <= msa->alen; apos++) conscols[apos-1] = apos;
1040 ncons = msa->alen;
1041 }
1042 }
1043
1044 /* Assign preferences for which sequences to retain.
1045 * Higher <sortwgt> means higher preference.
1046 */
1047 if (filterpref == eslMSAWEIGHT_FILT_CONSCOVER) set_preference_conscover(msa, conscols, ncons, sortwgt);
1048 else if (filterpref == eslMSAWEIGHT_FILT_RANDOM) set_preference_randomly (cfg, msa->nseq, sortwgt);
1049 else if (filterpref == eslMSAWEIGHT_FILT_ORIGORDER) set_preference_origorder( msa->nseq, sortwgt);
1050 else esl_fatal("bad filterpref");
1051
1052 /* Sort sequence indices by these preferences.
1053 * <ranked_at[]> is a ranked list of sequence indices 0..nseq-1.
1054 */
1055 esl_quicksort(sortwgt, msa->nseq, sort_doubles_decreasing, ranked_at);
1056
1057 /* Determine which seqs will be kept, favoring highest ranked ones.
1058 */
1059 for (r = 0; r < msa->nseq; r++) // Try to include each sequence, starting with highest ranked ones
1060 {
1061 for (i = 0; i < nnew; i++) // Test it against all the seqs we've already put in the list.
1062 {
1063 if ((status = esl_dst_XPairId(msa->abc, msa->ax[ranked_at[r]], msa->ax[list[i]], &ident, NULL, NULL)) != eslOK) goto ERROR;
1064 if (ident >= maxid) break;
1065 }
1066
1067 if (i == nnew) // if the seq made it past comparisons with all <nnew> current seqs in the list...
1068 {
1069 list[nnew++] = ranked_at[r]; // ... add it to the growing list.
1070 useme[ranked_at[r]] = TRUE;
1071 }
1072 }
1073
1074 /* Filter the input MSA.
1075 */
1076 if ((status = esl_msa_SequenceSubset(msa, useme, ret_newmsa)) != eslOK) goto ERROR;
1077
1078 ERROR:
1079 free(useme);
1080 free(list);
1081 free(ranked_at);
1082 free(sortwgt);
1083 free(conscols);
1084 esl_mat_IDestroy(ct);
1085 return status;
1086 }
1087
1088
1089
1090 /* Sorting function for the esl_quicksort() in the
1091 * esl_msaweight_IDFilter_adv() implementation below:
1092 * rank seqs in order of decreasing sortwgt.
1093 */
1094 static int
1095 sort_doubles_decreasing(const void *data, int e1, int e2)
1096 {
1097 double *sortwgt = (double *) data;
1098 if (sortwgt[e1] > sortwgt[e2]) return -1;
1099 if (sortwgt[e1] < sortwgt[e2]) return 1;
1100 return 0;
1101 }
1102
1103 /* Preference-setting function for which seqs we prefer to retain. The
1104 * default "conscover" rule counts how many consensus columns are
1105 * covered by the "span" of this sequence from its first to last
1106 * residue.
1107 * - set lpos, rpos to the column coord (1..alen) of the leftmost,
1108 * rightmost residue in this seq;
1109 * - count how many consensus columns are covered by that span.
1110 *
1111 * This is not the same as counting how many consensus columns have
1112 * a residue in them. We're trying not to bias (too much) against
1113 * deletions when we select representative sequences.
1114 */
1115 static int
1116 set_preference_conscover(const ESL_MSA *msa, const int *conscols, int ncons, double *sortwgt)
1117 {
1118 int idx, apos, lpos, rpos, j;
1119
1120 for (idx = 0; idx < msa->nseq; idx++)
1121 {
1122 for (lpos = 1; lpos <= msa->alen; lpos++) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][lpos])) break;
1123 for (rpos = msa->alen; rpos >= 1; rpos--) if (esl_abc_XIsResidue(msa->abc, msa->ax[idx][rpos])) break;
1124
1125 sortwgt[idx] = 0.;
1126 for (j = 0; j < ncons && conscols[j] <= rpos; j++)
1127 {
1128 apos = conscols[j];
1129 if (apos < lpos) continue;
1130 sortwgt[idx] += 1.;
1131 }
1132 }
1133 return eslOK;
1134 }
1135
1136 /* Preference-setting function where we assign random preference.
1137 */
1138 static int
1139 set_preference_randomly(const ESL_MSAWEIGHT_CFG *cfg, int nseq, double *sortwgt)
1140 {
1141 ESL_RAND64 *rng = (cfg? esl_rand64_Create(cfg->seed) : esl_rand64_Create(eslMSAWEIGHT_RNGSEED));
1142 int idx;
1143
1144 for (idx = 0; idx < nseq; idx++)
1145 sortwgt[idx] = esl_rand64_double(rng);
1146
1147 esl_rand64_Destroy(rng);
1148 return eslOK;
1149 }
1150
1151 /* Preference-setting function that favors the earlier sequence
1152 * in the alignment; same as the rule used for text mode alignments.
1153 */
1154 static int
1155 set_preference_origorder(int nseq, double *sortwgt)
1156 {
1157 int idx;
1158
1159 for (idx = 0; idx < nseq; idx++)
1160 sortwgt[idx] = (double) (nseq - idx); // sets them to nseq..1
1161 return eslOK;
1162 }
1163
1164
1165 /* msaweight_IDFilter_txt()
1166 * %id filtering for text-mode MSAs.
1167 */
1168 static int
1169 msaweight_IDFilter_txt(const ESL_MSA *msa, double maxid, ESL_MSA **ret_newmsa)
1170 {
1171 int *list = NULL; /* array of seqs in new msa */
1172 int *useme = NULL; /* TRUE if seq is kept in new msa */
1173 int nnew; /* number of seqs in new alignment */
1174 double ident; /* pairwise percentage id */
1175 int i,j; /* seqs counters*/
1176 int remove; /* TRUE if sq is to be removed */
1177 int status;
1178
1179 ESL_DASSERT1(( msa ));
1180 ESL_DASSERT1(( msa->nseq >= 1 ));
1181 ESL_DASSERT1(( msa->alen >= 1 ));
1182 ESL_DASSERT1(( ! (msa->flags & eslMSA_DIGITAL )));
1183
1184 /* allocate */
1185 ESL_ALLOC(list, sizeof(int) * msa->nseq);
1186 ESL_ALLOC(useme, sizeof(int) * msa->nseq);
1187 esl_vec_ISet(useme, msa->nseq, 0); /* initialize array */
1188
1189 /* find which seqs to keep (list) */
1190 nnew = 0;
1191 for (i = 0; i < msa->nseq; i++)
1192 {
1193 remove = FALSE;
1194 for (j = 0; j < nnew; j++)
1195 {
1196 if (! (msa->flags & eslMSA_DIGITAL)) {
1197 if ((status = esl_dst_CPairId(msa->aseq[i], msa->aseq[list[j]], &ident, NULL, NULL)) != eslOK) goto ERROR;
1198 }
1199 else {
1200 if ((status = esl_dst_XPairId(msa->abc, msa->ax[i], msa->ax[list[j]], &ident, NULL, NULL)) != eslOK) goto ERROR;
1201 }
1202
1203 if (ident >= maxid)
1204 {
1205 remove = TRUE;
1206 break;
1207 }
1208 }
1209 if (remove == FALSE) {
1210 list[nnew++] = i;
1211 useme[i] = TRUE;
1212 }
1213 }
1214 if ((status = esl_msa_SequenceSubset(msa, useme, ret_newmsa)) != eslOK) goto ERROR;
1215
1216 free(list);
1217 free(useme);
1218 return eslOK;
1219
1220 ERROR:
1221 if (list != NULL) free(list);
1222 if (useme != NULL) free(useme);
1223 return status;
1224 }
1225
1226
1227
1228 /*****************************************************************
1229 * 5. Benchmark
1230 *****************************************************************/
1231 #ifdef eslMSAWEIGHT_BENCHMARK
1232 /* gcc -g -Wall -o benchmark -I. -L. -DeslMSAWEIGHT_BENCHMARK esl_msaweight.c -leasel -lm
1233 * ./benchmark <MSA file>
1234 *
1235 * Script for benchmarks on Pfam:
1236 * ./benchmark --gsc --maxN 4000 /misc/data0/databases/Pfam/Pfam-A.full
1237 * ./benchmark --blosum /misc/data0/databases/Pfam/Pfam-A.full
1238 * ./benchmark --pb /misc/data0/databases/Pfam/Pfam-A.full
1239 */
1240 #include "easel.h"
1241 #include "esl_getopts.h"
1242 #include "esl_msa.h"
1243 #include "esl_msafile.h"
1244 #include "esl_msaweight.h"
1245 #include "esl_vectorops.h"
1246 #include "esl_stopwatch.h"
1247
1248 #define WGROUP "--blosum,--gsc,--pb"
1249
1250 static ESL_OPTIONS options[] = {
1251 /* name type deflt env rng togs req incmpt help docgrp */
1252 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0 },
1253 { "--blosum", eslARG_NONE, FALSE, NULL, NULL, WGROUP, NULL, NULL, "use BLOSUM weights", 0 },
1254 { "--gsc", eslARG_NONE,"default",NULL,NULL, WGROUP, NULL, NULL, "use GSC weights", 0 },
1255 { "--pb", eslARG_NONE, FALSE, NULL, NULL, WGROUP, NULL, NULL, "use position-based weights", 0 },
1256 { "--id", eslARG_REAL, "0.62", NULL,"0<=x<=1",NULL,"--blosum",NULL, "id threshold for --blosum", 0 },
1257 { "--maxN", eslARG_INT, "0", NULL,"n>=0", NULL, NULL, NULL, "skip alignments w/ > <n> seqs", 0 },
1258 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1259 };
1260
1261 static char usage[] = "Usage: ./benchmark [-options] <msa_file>";
1262
1263 int
1264 main(int argc, char **argv)
1265 {
1266 ESL_STOPWATCH *w;
1267 ESL_GETOPTS *go;
1268 char *msafile;
1269 ESL_MSAFILE *afp;
1270 ESL_MSA *msa;
1271 int do_gsc;
1272 int do_pb;
1273 int do_blosum;
1274 int maxN;
1275 double maxid;
1276 double cpu;
1277 int status;
1278
1279 /* Process command line
1280 */
1281 go = esl_getopts_Create(options);
1282 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) esl_fatal("failed to parse cmd line: %s", go->errbuf);
1283 if (esl_opt_VerifyConfig(go) != eslOK) esl_fatal("failed to parse cmd line: %s", go->errbuf);
1284 if (esl_opt_GetBoolean(go, "-h") == TRUE) {
1285 puts(usage);
1286 puts("\n where options are:");
1287 esl_opt_DisplayHelp(stdout, go, 0, 2, 80); /* 0=all docgroups; 2=indentation; 80=width */
1288 return 0;
1289 }
1290 do_blosum = esl_opt_GetBoolean(go, "--blosum");
1291 do_gsc = esl_opt_GetBoolean(go, "--gsc");
1292 do_pb = esl_opt_GetBoolean(go, "--pb");
1293 maxid = esl_opt_GetReal (go, "--id");
1294 maxN = esl_opt_GetInteger(go, "--maxN");
1295 if (esl_opt_ArgNumber(go) != 1) {
1296 puts("Incorrect number of command line arguments.");
1297 puts(usage);
1298 return 1;
1299 }
1300 if ((msafile = esl_opt_GetArg(go, 1)) == NULL) esl_fatal("failed to parse cmd line: %s", go->errbuf);
1301 esl_getopts_Destroy(go);
1302
1303 w = esl_stopwatch_Create();
1304
1305 /* Weight one or more alignments from input file
1306 */
1307 if ((status = esl_msafile_Open(NULL, msafile, NULL, eslMSAFILE_UNKNOWN, NULL, &afp)) != eslOK)
1308 esl_msafile_OpenFailure(afp, status);
1309
1310 while ( (status = esl_msafile_Read(afp, &msa)) != eslEOF)
1311 {
1312 if (status != eslOK) esl_msafile_ReadFailure(afp, status);
1313 if (maxN > 0 && msa->nseq > maxN) { esl_msa_Destroy(msa); continue; }
1314
1315 esl_stopwatch_Start(w);
1316
1317 if (do_gsc) esl_msaweight_GSC(msa);
1318 else if (do_pb) esl_msaweight_PB(msa);
1319 else if (do_blosum) esl_msaweight_BLOSUM(msa, maxid);
1320
1321 esl_stopwatch_Stop(w);
1322 cpu = w->user;
1323 printf("%-20s %6d %6d %.3f\n", msa->name, msa->alen, msa->nseq, cpu);
1324 esl_msa_Destroy(msa);
1325 }
1326 esl_msafile_Close(afp);
1327
1328 esl_stopwatch_Destroy(w);
1329 return eslOK;
1330 }
1331 #endif /* eslMSAWEIGHT_BENCHMARK */
1332 /*-------------------- end, benchmark --------------------------*/
1333
1334
1335
1336 /*****************************************************************
1337 * 6. Statistics driver
1338 *****************************************************************/
1339 #ifdef eslMSAWEIGHT_STATS
1340 /* gcc -g -Wall -o stats -I. -L. -DeslMSAWEIGHT_STATS esl_msaweight.c -leasel -lm
1341 * ./stats <MSA file>
1342 *
1343 * Script for weight statistics on Pfam:
1344 * ./stats --gsc --maxN 4000 /misc/data0/databases/Pfam/Pfam-A.full
1345 * ./stats --blosum /misc/data0/databases/Pfam/Pfam-A.full
1346 * ./stats --pb /misc/data0/databases/Pfam/Pfam-A.full
1347 */
1348 #include "easel.h"
1349 #include "esl_getopts.h"
1350 #include "esl_msa.h"
1351 #include "esl_msafile.h"
1352 #include "esl_msaweight.h"
1353 #include "esl_vectorops.h"
1354
1355 #define WGROUP "--blosum,--gsc,--pb"
1356
1357 static ESL_OPTIONS options[] = {
1358 /* name type deflt env rng togs req incmpt help docgrp */
1359 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0 },
1360 { "--blosum", eslARG_NONE, FALSE, NULL, NULL, WGROUP, NULL, NULL, "use BLOSUM weights", 0 },
1361 { "--gsc", eslARG_NONE,"default",NULL,NULL, WGROUP, NULL, NULL, "use GSC weights", 0 },
1362 { "--pb", eslARG_NONE, FALSE, NULL, NULL, WGROUP, NULL, NULL, "use position-based weights", 0 },
1363 { "--id", eslARG_REAL, "0.62", NULL,"0<=x<=1",NULL,"--blosum",NULL, "id threshold for --blosum", 0 },
1364 { "--maxN", eslARG_INT, "0", NULL,"n>=0", NULL, NULL, NULL, "skip alignments w/ > <n> seqs", 0 },
1365 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1366 };
1367
1368 static char usage[] = "Usage: ./stats [-options] <msa_file>";
1369
1370 int
1371 main(int argc, char **argv)
1372 {
1373 ESL_GETOPTS *go;
1374 char *msafile;
1375 ESL_MSAFILE *afp;
1376 ESL_MSA *msa;
1377 int do_gsc;
1378 int do_pb;
1379 int do_blosum;
1380 int maxN;
1381 double maxid;
1382 int nsmall, nbig;
1383 int i;
1384 int status;
1385
1386 /* Process command line */
1387 go = esl_getopts_Create(options);
1388 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK) esl_fatal("%s", go->errbuf);
1389 if (esl_opt_VerifyConfig(go) != eslOK) esl_fatal("%s", go->errbuf);
1390 if (esl_opt_GetBoolean(go, "-h") == TRUE){
1391 puts(usage);
1392 puts("\n where options are:");
1393 esl_opt_DisplayHelp(stdout, go, 0, 2, 80); /* 0=all docgroups; 2=indentation; 80=width */
1394 return 0;
1395 }
1396 do_blosum = esl_opt_GetBoolean(go, "--blosum");
1397 do_gsc = esl_opt_GetBoolean(go, "--gsc");
1398 do_pb = esl_opt_GetBoolean(go, "--pb");
1399 maxid = esl_opt_GetReal (go, "--id");
1400 maxN = esl_opt_GetInteger(go, "--maxN");
1401 if (esl_opt_ArgNumber(go) != 1) {
1402 puts("Incorrect number of command line arguments.");
1403 puts(usage);
1404 return 1;
1405 }
1406 if ((msafile = esl_opt_GetArg(go, 1)) == NULL) esl_fatal("%s", go->errbuf);
1407 esl_getopts_Destroy(go);
1408
1409 /* Weight one or more alignments from input file
1410 */
1411 if ((status = esl_msafile_Open(NULL, msafile, NULL, eslMSAFILE_UNKNOWN, NULL, &afp)) != eslOK)
1412 esl_msafile_OpenFailure(afp, status);
1413
1414 while ( (status = esl_msafile_Read(afp, &msa)) != eslEOF)
1415 {
1416 if (status != eslOK) esl_msafile_ReadFailure(afp, status);
1417 if (maxN > 0 && msa->nseq > maxN) { esl_msa_Destroy(msa); continue; }
1418
1419 if (do_gsc) esl_msaweight_GSC(msa);
1420 else if (do_pb) esl_msaweight_PB(msa);
1421 else if (do_blosum) esl_msaweight_BLOSUM(msa, maxid);
1422
1423 for (nsmall = 0, nbig = 0, i = 0; i < msa->nseq; i++) {
1424 if (msa->wgt[i] < 0.2) nsmall++;
1425 if (msa->wgt[i] > 5.0) nbig++;
1426 }
1427
1428 printf("%-20s %5d %5d %8.4f %8.4f %5d %5d\n",
1429 msa->name,
1430 msa->nseq,
1431 msa->alen,
1432 esl_vec_DMin(msa->wgt, msa->nseq),
1433 esl_vec_DMax(msa->wgt, msa->nseq),
1434 nsmall,
1435 nbig);
1436 esl_msa_Destroy(msa);
1437 }
1438 esl_msafile_Close(afp);
1439 return eslOK;
1440 }
1441 #endif /* eslMSAWEIGHT_STATS */
1442 /*---------------- end, statistics driver ----------------------*/
1443
1444
1445
1446
1447 /*****************************************************************
1448 * 7. Unit tests
1449 *****************************************************************/
1450 #ifdef eslMSAWEIGHT_TESTDRIVE
1451
1452 #include "esl_msafile.h"
1453
1454 /* GSC weighting test on text-mode alignment <msa>, where we expect
1455 * the weights to be <expect[0]..expect[nseq-1]>.
1456 *
1457 * If <abc> is non-NULL, digitize alignment and run test again in
1458 * digital alignment mode.
1459 *
1460 * On failure, caller utest provides <msg> as the error msg to print.
1461 */
1462 static void
1463 do_GSC(ESL_ALPHABET *abc, ESL_MSA *msa, double *expect, char *msg)
1464 {
1465 /* text mode */
1466 if (esl_msaweight_GSC(msa) != eslOK) esl_fatal(msg);
1467 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1468
1469 /* digital mode */
1470 if (abc)
1471 {
1472 if (esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg);
1473 if (esl_msaweight_GSC(msa) != eslOK) esl_fatal(msg);
1474 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1475 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
1476 }
1477 }
1478
1479 /* As above, but for default PB weights */
1480 static void
1481 do_PB(ESL_ALPHABET *abc, ESL_MSA *msa, double *expect, char *msg)
1482 {
1483 if (esl_msaweight_PB(msa) != eslOK) esl_fatal(msg);
1484 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1485
1486 if (abc)
1487 {
1488 if (esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg);
1489 if (esl_msaweight_PB(msa) != eslOK) esl_fatal(msg);
1490 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1491 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
1492 }
1493 }
1494
1495 /* As above, but for BLOSUM weights with fractional identity threshold <maxid> */
1496 static void
1497 do_BLOSUM(ESL_ALPHABET *abc, ESL_MSA *msa, double maxid, double *expect, char *msg)
1498 {
1499 if (esl_msaweight_BLOSUM(msa, maxid) != eslOK) esl_fatal(msg);
1500 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1501
1502 if (abc)
1503 {
1504 if (esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg);
1505 if (esl_msaweight_BLOSUM(msa, maxid) != eslOK) esl_fatal(msg);
1506 if (esl_vec_DCompare(msa->wgt, expect, msa->nseq, 0.001) != eslOK) esl_fatal(msg);
1507 if (esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
1508 }
1509 }
1510
1511 /* utest_wgt_identical_seqs
1512 * For all identical sequences, weights are uniform, all 1.0.
1513 */
1514 static void
1515 utest_identical_seqs(void)
1516 {
1517 char msg[] = "identical_seqs test failed";
1518 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nseq1 AAAAA\nseq2 AAAAA\nseq3 AAAAA\nseq4 AAAAA\nseq5 AAAAA\n//\n", eslMSAFILE_STOCKHOLM);
1519 ESL_ALPHABET *aa_abc = esl_alphabet_Create(eslAMINO);
1520 ESL_ALPHABET *nt_abc = esl_alphabet_Create(eslDNA);
1521 double uniform[5] = { 1.0, 1.0, 1.0, 1.0, 1.0 };
1522
1523 do_GSC (aa_abc, msa, uniform, msg);
1524 do_GSC (nt_abc, msa, uniform, msg);
1525 do_PB (aa_abc, msa, uniform, msg);
1526 do_PB (nt_abc, msa, uniform, msg);
1527 do_BLOSUM(aa_abc, msa, 0.62, uniform, msg);
1528 do_BLOSUM(nt_abc, msa, 0.62, uniform, msg);
1529
1530 esl_alphabet_Destroy(nt_abc);
1531 esl_alphabet_Destroy(aa_abc);
1532 esl_msa_Destroy(msa);
1533 }
1534
1535 /* The "contrived" example of [Henikoff94b].
1536 * "Correct" solution is 1==2, 3==4, 5==2x others.
1537 * PB, GSC, BLOSUM weights all agree.
1538 */
1539 static void
1540 utest_henikoff_contrived(void)
1541 {
1542 char msg[] = "henikoff_contrived test failed";
1543 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nseq1 AAAAA\nseq2 AAAAA\nseq3 CCCCC\nseq4 CCCCC\nseq5 TTTTT\n//\n", eslMSAFILE_STOCKHOLM);
1544 ESL_ALPHABET *aa_abc = esl_alphabet_Create(eslAMINO);
1545 ESL_ALPHABET *nt_abc = esl_alphabet_Create(eslDNA);
1546 double ewgt[5] = { 0.833333, 0.833333, 0.833333, 0.833333, 1.66667 };
1547
1548 do_GSC (aa_abc, msa, ewgt, msg);
1549 do_GSC (nt_abc, msa, ewgt, msg);
1550 do_PB (aa_abc, msa, ewgt, msg);
1551 do_PB (nt_abc, msa, ewgt, msg);
1552 do_BLOSUM(aa_abc, msa, 0.62, ewgt, msg);
1553 do_BLOSUM(nt_abc, msa, 0.62, ewgt, msg);
1554
1555 esl_alphabet_Destroy(nt_abc);
1556 esl_alphabet_Destroy(aa_abc);
1557 esl_msa_Destroy(msa);
1558 }
1559
1560 /* The "nitrogenase segments" example of [Henikoff94b].
1561 * PB, GSC, BLOSUM wgts differ on this example.
1562 */
1563 static void
1564 utest_nitrogenase(void)
1565 {
1566 char msg[] = "nitrogenase test failed";
1567 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nNIFE_CLOPA GYVGS\nNIFD_AZOVI GFDGF\nNIFD_BRAJA GYDGF\nNIFK_ANASP GYQGG\n//\n", eslMSAFILE_STOCKHOLM);
1568 ESL_ALPHABET *aa_abc = esl_alphabet_Create(eslAMINO);
1569 double egsc[4] = { 1.125000, 0.875000, 0.875000, 1.125000 };
1570 double epb[4] = { 1.066667, 1.066667, 0.800000, 1.066667 };
1571 double eblo[4] = { 1.333333, 0.666667, 0.666667, 1.333333 };
1572
1573 do_GSC (aa_abc, msa, egsc, msg);
1574 do_PB (aa_abc, msa, epb, msg);
1575 do_BLOSUM(aa_abc, msa, 0.62, eblo, msg);
1576
1577 esl_alphabet_Destroy(aa_abc);
1578 esl_msa_Destroy(msa);
1579 }
1580
1581 /* gerstein4 test:
1582 * alignment that makes the same distances as Figure 4 from [Gerstein94].
1583 */
1584 static void
1585 utest_gerstein4(void)
1586 {
1587 char msg[] = "gerstein4 test failed";
1588 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nA AAAAAAAAAA\nB TTAAAAAAAA\nC ATAAAACCCC\nD GGGAAGGGGG\n//\n", eslMSAFILE_STOCKHOLM);
1589 ESL_ALPHABET *aa_abc = esl_alphabet_Create(eslAMINO);
1590 ESL_ALPHABET *nt_abc = esl_alphabet_Create(eslDNA);
1591 double egsc[4] = { 0.760870, 0.760870, 1.086957, 1.391304 };
1592 double epb[4] = { 0.800000, 0.800000, 1.000000, 1.400000 };
1593 double eblo[4] = { 0.666667, 0.666667, 1.333333, 1.333333 };
1594 double uni[4] = { 1.0, 1.0, 1.0, 1.0 };
1595
1596 do_GSC (aa_abc, msa, egsc, msg);
1597 do_GSC (nt_abc, msa, egsc, msg);
1598 do_PB (aa_abc, msa, epb, msg);
1599 do_PB (nt_abc, msa, epb, msg);
1600 do_BLOSUM(aa_abc, msa, 0.62, eblo, msg);
1601 do_BLOSUM(nt_abc, msa, 0.62, eblo, msg);
1602
1603 /* BLOSUM weights have the peculiar property of going flat at maxid=0.0
1604 * (when everyone clusters) or maxid=1.0 (nobody clusters). Test that here.
1605 */
1606 do_BLOSUM(aa_abc, msa, 0.0, uni, msg);
1607 do_BLOSUM(aa_abc, msa, 1.0, uni, msg);
1608
1609 esl_alphabet_Destroy(nt_abc);
1610 esl_alphabet_Destroy(aa_abc);
1611 esl_msa_Destroy(msa);
1612 }
1613
1614 /* pathologs test
1615 * A gappy alignment where no seqs overlap, and weighting methods
1616 * have to resort to uniform weights.
1617 */
1618 static void
1619 utest_pathologs(void)
1620 {
1621 char msg[] = "pathologs test failed";
1622 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nA A----\nB -C---\nC --G--\nD ---T-\nE ----T\n//\n", eslMSAFILE_STOCKHOLM);
1623 ESL_ALPHABET *aa_abc = esl_alphabet_Create(eslAMINO);
1624 ESL_ALPHABET *nt_abc = esl_alphabet_Create(eslDNA);
1625 double uni[5] = { 1.0, 1.0, 1.0, 1.0, 1.0 };
1626
1627 do_GSC (aa_abc, msa, uni, msg);
1628 do_GSC (nt_abc, msa, uni, msg);
1629 do_PB (aa_abc, msa, uni, msg);
1630 do_PB (nt_abc, msa, uni, msg);
1631 do_BLOSUM(aa_abc, msa, 0.62, uni, msg);
1632 do_BLOSUM(nt_abc, msa, 0.62, uni, msg);
1633
1634 esl_alphabet_Destroy(nt_abc);
1635 esl_alphabet_Destroy(aa_abc);
1636 esl_msa_Destroy(msa);
1637 }
1638
1639
1640 /* Simple test of the %id filter.
1641 * seq1 and seq2 are 100% identical, but seq1 is shorter.
1642 * seq2 is preferred in the default conscover rule;
1643 * seq1 is preferred in the origorder rule;
1644 * either seq1 or seq2 will be selected with the random rule.
1645 */
1646 static void
1647 utest_idfilter(void)
1648 {
1649 char msg[] = "idfilter test failed";
1650 ESL_MSAWEIGHT_CFG *cfg = esl_msaweight_cfg_Create();
1651 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
1652 ESL_MSA *msa = esl_msa_CreateFromString("# STOCKHOLM 1.0\n\nseq1 ..AAAAAAAA\nseq2 AAAAAAAAAA\nseq3 CCCCCCCCCC\nseq4 GGGGGGGGGG\n//\n", eslMSAFILE_STOCKHOLM);
1653 ESL_MSA *msa2 = NULL;
1654
1655 /* Default text mode rule is origorder */
1656 if (esl_msaweight_IDFilter(msa, 1.0, &msa2) != eslOK) esl_fatal(msg);
1657 if (msa2->nseq != 3 || strcmp(msa2->sqname[0], "seq1") != 0) esl_fatal(msg);
1658 esl_msa_Destroy(msa2);
1659
1660 /* Default digital mode rule is conscover */
1661 if (esl_msa_Digitize(abc, msa, NULL) != eslOK) esl_fatal(msg);
1662 if (esl_msaweight_IDFilter(msa, 1.0, &msa2) != eslOK) esl_fatal(msg);
1663 if (msa2->nseq != 3 || strcmp(msa2->sqname[0], "seq2") != 0) esl_fatal(msg);
1664 esl_msa_Destroy(msa2);
1665
1666 /* Ditto with _adv too */
1667 if (esl_msaweight_IDFilter_adv(cfg, msa, 1.0, &msa2) != eslOK) esl_fatal(msg);
1668 if (msa2->nseq != 3 || strcmp(msa2->sqname[0], "seq2") != 0) esl_fatal(msg);
1669 esl_msa_Destroy(msa2);
1670
1671 /* Custom setting _adv to origorder */
1672 cfg->filterpref = eslMSAWEIGHT_FILT_ORIGORDER;
1673 if (esl_msaweight_IDFilter_adv(cfg, msa, 1.0, &msa2) != eslOK) esl_fatal(msg);
1674 if (msa2->nseq != 3 || strcmp(msa2->sqname[0], "seq1") != 0) esl_fatal(msg);
1675 esl_msa_Destroy(msa2);
1676
1677 /* Custom setting _adv to randorder */
1678 cfg->filterpref = eslMSAWEIGHT_FILT_RANDOM;
1679 if (esl_msaweight_IDFilter_adv(cfg, msa, 1.0, &msa2) != eslOK) esl_fatal(msg);
1680 if (msa2->nseq != 3) esl_fatal(msg);
1681 if (strcmp(msa2->sqname[0], "seq1") != 0 && strcmp(msa2->sqname[0], "seq2") != 0) esl_fatal(msg);
1682 esl_msa_Destroy(msa2);
1683
1684 esl_msaweight_cfg_Destroy(cfg);
1685 esl_alphabet_Destroy(abc);
1686 esl_msa_Destroy(msa);
1687 }
1688
1689 #endif /*eslMSAWEIGHT_TESTDRIVE*/
1690 /*-------------------- end, unit tests -------------------------*/
1691
1692
1693
1694 /*****************************************************************
1695 * 8. Test driver
1696 *****************************************************************/
1697 #ifdef eslMSAWEIGHT_TESTDRIVE
1698
1699 #include "easel.h"
1700 #include "esl_getopts.h"
1701 #include "esl_msa.h"
1702 #include "esl_msafile.h"
1703 #include "esl_msaweight.h"
1704
1705 static ESL_OPTIONS options[] = {
1706 /* name type default env range toggles reqs incomp help docgroup*/
1707 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
1708 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1709 };
1710 static char usage[] = "[-options]";
1711 static char banner[] = "test driver for msaweight module";
1712
1713 int
1714 main(int argc, char **argv)
1715 {
1716 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1717
1718 fprintf(stderr, "## %s\n", argv[0]);
1719
1720 utest_identical_seqs();
1721 utest_henikoff_contrived();
1722 utest_nitrogenase();
1723 utest_gerstein4();
1724 utest_pathologs();
1725
1726 utest_idfilter();
1727
1728 fprintf(stderr, "# status = ok\n");
1729
1730 esl_getopts_Destroy(go);
1731 exit(0);
1732 }
1733 #endif /*eslMSAWEIGHT_TESTDRIVE*/
1734 /*-------------------- end, test driver -------------------------*/
1735
1736
1737
1738
1739
1740 /*****************************************************************
1741 * 9. Example
1742 *****************************************************************/
1743 #ifdef eslMSAWEIGHT_EXAMPLE
1744
1745 #include "easel.h"
1746 #include "esl_getopts.h"
1747 #include "esl_msa.h"
1748 #include "esl_msafile.h"
1749 #include "esl_msaweight.h"
1750
1751 static ESL_OPTIONS options[] = {
1752 /* name type default env range toggles reqs incomp help docgroup*/
1753 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 1 },
1754 { "--informat", eslARG_STRING, NULL, NULL, NULL, NULL, NULL, NULL, "specify the input MSA file is in format <s>", 1 },
1755 { "--dna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use DNA alphabet", 1 },
1756 { "--rna", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use RNA alphabet", 1 },
1757 { "--amino", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "use protein alphabet", 1 },
1758
1759 { "--ignore-rf", eslARG_NONE, eslMSAWEIGHT_IGNORE_RF, NULL, NULL, NULL, NULL, NULL, "ignore any RF line; always determine our own consensus", 2 },
1760 { "--fragthresh", eslARG_REAL, ESL_STR(eslMSAWEIGHT_FRAGTHRESH), NULL, "0<=x<=1", NULL, NULL, NULL, "seq is fragment if aspan/alen < fragthresh", 2 }, // 0.0 = no fragments; 1.0 = everything is a frag except 100% full-span aseq
1761 { "--symfrac", eslARG_REAL, ESL_STR(eslMSAWEIGHT_SYMFRAC), NULL, "0<=x<=1", NULL, NULL, NULL, "col is consensus if nres/(nres+ngap) >= symfrac", 2 }, // 0.0 = all cols are consensus; 1.0 = only 100% all-residue cols are consensus
1762
1763 { "--no-sampling", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "never use subsampling to determine consensus", 3 },
1764 { "--nsamp", eslARG_INT, ESL_STR(eslMSAWEIGHT_NSAMP), NULL, "n>=0", NULL, NULL, "--no-sampling", "number of seqs to sample (if using sampling)", 3 },
1765 { "--sampthresh", eslARG_INT, ESL_STR(eslMSAWEIGHT_SAMPTHRESH), NULL, "n>=0", NULL, NULL, "--no-sampling", "switch to using sampling when nseq > nsamp", 3 },
1766 { "--maxfrag", eslARG_INT, ESL_STR(eslMSAWEIGHT_MAXFRAG), NULL, "n>=0", NULL, NULL, "--no-sampling", "if sample has > maxfrag fragments, don't use sample", 3 },
1767 { "-s", eslARG_INT, ESL_STR(eslMSAWEIGHT_RNGSEED), NULL, "n>=0", NULL, NULL, NULL, "set random number seed to <n>", 3 },
1768
1769 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1770 };
1771
1772 static char usage[] = "[-options] <msafile>";
1773 static char banner[] = "esl_msaweight example";
1774
1775 int
1776 main(int argc, char **argv)
1777 {
1778 ESL_GETOPTS *go = esl_getopts_Create(options);
1779 char *msafile = NULL;
1780 int infmt = eslMSAFILE_UNKNOWN;
1781 ESL_MSAWEIGHT_CFG *cfg = esl_msaweight_cfg_Create();
1782 ESL_MSAWEIGHT_DAT *dat = esl_msaweight_dat_Create();
1783 ESL_ALPHABET *abc = NULL;
1784 ESL_MSAFILE *afp = NULL;
1785 ESL_MSA *msa = NULL;
1786 int nali = 0;
1787 int idx;
1788 int status;
1789
1790 /* Process command line and options
1791 */
1792 if (esl_opt_ProcessCmdline(go, argc, argv) != eslOK ||
1793 esl_opt_VerifyConfig(go) != eslOK)
1794 esl_fatal("Failed to parse command line: %s\n", go->errbuf);
1795 if (esl_opt_GetBoolean(go, "-h") == TRUE)
1796 {
1797 esl_banner(stdout, argv[0], banner);
1798 esl_usage (stdout, argv[0], usage);
1799 puts("\noptions:");
1800 esl_opt_DisplayHelp(stdout, go, 1, 2, 80); /* 1=docgroup; 2=indentation; 80=width */
1801 puts("\noptions for deriving consensus:");
1802 esl_opt_DisplayHelp(stdout, go, 2, 2, 80); /* 1=docgroup; 2=indentation; 80=width */
1803 puts("\noptions for deriving consensus by sampling (on deep MSAs):");
1804 esl_opt_DisplayHelp(stdout, go, 3, 2, 80); /* 1=docgroup; 2=indentation; 80=width */
1805 return 0;
1806 }
1807
1808 if (esl_opt_ArgNumber(go) != 1) esl_fatal("Incorrect number of command line arguments.\n%s\n", usage);
1809 msafile = esl_opt_GetArg(go, 1);
1810
1811 if (esl_opt_GetBoolean(go, "--rna")) abc = esl_alphabet_Create(eslRNA);
1812 else if (esl_opt_GetBoolean(go, "--dna")) abc = esl_alphabet_Create(eslDNA);
1813 else if (esl_opt_GetBoolean(go, "--amino")) abc = esl_alphabet_Create(eslAMINO);
1814
1815 if (esl_opt_IsOn(go, "--informat") &&
1816 (infmt = esl_msafile_EncodeFormat(esl_opt_GetString(go, "--informat"))) == eslMSAFILE_UNKNOWN)
1817 esl_fatal("%s is not a valid MSA file format for --informat", esl_opt_GetString(go, "--informat"));
1818
1819 cfg->fragthresh = esl_opt_GetReal (go, "--fragthresh");
1820 cfg->symfrac = esl_opt_GetReal (go, "--symfrac");
1821 cfg->ignore_rf = esl_opt_GetBoolean(go, "--ignore-rf");
1822 cfg->allow_samp = !esl_opt_GetBoolean(go, "--no-sampling");
1823 cfg->sampthresh = esl_opt_GetInteger(go, "--sampthresh");
1824 cfg->nsamp = esl_opt_GetInteger(go, "--nsamp");
1825 cfg->maxfrag = esl_opt_GetInteger(go, "--maxfrag");
1826 cfg->seed = esl_opt_GetInteger(go, "-s");
1827
1828 if ((status = esl_msafile_Open(&abc, msafile, NULL, infmt, NULL, &afp)) != eslOK)
1829 esl_msafile_OpenFailure(afp, status);
1830
1831 while ((status = esl_msafile_Read(afp, &msa)) == eslOK)
1832 {
1833 nali++;
1834
1835 if ((status = esl_msaweight_PB_adv(cfg, msa, dat)) != eslOK)
1836 esl_fatal("weighting failed");
1837
1838 for (idx = 0; idx < msa->nseq; idx++)
1839 printf("%-25s %.4f\n", msa->sqname[idx], msa->wgt[idx]);
1840
1841
1842 if (dat->cons_by_rf) printf("# consensus by: RF annotation\n");
1843 else if (dat->cons_by_sample) printf("# consensus by: subsampling\n");
1844 else if (dat->cons_by_all) printf("# consensus by: standard rules\n");
1845 else if (dat->cons_allcols) printf("# consensus by: all columns\n");
1846
1847 if (dat->rejected_sample) printf("# (attempted sampling but rejected, too many frags\n");
1848 printf("# sampling allowed? %s\n", cfg->allow_samp ? "yes" : "NO");
1849
1850 printf("# fragthresh: %.4f\n", cfg->fragthresh);
1851 printf("# symfrac: %.4f\n", cfg->symfrac);
1852 if (dat->cons_by_sample)
1853 {
1854 printf("# Info on sampling:\n");
1855 printf("# RNG seed: %" PRIu64 "\n", dat->seed);
1856 printf("# Sample size: %d\n", cfg->nsamp);
1857 printf("# Fragments: %d (<= maxfrag of %d)\n", dat->samp_nfrag, cfg->maxfrag);
1858 }
1859
1860 printf("# number of consensus cols: %d out of %d\n", dat->ncons, (int) msa->alen);
1861 printf("# number of fragments: %d out of %d\n", dat->all_nfrag, msa->nseq);
1862
1863 esl_msa_Destroy(msa);
1864 }
1865 if (nali == 0 || status != eslEOF) esl_msafile_ReadFailure(afp, status); /* a convenience, like esl_msafile_OpenFailure() */
1866
1867 esl_msaweight_cfg_Destroy(cfg);
1868 esl_msaweight_dat_Destroy(dat);
1869 esl_alphabet_Destroy(abc);
1870 esl_msafile_Close(afp);
1871 esl_getopts_Destroy(go);
1872 exit(0);
1873 }
1874 #endif /*eslMSAWEIGHT_EXAMPLE*/