Debian Codegraph @

easel/esl_distance.c

raw symbols SCIP
1 /* Pairwise identities, distances, and distance matrices.
2 *
3 * Contents:
4 * 1. Pairwise distances for aligned text sequences.
5 * 2. Pairwise distances for aligned digital seqs.
6 * 3. Distance matrices for aligned text sequences.
7 * 4. Distance matrices for aligned digital sequences.
8 * 5. Average pairwise identity for multiple alignments.
9 * 6. Private (static) functions.
10 * 7. Unit tests.
11 * 8. Test driver.
12 * 9. Example.
13 */
14 #include <esl_config.h>
15
16 #include <ctype.h>
17 #include <string.h>
18 #include <math.h>
19
20 #include "easel.h"
21 #include "esl_alphabet.h"
22 #include "esl_dmatrix.h"
23 #include "esl_random.h"
24
25 #include "esl_distance.h"
26
27 /* Forward declaration of our static functions.
28 */
29 static int jukescantor(int n1, int n2, int alphabet_size, double *opt_distance, double *opt_variance);
30
31
32 /*****************************************************************
33 * 1. Pairwise distances for aligned text sequences.
34 *****************************************************************/
35
36 /* Function: esl_dst_CPairId()
37 * Synopsis: Pairwise identity of two aligned text strings.
38 * Incept: SRE, Mon Apr 17 20:06:07 2006 [St. Louis]
39 *
40 * Purpose: Calculates pairwise fractional identity between two
41 * aligned character strings <asq1> and <asq2>.
42 * Return this distance in <opt_pid>; return the
43 * number of identities counted in <opt_nid>; and
44 * return the denominator <MIN(len1,len2)> in
45 * <opt_n>.
46 *
47 * Alphabetic symbols <[a-zA-Z]> are compared
48 * case-insensitively for identity. Any nonalphabetic
49 * character is assumed to be a gap symbol.
50 *
51 * This simple comparison rule is unaware of synonyms and
52 * degeneracies in biological alphabets. For a more
53 * sophisticated and biosequence-aware comparison, use
54 * digitized sequences and the <esl_dst_XPairId()> function
55 * instead. Note that currently <esl_dst_XPairId()> does
56 * not correctly handle degeneracies, but is set up to.
57 *
58 * Args: as1 - aligned character string 1
59 * as2 - aligned character string 2
60 * opt_pid - optRETURN: pairwise identity, 0<=x<=1
61 * opt_nid - optRETURN: # of identities
62 * opt_n - optRETURN: denominator MIN(len1,len2)
63 *
64 * Returns: <eslOK> on success. <opt_pid>, <opt_nid>, <opt_n>
65 * contain the answers (for whichever were passed non-NULL).
66 *
67 * Throws: <eslEINVAL> if the strings are different lengths
68 * (not aligned).
69 */
70 int
71 esl_dst_CPairId(const char *as1, const char *as2, double *opt_pid, int *opt_nid, int *opt_n)
72 {
73 int nid; /* total identical positions */
74 int len1, len2; /* lengths of seqs */
75 int i; /* position in aligned seqs */
76 int status;
77
78
79 nid = len1 = len2 = 0;
80 for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
81 {
82 if (isalpha(as1[i])) len1++;
83 if (isalpha(as2[i])) len2++;
84 if (isalpha(as1[i]) && isalpha(as2[i])
85 && toupper(as1[i]) == toupper(as2[i]))
86 nid++;
87 }
88 len1 = ESL_MIN(len1, len2);
89
90 if (as1[i] != '\0' || as2[i] != '\0')
91 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
92
93 if (opt_pid != NULL) *opt_pid = ( len1==0 ? 0. : (double) nid / (double) len1);
94 if (opt_nid != NULL) *opt_nid = nid;
95 if (opt_n != NULL) *opt_n = len1;
96 return eslOK;
97
98 ERROR:
99 if (opt_pid != NULL) *opt_pid = 0.;
100 if (opt_nid != NULL) *opt_nid = 0;
101 if (opt_n != NULL) *opt_n = 0;
102 return status;
103 }
104
105 /* Function: esl_dst_CPairMatch()
106 * Synopsis: Pairwise matches of two aligned text strings.
107 * Incept: ER, Wed Oct 29 09:02:35 EDT 2014 [janelia]
108 *
109 * Purpose: Calculates pairwise fractional matches between two aligned
110 * character strings <asq1> and <asq2>, in the pairHMM
111 * sense, where a match state M is any aligned residue pair
112 * (not necessarily an identity), and I and D are X- and -X
113 * singlets.
114 *
115 * Return the fraction of matches, M / (M+I+D), in
116 * <opt_pmatch>; return the number of matches M counted in
117 * <opt_nmatch>; and return the denominator M+I+D, which is
118 * <alen - double_gaps>, in <*opt_n>.
119 *
120 * Alphabetic symbols <[a-zA-Z]> are compared
121 * case-insensitively for identity. Any nonalphabetic
122 * character is assumed to be a gap symbol.
123 *
124 * This simple comparison rule is unaware of synonyms and
125 * degeneracies in biological alphabets. For a more
126 * sophisticated and biosequence-aware comparison, use
127 * digitized sequences and the <esl_dst_XPairMatch()> function
128 * instead. Note that currently <esl_dst_XPairMatch()> does
129 * not correctly handle degeneracies, but is set up to.
130 *
131 * Args: as1 - aligned character string 1
132 * as2 - aligned character string 2
133 * opt_pm - optRETURN: fraction of M states, M/(M+D+I) [0..1]
134 * opt_nm - optRETURN: # of match states, M
135 * opt_n - optRETURN: denominator alen - double_gaps, M+D+1
136 *
137 * Returns: <eslOK> on success. <opt_pm>, <opt_nm>, <opt_n>
138 * contain the answers (for whichever were passed non-NULL).
139 *
140 * Throws: <eslEINVAL> if the strings are different lengths
141 * (not aligned).
142 */
143 int
144 esl_dst_CPairMatch(const char *as1, const char *as2, double *opt_pm, int *opt_nm, int *opt_n)
145 {
146 int nm; // total matched positions
147 int len; // length of alignment (no double gaps)
148 int i; // position in aligned seqs
149 int status;
150
151 nm = len = 0;
152 for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
153 {
154 if (isalpha(as1[i]) || isalpha(as2[i])) len++;
155 if (isalpha(as1[i]) && isalpha(as2[i])) nm++;
156 }
157 if (as1[i] != '\0' || as2[i] != '\0')
158 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
159
160 if (opt_pm) *opt_pm = ( len==0 ? 0. : (double)nm / (double)len);
161 if (opt_nm) *opt_nm = nm;
162 if (opt_n) *opt_n = len;
163 return eslOK;
164
165 ERROR:
166 if (opt_pm) *opt_pm = 0.;
167 if (opt_nm) *opt_nm = 0;
168 if (opt_n) *opt_n = 0;
169 return status;
170 }
171
172 /* Function: esl_dst_CJukesCantor()
173 * Synopsis: Jukes-Cantor distance for two aligned strings.
174 * Incept: SRE, Tue Apr 18 14:00:37 2006 [St. Louis]
175 *
176 * Purpose: Calculate the generalized Jukes-Cantor distance between
177 * two aligned character strings <as1> and <as2>, in
178 * substitutions/site, for an alphabet of <K> residues
179 * (<K=4> for nucleic acid, <K=20> for proteins). The
180 * maximum likelihood estimate for the distance is
181 * optionally returned in <opt_distance>. The large-sample
182 * variance for the distance estimate is
183 * optionally returned in <opt_variance>.
184 *
185 * Alphabetic symbols <[a-zA-Z]> are compared
186 * case-insensitively to count the number of identities
187 * (<n1>) and mismatches (<n2>>). Any nonalphabetic
188 * character is assumed to be a gap symbol, and aligned
189 * columns containing gap symbols are ignored. The
190 * fractional difference <D> used to calculate the
191 * Jukes/Cantor distance is <n2/n1+n2>.
192 *
193 * Args: K - size of the alphabet (4 or 20)
194 * as1 - 1st aligned seq, 0..L-1, \0-terminated
195 * as2 - 2nd aligned seq, 0..L-1, \0-terminated
196 * opt_distance - optRETURN: ML estimate of distance d
197 * opt_variance - optRETURN: large-sample variance of d
198 *
199 * Returns: <eslOK> on success.
200 *
201 * Infinite distances are possible, in which case distance
202 * and variance are both <HUGE_VAL>. Caller has to deal
203 * with this case as it sees fit, perhaps by enforcing
204 * an arbitrary maximum distance.
205 *
206 * Throws: <eslEINVAL> if the two strings aren't the same length (and
207 * thus can't have been properly aligned).
208 * <eslEDIVZERO> if no aligned residues were counted.
209 * On either failure, distance and variance are both returned
210 * as <HUGE_VAL>.
211 */
212 int
213 esl_dst_CJukesCantor(int K, const char *as1, const char *as2,
214 double *opt_distance, double *opt_variance)
215 {
216 int n1, n2; /* number of observed identities, substitutions */
217 int i; /* position in aligned seqs */
218 int status;
219
220 n1 = n2 = 0;
221 for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
222 {
223 if (isalpha(as1[i]) && isalpha(as2[i]))
224 {
225 if (toupper(as1[i]) == toupper(as2[i])) n1++; else n2++;
226 }
227 }
228 if (as1[i] != '\0' || as2[i] != '\0')
229 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
230
231 return jukescantor(n1, n2, K, opt_distance, opt_variance); /* can throw eslEDIVZERO */
232
233 ERROR:
234 if (opt_distance != NULL) *opt_distance = HUGE_VAL;
235 if (opt_variance != NULL) *opt_variance = HUGE_VAL;
236 return status;
237 }
238
239 /*------- end, pairwise distances for aligned text seqs ---------*/
240
241
242
243
244
245 /*****************************************************************
246 * 2. Pairwise distances for aligned digitized sequences.
247 *****************************************************************/
248
249 /* Function: esl_dst_XPairId()
250 * Synopsis: Pairwise identity of two aligned digital seqs.
251 * Incept: SRE, Tue Apr 18 09:24:05 2006 [St. Louis]
252 *
253 * Purpose: Digital version of <esl_dst_CPairId()>: <ax1> and
254 * <ax2> are digitized aligned sequences, in alphabet
255 * <abc>.
256 *
257 * Only exactly matching codes count as identities;
258 * canonical residues, of course, but also IUPAC degeneracy
259 * codes. (YY is an identity; YC is not.) It would be more
260 * sophisticated to use <esl_abc_Match()> to handle
261 * degeneracies, but doing that would require that
262 * <opt_nid> be changed to an expectation, and a double.
263 *
264 * Args: abc - digital alphabet in use
265 * ax1 - aligned digital seq 1
266 * ax2 - aligned digital seq 2
267 * opt_pid - optRETURN: pairwise identity, 0<=x<=1
268 * opt_nid - optRETURN: # of identities
269 * opt_n - optRETURN: denominator MIN(len1,len2)
270 *
271 * Returns: <eslOK> on success. <opt_pid>, <opt_nid>, <opt_n>
272 * contain the answers, for any of these that were passed
273 * non-<NULL> pointers.
274 *
275 * Throws: <eslEINVAL> if the strings are different lengths (not aligned).
276 */
277 int
278 esl_dst_XPairId(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2,
279 double *opt_pid, int *opt_nid, int *opt_n)
280 {
281 int nid; /* total identical positions */
282 int len1, len2; /* lengths of seqs */
283 int i; /* position in aligned seqs */
284 int status;
285
286 nid = len1 = len2 = 0;
287 for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
288 {
289 if (esl_abc_XIsResidue(abc, ax1[i])) len1++;
290 if (esl_abc_XIsResidue(abc, ax2[i])) len2++;
291 if (esl_abc_XIsResidue(abc, ax1[i]) && esl_abc_XIsResidue(abc, ax2[i]) && ax1[i] == ax2[i]) nid++; // IUPAC degen only counts as identity if code exactly matches
292 }
293 len1 = ESL_MIN(len1, len2);
294
295 if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
296 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
297
298 if (opt_pid) *opt_pid = ( len1==0 ? 0. : (double) nid / (double) len1 );
299 if (opt_nid) *opt_nid = nid;
300 if (opt_n) *opt_n = len1;
301 return eslOK;
302
303 ERROR:
304 if (opt_pid) *opt_pid = 0.;
305 if (opt_nid) *opt_nid = 0;
306 if (opt_n) *opt_n = 0;
307 return status;
308 }
309
310 /* Function: esl_dst_XPairMatch()
311 * Synopsis: Pairwise matches of two aligned digital seqs.
312 * Incept: ER, Wed Oct 29 09:09:07 EDT 2014 [janelia]
313 *
314 * Purpose: Digital version of <esl_dst_CPairMatch()>: <ax1> and
315 * <ax2> are digitized aligned sequences, in alphabet
316 * <abc>.
317 *
318 * IUPAC degeneracy codes count as residues both in
319 * counting match (XX residue/residue) and delete/insert
320 * (X-, -X) states.
321 *
322 * Args: abc - digital alphabet in use
323 * ax1 - aligned digital seq 1
324 * ax2 - aligned digital seq 2
325 * opt_pm - optRETURN: pairwise fractional match states, M/(M+D+I), 0<=x<=1
326 * opt_nm - optRETURN: # of match states, M
327 * opt_n - optRETURN: denominator alen-double_gaps, (M+D+I)
328 *
329 * Returns: <eslOK> on success. <opt_pm>, <opt_nm>, <opt_n>
330 * contain the answers, for any of these that were passed
331 * non-<NULL> pointers.
332 *
333 * Throws: <eslEINVAL> if the strings are different lengths (not aligned).
334 */
335 int
336 esl_dst_XPairMatch(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2, double *opt_pm, int *opt_nm, int *opt_n)
337 {
338 int nm; // total matched positions
339 int len; // length of alignment (no double gaps)
340 int i; // position in aligned seqs
341 int status;
342
343 nm = len = 0;
344 for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
345 {
346 if (esl_abc_XIsResidue(abc, ax1[i]) || esl_abc_XIsResidue(abc, ax2[i])) len++;
347 if (esl_abc_XIsResidue(abc, ax1[i]) && esl_abc_XIsResidue(abc, ax2[i])) nm++;
348 }
349
350 if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
351 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
352
353 if (opt_pm) *opt_pm = ( len==0 ? 0. : (double)nm / (double)len );
354 if (opt_nm) *opt_nm = nm;
355 if (opt_n) *opt_n = len;
356 return eslOK;
357
358 ERROR:
359 if (opt_pm) *opt_pm = 0.;
360 if (opt_nm) *opt_nm = 0;
361 if (opt_n) *opt_n = 0;
362 return status;
363 }
364
365
366 /* Function: esl_dst_XJukesCantor()
367 * Synopsis: Jukes-Cantor distance for two aligned digitized seqs.
368 * Incept: SRE, Tue Apr 18 15:26:51 2006 [St. Louis]
369 *
370 * Purpose: Calculate the generalized Jukes-Cantor distance between two
371 * aligned digital strings <ax1> and <ax2>, in substitutions/site,
372 * using alphabet <abc> to evaluate identities and differences.
373 * The maximum likelihood estimate for the distance is optionally returned in
374 * <opt_distance>. The large-sample variance for the distance
375 * estimate is optionally returned in <opt_variance>.
376 *
377 * Identical to <esl_dst_CJukesCantor()>, except that it takes
378 * digital sequences instead of character strings.
379 *
380 * Args: abc - bioalphabet to use for comparisons
381 * ax1 - 1st digital aligned seq
382 * ax2 - 2nd digital aligned seq
383 * opt_distance - optRETURN: ML estimate of distance d
384 * opt_variance - optRETURN: large-sample variance of d
385 *
386 * Returns: <eslOK> on success. As in <esl_dst_CJukesCantor()>, the
387 * distance and variance may be infinite, in which case they
388 * are returned as <HUGE_VAL>.
389 *
390 * Throws: <eslEINVAL> if the two strings aren't the same length (and
391 * thus can't have been properly aligned).
392 * <eslEDIVZERO> if no aligned residues were counted.
393 * On either failure, the distance and variance are set
394 * to <HUGE_VAL>.
395 */
396 int
397 esl_dst_XJukesCantor(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2, double *opt_distance, double *opt_variance)
398 {
399 int n1, n2; // number of observed identities, substitutions
400 int i; // position in aligned seqs
401 int status;
402
403 n1 = n2 = 0;
404 for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
405 {
406 if (esl_abc_XIsCanonical(abc, ax1[i]) && esl_abc_XIsCanonical(abc, ax2[i]))
407 {
408 if (ax1[i] == ax2[i]) n1++;
409 else n2++;
410 }
411 }
412 if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
413 ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
414
415 return jukescantor(n1, n2, abc->K, opt_distance, opt_variance);
416
417 ERROR:
418 if (opt_distance) *opt_distance = HUGE_VAL;
419 if (opt_variance) *opt_variance = HUGE_VAL;
420 return status;
421 }
422 /*---------- end pairwise distances, digital seqs --------------*/
423
424
425
426
427 /*****************************************************************
428 * 3. Distance matrices for aligned text sequences.
429 *****************************************************************/
430
431 /* Function: esl_dst_CPairIdMx()
432 * Synopsis: NxN identity matrix for N aligned text sequences.
433 * Incept: SRE, Thu Apr 27 08:46:08 2006 [New York]
434 *
435 * Purpose: Given a multiple sequence alignment <as>, consisting
436 * of <N> aligned character strings; calculate
437 * a symmetric fractional pairwise identity matrix by $N(N-1)/2$
438 * calls to <esl_dst_CPairId()>, and return it in
439 * <opt_D>.
440 *
441 * Args: as - aligned seqs (all same length), [0..N-1]
442 * N - # of aligned sequences
443 * ret_S - RETURN: symmetric fractional identity matrix
444 *
445 * Returns: <eslOK> on success, and <ret_S> contains the fractional
446 * identity matrix. Caller free's <S> with
447 * <esl_dmatrix_Destroy()>.
448 *
449 * Throws: <eslEINVAL> if a seq has a different
450 * length than others. On failure, <ret_D> is returned <NULL>
451 * and state of inputs is unchanged.
452 *
453 * <eslEMEM> on allocation failure.
454 */
455 int
456 esl_dst_CPairIdMx(char **as, int N, ESL_DMATRIX **opt_S)
457 {
458 ESL_DMATRIX *S = NULL;
459 int status;
460 int i,j;
461
462 if (( S = esl_dmatrix_Create(N,N) ) == NULL) { status = eslEMEM; goto ERROR; }
463
464 for (i = 0; i < N; i++)
465 {
466 S->mx[i][i] = 1.;
467 for (j = i+1; j < N; j++)
468 {
469 status = esl_dst_CPairId(as[i], as[j], &(S->mx[i][j]), NULL, NULL);
470 if (status != eslOK)
471 ESL_XEXCEPTION(status, "Pairwise identity calculation failed at seqs %d,%d\n", i,j);
472 S->mx[j][i] = S->mx[i][j];
473 }
474 }
475
476 if (opt_S) *opt_S = S; else esl_dmatrix_Destroy(S);
477 return eslOK;
478
479 ERROR:
480 esl_dmatrix_Destroy(S);
481 if (opt_S) *opt_S = NULL;
482 return status;
483 }
484
485
486 /* Function: esl_dst_CDiffMx()
487 * Synopsis: NxN difference matrix for N aligned text sequences.
488 * Incept: SRE, Fri Apr 28 06:27:20 2006 [New York]
489 *
490 * Purpose: Same as <esl_dst_CPairIdMx()>, but calculates
491 * the fractional difference <d=1-s> instead of the
492 * fractional identity <s> for each pair.
493 *
494 * Args: as - aligned seqs (all same length), [0..N-1]
495 * N - # of aligned sequences
496 * opt_D - RETURN: symmetric fractional difference matrix
497 *
498 * Returns: <eslOK> on success, and <opt_D> contains the
499 * fractional difference matrix. Caller free's <D> with
500 * <esl_dmatrix_Destroy()>.
501 *
502 * Throws: <eslEINVAL> if any seq has a different
503 * length than others. On failure, <opt_D> is returned <NULL>
504 * and state of inputs is unchanged.
505 */
506 int
507 esl_dst_CDiffMx(char **as, int N, ESL_DMATRIX **opt_D)
508 {
509 ESL_DMATRIX *D = NULL;
510 int status;
511 int i,j;
512
513 if ((status = esl_dst_CPairIdMx(as, N, &D)) != eslOK) goto ERROR;
514
515 for (i = 0; i < N; i++)
516 {
517 D->mx[i][i] = 0.;
518 for (j = i+1; j < N; j++)
519 {
520 D->mx[i][j] = 1. - D->mx[i][j];
521 D->mx[j][i] = D->mx[i][j];
522 }
523 }
524 if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
525 return eslOK;
526
527 ERROR:
528 esl_dmatrix_Destroy(D);
529 if (opt_D) *opt_D = NULL;
530 return status;
531
532 }
533
534 /* Function: esl_dst_CJukesCantorMx()
535 * Synopsis: NxN Jukes/Cantor distance matrix for N aligned text seqs.
536 * Incept: SRE, Tue Apr 18 16:00:16 2006 [St. Louis]
537 *
538 * Purpose: Given a multiple sequence alignment <aseq>, consisting of
539 * <nseq> aligned character sequences in an alphabet of
540 * <K> letters (usually 4 for DNA, 20 for protein);
541 * calculate a symmetric Jukes/Cantor pairwise distance
542 * matrix for all sequence pairs, and optionally return the distance
543 * matrix in <ret_D>, and optionally return a symmetric matrix of the
544 * large-sample variances for those ML distance estimates
545 * in <ret_V>.
546 *
547 * Infinite distances (and variances) are possible; they
548 * are represented as <HUGE_VAL> in <D> and <V>. Caller must
549 * be prepared to deal with them as appropriate.
550 *
551 * Args: K - size of the alphabet (usually 4 or 20)
552 * as - aligned sequences [0.nseq-1][0..L-1]
553 * N - number of aseqs
554 * opt_D - optRETURN: [0..nseq-1]x[0..nseq-1] symmetric distance mx
555 * opt_V - optRETURN: matrix of variances.
556 *
557 * Returns: <eslOK> on success. <D> and <V> contain the
558 * distance matrix (and variances); caller frees these with
559 * <esl_dmatrix_Destroy()>.
560 *
561 * Throws: <eslEINVAL> if any pair of sequences have differing lengths
562 * (and thus cannot have been properly aligned).
563 * <eslEDIVZERO> if some pair of sequences had no aligned
564 * residues. On failure, <D> and <V> are both returned <NULL>
565 * and state of inputs is unchanged.
566 *
567 * <eslEMEM> on allocation failure.
568 */
569 int
570 esl_dst_CJukesCantorMx(int K, char **as, int N, ESL_DMATRIX **opt_D, ESL_DMATRIX **opt_V)
571 {
572 ESL_DMATRIX *D = NULL;
573 ESL_DMATRIX *V = NULL;
574 int i,j;
575 int status;
576
577 if (( D = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
578 if (( V = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
579
580 for (i = 0; i < N; i++)
581 {
582 D->mx[i][i] = 0.;
583 V->mx[i][i] = 0.;
584 for (j = i+1; j < N; j++)
585 {
586 if ((status = esl_dst_CJukesCantor(K, as[i], as[j], &(D->mx[i][j]), &(V->mx[i][j]))) != eslOK)
587 ESL_XEXCEPTION(status, "J/C calculation failed at seqs %d,%d", i,j);
588
589 D->mx[j][i] = D->mx[i][j];
590 V->mx[j][i] = V->mx[i][j];
591 }
592 }
593 if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
594 if (opt_V) *opt_V = V; else esl_dmatrix_Destroy(V);
595 return eslOK;
596
597 ERROR:
598 esl_dmatrix_Destroy(D);
599 esl_dmatrix_Destroy(V);
600 if (opt_D) *opt_D = NULL;
601 if (opt_V) *opt_V = NULL;
602 return status;
603 }
604 /*----------- end, distance matrices for aligned text seqs ---------*/
605
606
607
608
609 /*****************************************************************
610 * 4. Distance matrices for aligned digital sequences.
611 *****************************************************************/
612
613 /* Function: esl_dst_XPairIdMx()
614 * Synopsis: NxN identity matrix for N aligned digital seqs.
615 * Incept: SRE, Thu Apr 27 09:08:11 2006 [New York]
616 *
617 * Purpose: Given a digitized multiple sequence alignment <ax>, consisting
618 * of <N> aligned digital sequences in alphabet <abc>; calculate
619 * a symmetric pairwise fractional identity matrix by $N(N-1)/2$
620 * calls to <esl_dst_XPairId()>, and return it in <ret_S>.
621 *
622 * Args: abc - digital alphabet in use
623 * ax - aligned dsq's, [0..N-1][1..alen]
624 * N - number of aligned sequences
625 * opt_S - RETURN: NxN matrix of fractional identities
626 *
627 * Returns: <eslOK> on success, and <opt_S> contains the distance
628 * matrix. Caller is obligated to free <S> with
629 * <esl_dmatrix_Destroy()>.
630 *
631 * Throws: <eslEINVAL> if a seq has a different
632 * length than others. On failure, <opt_S> is returned <NULL>
633 * and state of inputs is unchanged.
634 *
635 * <eslEMEM> on allocation failure.
636 */
637 int
638 esl_dst_XPairIdMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_S)
639 {
640 ESL_DMATRIX *S = NULL;
641 int i,j;
642 int status;
643
644 if (( S = esl_dmatrix_Create(N,N) ) == NULL) { status = eslEMEM; goto ERROR; }
645
646 for (i = 0; i < N; i++)
647 {
648 S->mx[i][i] = 1.;
649 for (j = i+1; j < N; j++)
650 {
651 status = esl_dst_XPairId(abc, ax[i], ax[j], &(S->mx[i][j]), NULL, NULL);
652 if (status != eslOK)
653 ESL_XEXCEPTION(status, "Pairwise identity calculation failed at seqs %d,%d\n", i,j);
654 S->mx[j][i] = S->mx[i][j];
655 }
656 }
657 if (opt_S) *opt_S = S; else esl_dmatrix_Destroy(S);
658 return eslOK;
659
660 ERROR:
661 esl_dmatrix_Destroy(S);
662 if (opt_S) *opt_S = NULL;
663 return status;
664 }
665
666
667 /* Function: esl_dst_XDiffMx()
668 * Synopsis: NxN difference matrix for N aligned digital seqs.
669 * Incept: SRE, Fri Apr 28 06:37:29 2006 [New York]
670 *
671 * Purpose: Same as <esl_dst_XPairIdMx()>, but calculates fractional
672 * difference <1-s> instead of fractional identity <s> for
673 * each pair.
674 *
675 * Args: abc - digital alphabet in use
676 * ax - aligned dsq's, [0..N-1][1..alen]
677 * N - number of aligned sequences
678 * opt_D - RETURN: NxN matrix of fractional differences
679 *
680 * Returns: <eslOK> on success, and <opt_D> contains the difference
681 * matrix; caller is obligated to free <D> with
682 * <esl_dmatrix_Destroy()>.
683 *
684 * Throws: <eslEINVAL> if a seq has a different
685 * length than others. On failure, <opt_D> is returned <NULL>
686 * and state of inputs is unchanged.
687 */
688 int
689 esl_dst_XDiffMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_D)
690 {
691 ESL_DMATRIX *D = NULL;
692 int i,j;
693 int status;
694
695 if ((status = esl_dst_XPairIdMx(abc, ax, N, &D)) != eslOK) goto ERROR;
696
697 for (i = 0; i < N; i++)
698 {
699 D->mx[i][i] = 0.;
700 for (j = i+1; j < N; j++)
701 {
702 D->mx[i][j] = 1. - D->mx[i][j];
703 D->mx[j][i] = D->mx[i][j];
704 }
705 }
706 if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
707 return eslOK;
708
709 ERROR:
710 esl_dmatrix_Destroy(D);
711 if (opt_D) *opt_D = NULL;
712 return status;
713 }
714
715 /* Function: esl_dst_XJukesCantorMx()
716 * Synopsis: NxN Jukes/Cantor distance matrix for N aligned digital seqs.
717 * Incept: SRE, Thu Apr 27 08:38:08 2006 [New York City]
718 *
719 * Purpose: Given a digitized multiple sequence alignment <ax>,
720 * consisting of <nseq> aligned digital sequences in
721 * bioalphabet <abc>, calculate a symmetric Jukes/Cantor
722 * pairwise distance matrix for all sequence pairs;
723 * optionally return the distance matrix in <ret_D> and
724 * a matrix of the large-sample variances for those ML distance
725 * estimates in <ret_V>.
726 *
727 * Infinite distances (and variances) are possible. They
728 * are represented as <HUGE_VAL> in <D> and <V>. Caller must
729 * be prepared to deal with them as appropriate.
730 *
731 * Args: abc - bioalphabet for <aseq>
732 * ax - aligned digital sequences [0.nseq-1][1..L]
733 * N - number of aseqs
734 * opt_D - optRETURN: [0..nseq-1]x[0..nseq-1] symmetric distance mx
735 * opt_V - optRETURN: matrix of variances.
736 *
737 * Returns: <eslOK> on success. <opt_D> and <opt_V>, if provided, contain the
738 * distance matrix and variances. Caller frees these with
739 * <esl_dmatrix_Destroy()>.
740 *
741 * Throws: <eslEINVAL> if any pair of sequences have differing lengths
742 * (and thus cannot have been properly aligned).
743 * <eslEDIVZERO> if some pair of sequences had no aligned
744 * residues. On failure, <opt_D> and <opt_V> are both returned <NULL>
745 * and state of inputs is unchanged.
746 *
747 * <eslEMEM> on allocation failure.
748 */
749 int
750 esl_dst_XJukesCantorMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_D, ESL_DMATRIX **opt_V)
751 {
752 ESL_DMATRIX *D = NULL;
753 ESL_DMATRIX *V = NULL;
754 int status;
755 int i,j;
756
757 if (( D = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
758 if (( V = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
759
760 for (i = 0; i < N; i++)
761 {
762 D->mx[i][i] = 0.;
763 V->mx[i][i] = 0.;
764 for (j = i+1; j < N; j++)
765 {
766 if ((status = esl_dst_XJukesCantor(abc, ax[i], ax[j], &(D->mx[i][j]), &(V->mx[i][j]))) != eslOK)
767 ESL_XEXCEPTION(status, "J/C calculation failed at digital aseqs %d,%d", i,j);
768
769 D->mx[j][i] = D->mx[i][j];
770 V->mx[j][i] = V->mx[i][j];
771 }
772 }
773 if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
774 if (opt_V) *opt_V = V; else esl_dmatrix_Destroy(V);
775 return eslOK;
776
777 ERROR:
778 esl_dmatrix_Destroy(D);
779 esl_dmatrix_Destroy(V);
780 if (opt_D) *opt_D = NULL;
781 if (opt_V) *opt_V = NULL;
782 return status;
783 }
784 /*------- end, distance matrices for digital alignments ---------*/
785
786
787
788 /*****************************************************************
789 * 5. Average pairwise identity for multiple alignments
790 *****************************************************************/
791
792 /* Function: esl_dst_CAverageId()
793 * Synopsis: Calculate avg identity for multiple alignment
794 * Incept: SRE, Fri May 18 15:02:38 2007 [Janelia]
795 *
796 * Purpose: Calculates the average pairwise fractional identity in
797 * a multiple sequence alignment <as>, consisting of <N>
798 * aligned character sequences of identical length.
799 *
800 * If an exhaustive calculation would require more than
801 * <max_comparisons> pairwise comparisons, then instead of
802 * looking at all pairs, calculate the average over a
803 * stochastic sample of <max_comparisons> random pairs.
804 * This allows the routine to work efficiently even on very
805 * deep MSAs.
806 *
807 * Each fractional pairwise identity (range $[0..$ pid $..1]$
808 * is calculated using <esl_dst_CPairId()>.
809 *
810 * Returns: <eslOK> on success, and <*opt_avgid> contains the average
811 * fractional identity.
812 *
813 * Throws: <eslEMEM> on allocation failure.
814 * <eslEINVAL> if any of the aligned sequence pairs aren't
815 * of the same length.
816 * In either case, <*opt_avgid> is set to 0.
817 */
818 int
819 esl_dst_CAverageId(char **as, int N, int max_comparisons, double *opt_avgid)
820 {
821 ESL_RANDOMNESS *rng = NULL;
822 double avgid = 0.;
823 double id;
824 int i,j,k;
825 int status;
826
827 if (N <= 1) // by convention, with no pairwise comparisons for N=0|1, set pid = 1.0
828 {
829 avgid = 1.0;
830 }
831 else if (N <= max_comparisons && // if N is small enough that we can average exhaustively over all pairwise comparisons...
832 N <= sqrt(2. * max_comparisons) && // (beware numerical overflow of N^2)
833 (N * (N-1) / 2) <= max_comparisons)
834 {
835 for (i = 0; i < N; i++)
836 for (j = i+1; j < N; j++)
837 {
838 if ((status = esl_dst_CPairId(as[i], as[j], &id, NULL, NULL)) != eslOK) return status;
839 avgid += id;
840 }
841 avgid /= (double) (N * (N-1) / 2);
842 }
843 else // If nseq is large, calculate average over a stochastic sample.
844 {
845 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
846
847 for (k = 0; k < max_comparisons; k++)
848 {
849 do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
850 if ((status = esl_dst_CPairId(as[i], as[j], &id, NULL, NULL)) != eslOK) return status;
851 avgid += id;
852 }
853 avgid /= (double) max_comparisons;
854 }
855
856 esl_randomness_Destroy(rng);
857 if (opt_avgid) *opt_avgid = avgid;
858 return eslOK;
859
860 ERROR:
861 esl_randomness_Destroy(rng);
862 if (opt_avgid) *opt_avgid = 0.;
863 return status;
864 }
865
866 /* Function: esl_dst_CAverageMatch()
867 * Synopsis: Calculate avg matches for multiple alignment
868 * Incept: ER, Wed Oct 29 09:25:09 EDT 2014 [Janelia]
869 *
870 * Purpose: Calculates the average pairwise fractional matches M/(M+D+I) in
871 * a multiple sequence alignment <as>, consisting of <N>
872 * aligned character sequences of identical length. M,D,I
873 * are in the pair-HMM state sense: M means any aligned pair,
874 * including both mismatches and identities.
875 *
876 * If an exhaustive calculation would require more than
877 * <max_comparisons> pairwise comparisons, then instead of
878 * looking at all pairs, calculate the average over a
879 * stochastic sample of <max_comparisons> random pairs.
880 * This allows the routine to work efficiently even on very
881 * deep MSAs.
882 *
883 * Each fractional pairwise matches (range $[0..$ pm $..1]$
884 * is calculated using <esl_dst_CPairMatch()>.
885 *
886 * Returns: <eslOK> on success, and <*ret_avgpm> contains the average
887 * fractional matches.
888 *
889 * Throws: <eslEMEM> on allocation failure.
890 * <eslEINVAL> if any of the aligned sequence pairs aren't
891 * of the same length.
892 * In either case, <*ret_avgpm> is set to 0.
893 */
894 int
895 esl_dst_CAverageMatch(char **as, int N, int max_comparisons, double *opt_avgpm)
896 {
897 ESL_RANDOMNESS *rng = NULL;
898 double avgpm = 0.;
899 double pmatch;
900 int i,j,k;
901 int status;
902
903 if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
904 { // Set a convention of id = 1.0 for the case of no pairwise comparisons
905 avgpm = 1.0;
906 }
907 else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
908 N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
909 (N * (N-1) / 2) <= max_comparisons)
910 {
911 for (i = 0; i < N; i++)
912 for (j = i+1; j < N; j++)
913 {
914 if ((status = esl_dst_CPairMatch(as[i], as[j], &pmatch, NULL, NULL)) != eslOK) return status;
915 avgpm += pmatch;
916 }
917 avgpm /= (double) (N * (N-1) / 2);
918 }
919 else /* If nseq is large, calculate average over a stochastic sample. */
920 {
921 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
922
923 for (k = 0; k < max_comparisons; k++)
924 {
925 do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
926 if ((status = esl_dst_CPairMatch(as[i], as[j], &pmatch, NULL, NULL)) != eslOK) return status;
927 avgpm += pmatch;
928 }
929 avgpm /= (double) max_comparisons;
930 }
931
932 esl_randomness_Destroy(rng);
933 if (opt_avgpm) *opt_avgpm = avgpm;
934 return eslOK;
935
936 ERROR:
937 esl_randomness_Destroy(rng);
938 if (opt_avgpm) *opt_avgpm = 0.;
939 return status;
940 }
941
942 /* Function: esl_dst_XAverageId()
943 * Synopsis: Calculate avg identity for digital MSA
944 * Incept: SRE, Fri May 18 15:19:14 2007 [Janelia]
945 *
946 * Purpose: Calculates the average pairwise fractional identity in
947 * a digital multiple sequence alignment <ax>, consisting of <N>
948 * aligned digital sequences of identical length.
949 *
950 * If an exhaustive calculation would require more than
951 * <max_comparisons> pairwise comparisons, then instead of
952 * looking at all pairs, calculate the average over a
953 * stochastic sample of <max_comparisons> random pairs.
954 * This allows the routine to work efficiently even on very
955 * deep MSAs.
956 *
957 * Each fractional pairwise identity (range $[0..$ pid $..1]$
958 * is calculated using <esl_dst_XPairId()>.
959 *
960 * Returns: <eslOK> on success, and <*ret_id> contains the average
961 * fractional identity.
962 *
963 * Throws: <eslEMEM> on allocation failure.
964 * <eslEINVAL> if any of the aligned sequence pairs aren't
965 * of the same length.
966 * In either case, <*ret_id> is set to 0.
967 */
968 int
969 esl_dst_XAverageId(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, int max_comparisons, double *opt_avgid)
970 {
971 ESL_RANDOMNESS *rng = NULL;
972 double avgid = 0.;
973 double id;
974 int i,j,k;
975 int status;
976
977 if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
978 { // Set a convention of id = 1.0 for the case of no pairwise comparisons
979 avgid = 1.;
980 }
981 else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
982 N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
983 (N * (N-1) / 2) <= max_comparisons)
984 {
985 for (i = 0; i < N; i++)
986 for (j = i+1; j < N; j++)
987 {
988 if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) return status;
989 avgid += id;
990 }
991 avgid /= (double) (N * (N-1) / 2);
992 }
993 else /* If nseq is large, calculate average over a stochastic sample. */
994 {
995 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
996
997 for (k = 0; k < max_comparisons; k++)
998 {
999 do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
1000 if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) return status;
1001 avgid += id;
1002 }
1003 avgid /= (double) max_comparisons;
1004 }
1005
1006 if (rng) esl_randomness_Destroy(rng);
1007 if (opt_avgid) *opt_avgid = avgid;
1008 return eslOK;
1009
1010 ERROR:
1011 if (rng) esl_randomness_Destroy(rng);
1012 if (opt_avgid) *opt_avgid = 0.;
1013 return status;
1014 }
1015
1016
1017 /* Function: esl_dst_XAverageMatch()
1018 * Synopsis: Calculate avg matches for digital MSA
1019 * Incept: ER, ed Oct 29 09:29:05 EDT 2014 [Janelia]
1020 *
1021 * Purpose: Calculates the average pairwise fractional matches in
1022 * a digital multiple sequence alignment <ax>, consisting of <N>
1023 * aligned digital sequences of identical length.
1024 *
1025 * If an exhaustive calculation would require more than
1026 * <max_comparisons> pairwise comparisons, then instead of
1027 * looking at all pairs, calculate the average over a
1028 * stochastic sample of <max_comparisons> random pairs.
1029 * This allows the routine to work efficiently even on very
1030 * deep MSAs.
1031 *
1032 * Each fractional pairwise matches (range $[0..$ pm $..1]$
1033 * is calculated using <esl_dst_XPairMatch()>.
1034 *
1035 * Returns: <eslOK> on success, and <*opt_avgpm> contains the average
1036 * fractional identity.
1037 *
1038 * Throws: <eslEMEM> on allocation failure.
1039 * <eslEINVAL> if any of the aligned sequence pairs aren't
1040 * of the same length.
1041 * In either case, <*ret_avgpm> is set to 0.
1042 */
1043 int
1044 esl_dst_XAverageMatch(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, int max_comparisons, double *opt_avgpm)
1045 {
1046 ESL_RANDOMNESS *rng = NULL;
1047 double avgpm = 0.;
1048 double pm;
1049 int i,j,k;
1050 int status;
1051
1052 if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
1053 { // Set a convention of pm = 1.0 for the case of no pairwise comparisons
1054 avgpm = 1.;
1055 }
1056 else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
1057 N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
1058 (N * (N-1) / 2) <= max_comparisons)
1059 {
1060 for (i = 0; i < N; i++)
1061 for (j = i+1; j < N; j++)
1062 {
1063 if ((status = esl_dst_XPairMatch(abc, ax[i], ax[j], &pm, NULL, NULL)) != eslOK) return status;
1064 avgpm += pm;
1065 }
1066 avgpm /= (double) (N * (N-1) / 2);
1067 }
1068 else /* If nseq is large, calculate average over a stochastic sample. */
1069 {
1070 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
1071
1072 for (k = 0; k < max_comparisons; k++)
1073 {
1074 do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
1075 if ((status = esl_dst_XPairMatch(abc, ax[i], ax[j], &pm, NULL, NULL)) != eslOK) return status;
1076 avgpm += pm;
1077 }
1078 avgpm /= (double) max_comparisons;
1079 }
1080
1081 if (rng) esl_randomness_Destroy(rng);
1082 if (opt_avgpm) *opt_avgpm = avgpm;
1083 return eslOK;
1084
1085 ERROR:
1086 if (rng) esl_randomness_Destroy(rng);
1087 if (opt_avgpm) *opt_avgpm = 0.;
1088 return status;
1089 }
1090
1091 /* Function: esl_dst_XAvgConnectivity()
1092 * Synopsis: Calculate both avg identity and connectivity for digital MSA
1093 * Incept: SRE, Sat 07 May 2022
1094 *
1095 * Purpose: Calculates average connectivity: the fraction of sequence
1096 * pairs with fractional pairwise identity >
1097 * <idthresh>. Also calculates average fractional pairwise
1098 * identity, since it's efficient to calculate avg id and
1099 * connectivity at the same time. The input is a digital
1100 * multiple sequence alignment <ax> of <N> sequences in
1101 * alphabet <abc>.
1102 *
1103 * As in <esl_dsq_XAvgId()>, if an exhaustive calculation
1104 * would require more than <max_comparisons> pairwise
1105 * comparisons, then instead of looking at all pairs,
1106 * calculate the average over a stochastic sample of
1107 * <max_comparisons> random pairs. This allows the routine
1108 * to work efficiently even on very deep MSAs.
1109 *
1110 * Each fractional pairwise identity (range $[0..$ pid $..1]$
1111 * is calculated using <esl_dst_XPairId()>. The calculation
1112 * is # of identities / unaligned length of shorter seq.
1113 *
1114 * Only makes sense for N > 1, so that there are pairwise
1115 * comparisons to make; but we may encounter N = 1 or N = 0
1116 * as edge cases of single sequence or empty alignments.
1117 * In this case, avgid and avgconn are set to 1.0 by
1118 * convention.
1119 *
1120 * Args: abc - digital alphabet
1121 * ax - array of digital aligned seqs
1122 * N - number of seqs in <ax>
1123 * max_comparisons - switch to a stochastic sample if N(N-1)/2 > this
1124 * idthresh - count pairs as linked when they have identity > this threshold [0..1]
1125 * opt_avgid - optRETURN: average identity [0..1]
1126 * opt_avgconn - optRETURN: average connectivity [0..1]
1127 *
1128 * Returns: <eslOK> on success, and <*opt_avgid> and <*opt_avgconn>, if
1129 * provided, contain avgid and avgconn.
1130 *
1131 * Throws: <eslEMEM> on allocation failure;
1132 * <eslEINVAL> if any aligned seq pair aren't of same length.
1133 * <*opt_avgid> and <*opt_avgconn> (if provided) are set to 0.
1134 *
1135 * Xref: Adapted from a previous version, esl_dst_Connectivity(), from
1136 * Sam Petti in Sept 2020. Where we calculate connectivity
1137 * (e.g. in profmark), we also need to calc avg identity,
1138 * and it's more efficient to calculate both at once.
1139 */
1140 int
1141 esl_dst_XAvgConnectivity(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, int max_comparisons, double idthresh, double *opt_avgid, double *opt_avgconn)
1142 {
1143 ESL_RANDOMNESS *rng = NULL;
1144 double avgid = 0.;
1145 double avgconn = 0.;
1146 double id;
1147 int i,j,k;
1148 int status;
1149
1150 if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
1151 { // Set a convention of id = 1.0 and conn = 1.0 for the case of no pairwise comparisons
1152 avgid = avgconn = 1.;
1153 }
1154 else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
1155 N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
1156 (N * (N-1) / 2) <= max_comparisons)
1157 {
1158 for (i = 0; i < N; i++)
1159 for (j = i+1; j < N; j++)
1160 {
1161 if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) goto ERROR;
1162 if (id > idthresh) avgconn += 1.;
1163 avgid += id;
1164 }
1165 avgid /= (double) (N * (N-1) / 2);
1166 avgconn /= (double) (N * (N-1) / 2);
1167 }
1168 else // for large N, calculate averages over a reproducible stochastic sample.
1169 {
1170 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
1171
1172 for (k = 0; k < max_comparisons; k++)
1173 {
1174 do {
1175 i = esl_rnd_Roll(rng, N);
1176 j = esl_rnd_Roll(rng, N);
1177 } while (j == i); /* make sure j != i */
1178
1179 if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) goto ERROR;
1180 if (id > idthresh) avgconn += 1.;
1181 avgid += id;
1182 }
1183 avgid /= (double) max_comparisons;
1184 avgconn /= (double) max_comparisons;
1185 }
1186
1187 if (rng) esl_randomness_Destroy(rng);
1188 if (opt_avgid) *opt_avgid = avgid;
1189 if (opt_avgconn) *opt_avgconn = avgconn;
1190 return eslOK;
1191
1192 ERROR:
1193 if (rng) esl_randomness_Destroy(rng);
1194 if (opt_avgid) *opt_avgid = 0.;
1195 if (opt_avgconn) *opt_avgconn = 0.;
1196 return status;
1197 }
1198
1199
1200 /* Function: esl_dst_XAvgSubsetConnectivity()
1201 * Synopsis: Like esl_dst_XAvgSubsetConnectivity(), but for a subset of the MSA
1202 * Incept: SRE, Thu 12 May 2022
1203 *
1204 * Purpose: Calculate average identity and average connectivity as in
1205 * <esl_dst_XAvgConnectivity()>, for a subset of the sequences
1206 * in the input <msa>. The subset is defined by an array of
1207 * <nV> sequence indices <V>: <V[0..nV-1] = 0..nseq-1>.
1208 *
1209 * (This was written for HMMER's create-profmark, which
1210 * does a bunch of manipulation of MSA subsets, and for
1211 * efficiency reasons, it doesn't explicitly extract new
1212 * MSAs for them.)
1213 *
1214 * Args: abc - digital alphabet
1215 * ax - array of digital aligned seqs
1216 * N - number of seqs in <ax>
1217 * V - array of seq indices in the subset; V[0..nV-1] = 0..nseq-1
1218 * nV - number of seqs in the subset; nV <= N
1219 * max_comparisons - switch to a stochastic sample if N(N-1)/2 > this
1220 * idthresh - count pairs as linked when they have identity > this threshold [0..1]
1221 * opt_avgid - optRETURN: average identity [0..1]
1222 * opt_avgconn - optRETURN: average connectivity [0..1]
1223 *
1224 * Returns: <eslOK> on success, and <*opt_avgid> and <*opt_avgconn>, if
1225 * provided, contain avgid and avgconn.
1226 *
1227 * Throws: <eslEMEM> on allocation failure;
1228 * <eslEINVAL> if any aligned seq pair aren't of same length.
1229 * <*opt_avgid> and <*opt_avgconn> (if provided) are set to 0.
1230 */
1231 int
1232 esl_dst_XAvgSubsetConnectivity(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, int *V, int nV, int max_comparisons, double idthresh, double *opt_avgid, double *opt_avgconn)
1233 {
1234 ESL_RANDOMNESS *rng = NULL;
1235 double avgid = 0.;
1236 double avgconn = 0.;
1237 double id;
1238 int i,j,k;
1239 int status;
1240
1241 ESL_DASSERT1(( nV <= N )); // indices in V[0..nV-1] are a subset of 0..N-1
1242
1243 if (nV <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
1244 { // Set a convention of id = 1.0 and conn = 1.0 for the case of no pairwise comparisons
1245 avgid = avgconn = 1.;
1246 }
1247 else if (nV <= max_comparisons && // Is nV small enough that we can average over all pairwise comparisons?
1248 nV <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, nV(nV-1)/2 can overflow.
1249 (nV * (nV-1) / 2) <= max_comparisons)
1250 {
1251 for (i = 0; i < nV; i++)
1252 for (j = i+1; j < nV; j++)
1253 {
1254 ESL_DASSERT1(( V[i] >= 0 && V[i] <= N && V[j] >= 0 && V[j] <= N ));
1255 if ((status = esl_dst_XPairId(abc, ax[V[i]], ax[V[j]], &id, NULL, NULL)) != eslOK) goto ERROR;
1256 if (id > idthresh) avgconn += 1.;
1257 avgid += id;
1258 }
1259 avgid /= (double) (nV * (nV-1) / 2);
1260 avgconn /= (double) (nV * (nV-1) / 2);
1261 }
1262 else // for large nV, calculate averages over a reproducible stochastic sample.
1263 {
1264 if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
1265
1266 for (k = 0; k < max_comparisons; k++)
1267 {
1268 do {
1269 i = esl_rnd_Roll(rng, nV);
1270 j = esl_rnd_Roll(rng, nV);
1271 } while (j == i); /* make sure j != i */
1272
1273 ESL_DASSERT1(( V[i] >= 0 && V[i] <= N && V[j] >= 0 && V[j] <= N ));
1274 if ((status = esl_dst_XPairId(abc, ax[V[i]], ax[V[j]], &id, NULL, NULL)) != eslOK) goto ERROR;
1275 if (id > idthresh) avgconn += 1.;
1276 avgid += id;
1277 }
1278 avgid /= (double) max_comparisons;
1279 avgconn /= (double) max_comparisons;
1280 }
1281
1282 if (rng) esl_randomness_Destroy(rng);
1283 if (opt_avgid) *opt_avgid = avgid;
1284 if (opt_avgconn) *opt_avgconn = avgconn;
1285 return eslOK;
1286
1287 ERROR:
1288 if (rng) esl_randomness_Destroy(rng);
1289 if (opt_avgid) *opt_avgid = 0.;
1290 if (opt_avgconn) *opt_avgconn = 0.;
1291 return status;
1292 }
1293
1294
1295
1296 /*****************************************************************
1297 * 6. Private (static) functions
1298 *****************************************************************/
1299
1300
1301 /* jukescantor()
1302 *
1303 * The generalized Jukes/Cantor distance calculation.
1304 * Given <n1> identities and <n2> differences, for a
1305 * base alphabet size of <alphabet_size> (4 or 20);
1306 * calculate J/C distance in substitutions/site and
1307 * return it in <ret_distance>; calculate large-sample
1308 * variance and return it in <ret_variance>.
1309 *
1310 * Returns <eslEDIVZERO> if there are no data (<n1+n2=0>).
1311 */
1312 static int
1313 jukescantor(int n1, int n2, int alphabet_size, double *opt_distance, double *opt_variance)
1314 {
1315 int status;
1316 double D, K, N;
1317 double x;
1318 double distance, variance;
1319
1320 ESL_DASSERT1( (n1 >= 0) );
1321 ESL_DASSERT1( (n2 >= 0) );
1322 ESL_DASSERT1( (alphabet_size >= 0) );
1323
1324 if (n1+n2 == 0) { status = eslEDIVZERO; goto ERROR; }
1325
1326 K = (double) alphabet_size;
1327 D = (double) n2 / (double) (n1+n2);
1328 N = (double) (n1+n2);
1329
1330 x = 1. - D * K/(K-1.);
1331 if (x <= 0.)
1332 {
1333 distance = HUGE_VAL;
1334 variance = HUGE_VAL;
1335 }
1336 else
1337 {
1338 distance = -log(x) * K/(K-1);
1339 variance = exp( 2.*K*distance/(K-1) ) * D * (1.-D) / N;
1340 }
1341 if (opt_distance != NULL) *opt_distance = distance;
1342 if (opt_variance != NULL) *opt_variance = variance;
1343 return eslOK;
1344
1345 ERROR:
1346 if (opt_distance != NULL) *opt_distance = HUGE_VAL;
1347 if (opt_variance != NULL) *opt_variance = HUGE_VAL;
1348 return status;
1349 }
1350 /*--------------- end of private functions ----------------------*/
1351
1352
1353 /*****************************************************************
1354 * 7. Unit tests.
1355 *****************************************************************/
1356 #ifdef eslDISTANCE_TESTDRIVE
1357
1358 #include "esl_msa.h"
1359 #include "esl_msafile.h"
1360 #include "esl_vectorops.h"
1361
1362 /* Each unit test has access to the same small test alignment
1363 * and predetermined pairwise identities and # of matches.
1364 *
1365 * At least one comparison should be 0% identity, to exercise one of
1366 * the cases in jukes-cantor distance calculations. Here, seq0/seq2.
1367 *
1368 * The alignment contains only canonical residues, because one of our
1369 * tests is that C and X functions give the same results.
1370 *
1371 * You can change the alignment and the associated static data here.
1372 * The unit tests don't make any assumptions of their own about the
1373 * example alignment.
1374 */
1375 static char testmsa[] = "\
1376 # STOCKHOLM 1.0\n\
1377 \n\
1378 seq0 .AAAA.AAAA\n\
1379 seq1 ...AA.AC..\n\
1380 seq2 .CCCC.CCCC\n\
1381 seq3 ....A.AAC.\n\
1382 //";
1383 static double true_pid[4][4] = { { 1.0, 0.75, 0.0, 0.75 },
1384 { 0.75, 1.0, 0.25, 0.5 },
1385 { 0.0, 0.25, 1.0, 0.25 },
1386 { 0.75, 0.5, 0.25, 1.0 } };
1387 static int true_nid[4][4] = { { 8, 3, 0, 3 },
1388 { 3, 4, 1, 2 },
1389 { 0, 1, 8, 1 },
1390 { 3, 2, 1, 4 } };
1391 static int true_len[4] = { 8, 4, 8, 4 };
1392 static int true_M[4][4] = { { 8, 4, 8, 4 },
1393 { 4, 4, 4, 3 },
1394 { 8, 4, 8, 4 },
1395 { 4, 3, 4, 4 } };
1396 static int true_MDI[4][4] = { { 8, 8, 8, 8 },
1397 { 8, 4, 8, 5 },
1398 { 8, 8, 8, 8 },
1399 { 8, 5, 8, 4 } };
1400
1401 static void
1402 create_testmsa(ESL_ALPHABET **ret_abc, ESL_MSA **ret_cmsa, ESL_MSA **ret_xmsa)
1403 {
1404 ESL_ALPHABET *abc = esl_alphabet_Create(eslDNA);
1405 ESL_MSA *cmsa = esl_msa_CreateFromString(testmsa, eslMSAFILE_STOCKHOLM);
1406 ESL_MSA *xmsa = esl_msa_Clone(cmsa);
1407 char errmsg[eslERRBUFSIZE];
1408
1409 if ( esl_msa_Digitize(abc, xmsa, errmsg) != eslOK) esl_fatal("esl_distance create_testmsa failed:\n%s\n", errmsg);
1410 *ret_abc = abc;
1411 *ret_cmsa = cmsa;
1412 *ret_xmsa = xmsa;
1413 }
1414
1415 static void
1416 utest_pairs(const ESL_ALPHABET *abc, ESL_DSQ **ax, char **as, int N)
1417 {
1418 char msg[] = "esl_distance::utest_pairs failed";
1419 double pid_c, pid_x, mpid_c, mpid_x;
1420 int nid_x, nid_c, mnid_c, mnid_x;
1421 int nres_x, nres_c, mn_c, mn_x;
1422 double jcd_x, jcd_c;
1423 double jcv_x, jcv_c;
1424 int i,j;
1425
1426 for (i = 0; i < N; i++)
1427 for (j = 0; j < N; j++)
1428 {
1429 if ( esl_dst_CPairId ( as[i], as[j], &pid_c, &nid_c, &nres_c) != eslOK) esl_fatal(msg);
1430 if ( esl_dst_CPairMatch ( as[i], as[j], &mpid_c, &mnid_c, &mn_c) != eslOK) esl_fatal(msg);
1431 if ( esl_dst_CJukesCantor(abc->K, as[i], as[j], &jcd_c, &jcv_c) != eslOK) esl_fatal(msg);
1432
1433 if ( esl_dst_XPairId (abc, ax[i], ax[j], &pid_x, &nid_x, &nres_x) != eslOK) esl_fatal(msg);
1434 if ( esl_dst_XPairMatch (abc, ax[i], ax[j], &mpid_x, &mnid_x, &mn_x) != eslOK) esl_fatal(msg);
1435 if ( esl_dst_XJukesCantor(abc, ax[i], ax[j], &jcd_x, &jcv_x) != eslOK) esl_fatal(msg);
1436
1437 if ( esl_DCompare( true_pid[i][j], pid_c, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1438 if ( esl_DCompare( true_pid[i][j], pid_x, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1439 if ( nid_c != true_nid[i][j] ) esl_fatal(msg);
1440 if ( nid_x != true_nid[i][j] ) esl_fatal(msg);
1441 if ( nres_c != ESL_MIN(true_len[i], true_len[j]) ) esl_fatal(msg);
1442 if ( nres_x != ESL_MIN(true_len[i], true_len[j]) ) esl_fatal(msg);
1443 if ( mnid_c != true_M[i][j] ) esl_fatal(msg);
1444 if ( mnid_x != true_M[i][j] ) esl_fatal(msg);
1445 if ( mn_c != true_MDI[i][j] ) esl_fatal(msg);
1446 if ( mn_x != true_MDI[i][j] ) esl_fatal(msg);
1447 if ( esl_DCompare( (double) true_M[i][j] / (double) true_MDI[i][j], mpid_c, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1448 if ( esl_DCompare( (double) true_M[i][j] / (double) true_MDI[i][j], mpid_x, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1449
1450 if (true_pid[i][j] == 1.0 && (jcd_c != 0.0 || jcd_x != 0.0)) esl_fatal(msg); // 100% identity, including self-comparisons, give distance = 0.
1451 if (true_pid[i][j] < 1./(double)abc->K && (jcd_c != HUGE_VAL || jcd_x != HUGE_VAL)) esl_fatal(msg); // <1/K pid gives infinite distance (HUGE_VAL)
1452 }
1453
1454 /* API accepts NULL for return values */
1455 if (esl_dst_CPairId ( as[0], as[0], NULL, NULL, NULL) != eslOK) esl_fatal(msg);
1456 if (esl_dst_CPairMatch ( as[0], as[0], NULL, NULL, NULL) != eslOK) esl_fatal(msg);
1457 if (esl_dst_CJukesCantor(abc->K, as[0], as[0], NULL, NULL) != eslOK) esl_fatal(msg);
1458 if (esl_dst_XPairId (abc, ax[0], ax[0], NULL, NULL, NULL) != eslOK) esl_fatal(msg);
1459 if (esl_dst_XPairMatch (abc, ax[0], ax[0], NULL, NULL, NULL) != eslOK) esl_fatal(msg);
1460 if (esl_dst_XJukesCantor(abc, ax[0], ax[0], NULL, NULL) != eslOK) esl_fatal(msg);
1461 }
1462
1463
1464 static void
1465 utest_matrices(const ESL_ALPHABET *abc, ESL_DSQ **ax, char **as, int N)
1466 {
1467 char msg[] = "esl_distance::utest_matrices failed";
1468 ESL_DMATRIX *id_c = NULL;
1469 ESL_DMATRIX *id_x = NULL;
1470 ESL_DMATRIX *diff_c = NULL;
1471 ESL_DMATRIX *diff_x = NULL;
1472 ESL_DMATRIX *jcd_c = NULL;
1473 ESL_DMATRIX *jcd_x = NULL;
1474 ESL_DMATRIX *jcV_c = NULL;
1475 ESL_DMATRIX *jcV_x = NULL;
1476 int i,j;
1477
1478 if ( esl_dst_CPairIdMx ( as, N, &id_c) != eslOK) esl_fatal(msg);
1479 if ( esl_dst_CDiffMx ( as, N, &diff_c) != eslOK) esl_fatal(msg);
1480 if ( esl_dst_CJukesCantorMx(abc->K, as, N, &jcd_c, &jcV_c) != eslOK) esl_fatal(msg);
1481
1482 if ( esl_dst_XPairIdMx (abc, ax, N, &id_x) != eslOK) esl_fatal(msg);
1483 if ( esl_dst_XDiffMx (abc, ax, N, &diff_x) != eslOK) esl_fatal(msg);
1484 if ( esl_dst_XJukesCantorMx(abc, ax, N, &jcd_x, &jcV_x) != eslOK) esl_fatal(msg);
1485
1486 for (i = 0; i < N; i++)
1487 for (j = 0; j < N; j++)
1488 {
1489 if (esl_DCompare( true_pid[i][j], id_c->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1490 if (esl_DCompare( true_pid[i][j], id_x->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1491 if (esl_DCompare(1.-true_pid[i][j], diff_c->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1492 if (esl_DCompare(1.-true_pid[i][j], diff_x->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1493 if (esl_DCompare( jcd_c->mx[i][j], jcd_x->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1494 if (esl_DCompare( jcV_c->mx[i][j], jcV_x->mx[i][j], 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1495 }
1496
1497 /* API accepts NULL for return values */
1498 if ( esl_dst_CPairIdMx ( as, N, NULL) != eslOK) esl_fatal(msg);
1499 if ( esl_dst_CDiffMx ( as, N, NULL) != eslOK) esl_fatal(msg);
1500 if ( esl_dst_CJukesCantorMx(abc->K, as, N, NULL, NULL) != eslOK) esl_fatal(msg);
1501 if ( esl_dst_XPairIdMx (abc, ax, N, NULL) != eslOK) esl_fatal(msg);
1502 if ( esl_dst_XDiffMx (abc, ax, N, NULL) != eslOK) esl_fatal(msg);
1503 if ( esl_dst_XJukesCantorMx(abc, ax, N, NULL, NULL) != eslOK) esl_fatal(msg);
1504
1505 esl_dmatrix_Destroy(id_c); esl_dmatrix_Destroy(id_x);
1506 esl_dmatrix_Destroy(diff_c); esl_dmatrix_Destroy(diff_x);
1507 esl_dmatrix_Destroy(jcd_c); esl_dmatrix_Destroy(jcd_x);
1508 esl_dmatrix_Destroy(jcV_c); esl_dmatrix_Destroy(jcV_x);
1509 }
1510
1511 static void
1512 utest_averages(const ESL_ALPHABET *abc, ESL_DSQ **ax, char **as, int N)
1513 {
1514 char msg[] = "esl_distance::utest_averages failed";
1515 double idthresh1 = 0.70; // sort of tuned to the current example MSA: 2/6
1516 double idthresh2 = 0.20; // ... and 5/6. But code will work with any MSA.
1517 double true_avgid = 0.;
1518 double true_avgid2 = 0.; // by Elena's denominator using the AverageMatch() functions
1519 double true_conn1 = 0.;
1520 double true_conn2 = 0.;
1521 double np = 0.;
1522 int i,j;
1523 double avgid, avgconn;
1524
1525 for (i = 0; i < N; i++)
1526 for (j = i+1; j < N; j++)
1527 {
1528 true_avgid += true_pid[i][j];
1529 true_avgid2 += (double) true_M[i][j] / (double) true_MDI[i][j];
1530 if (true_pid[i][j] > idthresh1) true_conn1 += 1.;
1531 if (true_pid[i][j] > idthresh2) true_conn2 += 1.;
1532 np += 1.;
1533 }
1534 true_avgid /= np;
1535 true_avgid2 /= np;
1536 true_conn1 /= np;
1537 true_conn2 /= np;
1538
1539 if ( esl_dst_CAverageId(as, N, 10000, &avgid) != eslOK) esl_fatal(msg);
1540 if ( esl_DCompare( true_avgid, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1541
1542 if ( esl_dst_CAverageMatch(as, N, 10000, &avgid) != eslOK) esl_fatal(msg);
1543 if ( esl_DCompare( true_avgid2, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1544
1545 if ( esl_dst_XAverageId(abc, ax, N, 10000, &avgid) != eslOK) esl_fatal(msg);
1546 if ( esl_DCompare( true_avgid, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1547
1548 if ( esl_dst_XAverageMatch(abc, ax, N, 10000, &avgid) != eslOK) esl_fatal(msg);
1549 if ( esl_DCompare( true_avgid2, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1550
1551 if ( esl_dst_XAvgConnectivity(abc, ax, N, 10000, idthresh1, &avgid, &avgconn) != eslOK) esl_fatal(msg);
1552 if ( esl_DCompare( true_avgid, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1553 if ( esl_DCompare( true_conn1, avgconn, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1554
1555 if ( esl_dst_XAvgConnectivity(abc, ax, N, 10000, idthresh2, &avgid, &avgconn) != eslOK) esl_fatal(msg);
1556 if ( esl_DCompare( true_avgid, avgid, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1557 if ( esl_DCompare( true_conn2, avgconn, 1e-4, 1e-4 ) != eslOK) esl_fatal(msg);
1558
1559 /* Edge case for zero connectivity (because links are defined as strictly > idthresh, at idthresh = 1.0 there are no links) */
1560 if ( esl_dst_XAvgConnectivity(abc, ax, N, 10000, 1.0, NULL, &avgconn) != eslOK || avgconn != 0.0) esl_fatal(msg);
1561
1562 /* API accepts NULL for return values */
1563 if ( esl_dst_CAverageId ( as, N, 10000, NULL) != eslOK) esl_fatal(msg);
1564 if ( esl_dst_CAverageMatch ( as, N, 10000, NULL) != eslOK) esl_fatal(msg);
1565 if ( esl_dst_XAverageId (abc, ax, N, 10000, NULL) != eslOK) esl_fatal(msg);
1566 if ( esl_dst_XAverageMatch (abc, ax, N, 10000, NULL) != eslOK) esl_fatal(msg);
1567 if ( esl_dst_XAvgConnectivity(abc, ax, N, 10000, idthresh2, NULL, NULL) != eslOK) esl_fatal(msg);
1568 }
1569
1570 /* Test concordance between stochastic sampling estimate vs. exhaustive calculation
1571 * of avg identity, connectivity.
1572 * */
1573 static void
1574 utest_sampling(ESL_RANDOMNESS *rng, const ESL_ALPHABET *abc, int allow_badluck)
1575 {
1576 char msg[] = "esl_distance::utest_sampling failed";
1577 ESL_MSA *msa = NULL;
1578 int max_nseq = 400; // 1..400, so avg nseq = ~200; typically ~20K pairs; up to 79.8K
1579 int max_alen = 10;
1580 double avgid1, avgid2, avgid3, avgid4;
1581 double avgpm1, avgpm2, avgpm3, avgpm4;
1582 double avgconn1, avgconn2;
1583
1584 if (! allow_badluck) esl_randomness_Init(rng, 4); // reinit to a fixed seed by default: less stringent test, but guarantee that it should succeed.
1585 // this seed was chosen to give nseq=320, thus exercising sampling vs. exhaustive
1586
1587 if ( esl_msa_Sample(rng, abc, max_nseq, max_alen, &msa) != eslOK) esl_fatal(msg);
1588 if (! allow_badluck && msa->nseq != 320) esl_fatal(msg); // trap here, if someone ever changes esl_msa_Sample() we need to recheck this test
1589
1590 if ( esl_dst_XAvgConnectivity(abc, msa->ax, msa->nseq, 10000, 0.30, &avgid1, &avgconn1) != eslOK) esl_fatal(msg); // will often (but not always) use sampling
1591 if ( esl_dst_XAvgConnectivity(abc, msa->ax, msa->nseq, 80000, 0.30, &avgid2, &avgconn2) != eslOK) esl_fatal(msg); // will always be exhaustive
1592 if ( esl_DCompare(avgid2, avgid1, 1e-4, 0.01) != eslOK) esl_fatal(msg); // absolute tolerance +/- 0.01. Default gives 0.229, 0.231
1593 if ( esl_DCompare(avgconn2, avgconn1, 1e-4, 0.01) != eslOK) esl_fatal(msg); // ... 0.268, 0.273
1594
1595 if ( esl_dst_XAverageId(abc, msa->ax, msa->nseq, 10000, &avgid1) != eslOK) esl_fatal(msg);
1596 if ( esl_dst_XAverageId(abc, msa->ax, msa->nseq, 80000, &avgid2) != eslOK) esl_fatal(msg);
1597 if ( esl_DCompare(avgid2, avgid1, 1e-4, 0.01) != eslOK) esl_fatal(msg);
1598
1599 if ( esl_dst_XAverageMatch(abc, msa->ax, msa->nseq, 10000, &avgpm1) != eslOK) esl_fatal(msg);
1600 if ( esl_dst_XAverageMatch(abc, msa->ax, msa->nseq, 80000, &avgpm2) != eslOK) esl_fatal(msg);
1601 if ( esl_DCompare(avgpm2, avgpm1, 1e-4, 0.01) != eslOK) esl_fatal(msg); // 0.825, 0.824
1602
1603 /* Convert MSA to text mode. We get the same avgid, avgpm in text vs digital mode of the same MSA. */
1604 if ( esl_msa_Textize(msa) != eslOK) esl_fatal(msg);
1605
1606 if ( esl_dst_CAverageId(msa->aseq, msa->nseq, 10000, &avgid3) != eslOK) esl_fatal(msg);
1607 if ( esl_dst_CAverageId(msa->aseq, msa->nseq, 80000, &avgid4) != eslOK) esl_fatal(msg);
1608 if ( esl_DCompare(avgid4, avgid3, 1e-4, 0.01) != eslOK) esl_fatal(msg);
1609 if ( esl_DCompare(avgid4, avgid2, 1e-4, 0.01) != eslOK) esl_fatal(msg);
1610
1611 if ( esl_dst_CAverageMatch(msa->aseq, msa->nseq, 10000, &avgpm3) != eslOK) esl_fatal(msg);
1612 if ( esl_dst_CAverageMatch(msa->aseq, msa->nseq, 80000, &avgpm4) != eslOK) esl_fatal(msg);
1613 if ( esl_DCompare(avgpm4, avgpm3, 1e-4, 0.01) != eslOK) esl_fatal(msg);
1614 if ( esl_DCompare(avgpm4, avgpm2, 1e-4, 0.01) != eslOK) esl_fatal(msg);
1615
1616 esl_msa_Destroy(msa);
1617 }
1618
1619 /* Unit test for esl_dst_XAvgSubsetConnectivity()
1620 *
1621 * For a randomly sampled MSA, take a random subset, and check that we
1622 * get the same avg id and avg connectivity whether we use
1623 * esl_dst_AvgSubsetConnectivity() the efficient way, or if we extract
1624 * the subset to a new MSA and use esl_dst_AvgConnectivity().
1625 */
1626 static void
1627 utest_subset_connectivity(ESL_RANDOMNESS *rng, const ESL_ALPHABET *abc)
1628 {
1629 char msg[] = "esl_distance::utest_subset_connectivity failed";
1630 int max_nseq = 100; // you don't want to set this high, but if you do, not so high that max_nseq*(max_nseq+1) overflows
1631 int max_alen = 20;
1632 ESL_MSA *msa = NULL;
1633 int *V = NULL;
1634 int *useme = NULL;
1635 ESL_MSA *submsa = NULL;
1636 int nV;
1637 double avgid1, avgid2;
1638 double avgconn1, avgconn2;
1639 int i;
1640 int status;
1641
1642 if ( esl_msa_Sample(rng, abc, max_nseq, max_alen, &msa) != eslOK) esl_fatal(msg); // a nastily sampled MSA
1643
1644 ESL_ALLOC(V, sizeof(int) * msa->nseq); // ... (0,1 are edge cases of no pairs, that give us avgid = avgconn = 1.0)
1645 nV = 1 + esl_rnd_Roll(rng, msa->nseq); // we'll take a subset of size nV = 1..nseq. (can't do 0; esl_msa_SequenceSubset() can't extract 0 seqs.)
1646 if ( esl_rnd_Deal(rng, nV, msa->nseq, V) != eslOK) esl_fatal(msg); // select the random subset of nV indices
1647
1648 ESL_ALLOC(useme, sizeof(int) * msa->nseq); // useme[0..nseq-1] = 0|1 flags for included seqs
1649 esl_vec_ISet(useme, msa->nseq, 0);
1650 for (i = 0; i < nV; i++) useme[V[i]] = 1;
1651 if ( esl_msa_SequenceSubset(msa, useme, &submsa) != eslOK) esl_fatal(msg); // extract the subset MSA
1652
1653 if ( esl_dst_XAvgConnectivity (abc, submsa->ax, submsa->nseq, max_nseq*(max_nseq+1), 0.30, &avgid1, &avgconn1) != eslOK) esl_fatal(msg); // will always be exhaustive & exact, because max_nseq*(max_nseq+1) > any subseq N(N+1)/2
1654 if ( esl_dst_XAvgSubsetConnectivity(abc, msa->ax, msa->nseq, V, nV, max_nseq*(max_nseq+1), 0.30, &avgid2, &avgconn2) != eslOK) esl_fatal(msg); // thus no stochastic variation; avgid and avgconn are expected to match exactly (up to fp error)
1655
1656 if ( esl_DCompare(avgid1, avgid2, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1657 if ( esl_DCompare(avgconn1, avgconn2, 1e-4, 1e-4) != eslOK) esl_fatal(msg);
1658
1659 esl_msa_Destroy(submsa);
1660 esl_msa_Destroy(msa);
1661 free(useme);
1662 free(V);
1663 return;
1664
1665 ERROR:
1666 esl_fatal(msg);
1667 }
1668 #endif /* eslDISTANCE_TESTDRIVE */
1669 /*------------------ end of unit tests --------------------------*/
1670
1671
1672
1673 /*****************************************************************
1674 * 8. Test driver.
1675 *****************************************************************/
1676
1677 #ifdef eslDISTANCE_TESTDRIVE
1678
1679 #include "easel.h"
1680 #include "esl_alphabet.h"
1681 #include "esl_getopts.h"
1682 #include "esl_msa.h"
1683 #include "esl_random.h"
1684
1685 #include "esl_distance.h"
1686
1687 static ESL_OPTIONS options[] = {
1688 /* name type def env range toggles reqs incomp help docgroup*/
1689 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show help and usage", 0 },
1690 { "-s", eslARG_INT, "0", NULL,"n>=0",NULL, NULL, NULL, "random number seed set to <n>", 0 },
1691 { "-x", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "allow bad luck (rare stochastic failures)", 0 },
1692 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
1693 };
1694 static char usage[] = "[-options]";
1695 static char banner[] = "test driver for distance module";
1696
1697 int
1698 main(int argc, char **argv)
1699 {
1700 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
1701 ESL_RANDOMNESS *rng = esl_randomness_Create(esl_opt_GetInteger(go, "-s"));
1702 int allow_badluck = esl_opt_GetBoolean(go, "-x");
1703 ESL_ALPHABET *abc = NULL;
1704 ESL_MSA *cmsa = NULL; // text mode
1705 ESL_MSA *xmsa = NULL; // digital mode
1706
1707 fprintf(stderr, "## %s\n", argv[0]);
1708 fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng));
1709
1710 create_testmsa(&abc, &cmsa, &xmsa);
1711
1712 utest_pairs (abc, xmsa->ax, cmsa->aseq, xmsa->nseq);
1713 utest_matrices(abc, xmsa->ax, cmsa->aseq, xmsa->nseq);
1714 utest_averages(abc, xmsa->ax, cmsa->aseq, xmsa->nseq);
1715
1716 utest_subset_connectivity(rng, abc);
1717
1718 /* tests that can stochastically fail must go last; by default they will reinit the RNG w/ fixed seed */
1719 utest_sampling(rng, abc, allow_badluck);
1720
1721 fprintf(stderr, "# status = ok\n");
1722
1723 esl_msa_Destroy(cmsa);
1724 esl_msa_Destroy(xmsa);
1725 esl_alphabet_Destroy(abc);
1726 esl_randomness_Destroy(rng);
1727 esl_getopts_Destroy(go);
1728 return eslOK;
1729 }
1730 #endif /*eslDISTANCE_TESTDRIVE*/
1731
1732
1733
1734
1735 /*****************************************************************
1736 * 9. Example.
1737 *****************************************************************/
1738
1739 #ifdef eslDISTANCE_EXAMPLE
1740 /*::cexcerpt::distance_example::begin::*/
1741
1742 #include "easel.h"
1743 #include "esl_msa.h"
1744 #include "esl_msafile.h"
1745
1746 #include "esl_distance.h"
1747
1748 int
1749 main(int argc, char **argv)
1750 {
1751 char *msafile = argv[1];
1752 ESL_ALPHABET *abc = NULL;
1753 ESL_MSAFILE *afp = NULL;
1754 ESL_MSA *msa = NULL;
1755 int max_comparisons = 10000;
1756 double idthresh = 0.50;
1757 double avgid;
1758 double avgconn;
1759 int status;
1760
1761 if ((status = esl_msafile_Open(&abc, msafile, NULL, eslMSAFILE_UNKNOWN, NULL, &afp)) != eslOK) esl_msafile_OpenFailure(afp, status);
1762 if ((status = esl_msafile_Read(afp, &msa)) != eslOK) esl_msafile_ReadFailure(afp, status);
1763
1764 esl_dst_XAverageId(abc, msa->ax, msa->nseq, max_comparisons, &avgid);
1765 printf("esl_dst_XAvgId()...\n");
1766 printf("average %%id: %.1f%%\n\n", avgid*100.);
1767
1768 esl_dst_XAvgConnectivity(abc, msa->ax, msa->nseq, max_comparisons, idthresh, &avgid, &avgconn);
1769 printf("esl_dst_XAvgConnectivity()...\n");
1770 printf("average %%id: %.1f%%\n", avgid*100.);
1771 printf("average %%conn at %.1f%%id: %.1f%%\n", idthresh*100, avgconn*100.);
1772
1773 esl_msa_Destroy(msa);
1774 esl_msafile_Close(afp);
1775 esl_alphabet_Destroy(abc);
1776 return eslOK;
1777 }
1778 /*::cexcerpt::distance_example::end::*/
1779 #endif /*eslDISTANCE_EXAMPLE*/
1780
1781
1782