forked from EddyRivasLab/easel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esl_distance.c
1782 lines (1578 loc) · 70.3 KB
/
esl_distance.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Pairwise identities, distances, and distance matrices.
*
* Contents:
* 1. Pairwise distances for aligned text sequences.
* 2. Pairwise distances for aligned digital seqs.
* 3. Distance matrices for aligned text sequences.
* 4. Distance matrices for aligned digital sequences.
* 5. Average pairwise identity for multiple alignments.
* 6. Private (static) functions.
* 7. Unit tests.
* 8. Test driver.
* 9. Example.
*/
#include <esl_config.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#include "easel.h"
#include "esl_alphabet.h"
#include "esl_dmatrix.h"
#include "esl_random.h"
#include "esl_distance.h"
/* Forward declaration of our static functions.
*/
static int jukescantor(int n1, int n2, int alphabet_size, double *opt_distance, double *opt_variance);
/*****************************************************************
* 1. Pairwise distances for aligned text sequences.
*****************************************************************/
/* Function: esl_dst_CPairId()
* Synopsis: Pairwise identity of two aligned text strings.
* Incept: SRE, Mon Apr 17 20:06:07 2006 [St. Louis]
*
* Purpose: Calculates pairwise fractional identity between two
* aligned character strings <asq1> and <asq2>.
* Return this distance in <opt_pid>; return the
* number of identities counted in <opt_nid>; and
* return the denominator <MIN(len1,len2)> in
* <opt_n>.
*
* Alphabetic symbols <[a-zA-Z]> are compared
* case-insensitively for identity. Any nonalphabetic
* character is assumed to be a gap symbol.
*
* This simple comparison rule is unaware of synonyms and
* degeneracies in biological alphabets. For a more
* sophisticated and biosequence-aware comparison, use
* digitized sequences and the <esl_dst_XPairId()> function
* instead. Note that currently <esl_dst_XPairId()> does
* not correctly handle degeneracies, but is set up to.
*
* Args: as1 - aligned character string 1
* as2 - aligned character string 2
* opt_pid - optRETURN: pairwise identity, 0<=x<=1
* opt_nid - optRETURN: # of identities
* opt_n - optRETURN: denominator MIN(len1,len2)
*
* Returns: <eslOK> on success. <opt_pid>, <opt_nid>, <opt_n>
* contain the answers (for whichever were passed non-NULL).
*
* Throws: <eslEINVAL> if the strings are different lengths
* (not aligned).
*/
int
esl_dst_CPairId(const char *as1, const char *as2, double *opt_pid, int *opt_nid, int *opt_n)
{
int nid; /* total identical positions */
int len1, len2; /* lengths of seqs */
int i; /* position in aligned seqs */
int status;
nid = len1 = len2 = 0;
for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
{
if (isalpha(as1[i])) len1++;
if (isalpha(as2[i])) len2++;
if (isalpha(as1[i]) && isalpha(as2[i])
&& toupper(as1[i]) == toupper(as2[i]))
nid++;
}
len1 = ESL_MIN(len1, len2);
if (as1[i] != '\0' || as2[i] != '\0')
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
if (opt_pid != NULL) *opt_pid = ( len1==0 ? 0. : (double) nid / (double) len1);
if (opt_nid != NULL) *opt_nid = nid;
if (opt_n != NULL) *opt_n = len1;
return eslOK;
ERROR:
if (opt_pid != NULL) *opt_pid = 0.;
if (opt_nid != NULL) *opt_nid = 0;
if (opt_n != NULL) *opt_n = 0;
return status;
}
/* Function: esl_dst_CPairMatch()
* Synopsis: Pairwise matches of two aligned text strings.
* Incept: ER, Wed Oct 29 09:02:35 EDT 2014 [janelia]
*
* Purpose: Calculates pairwise fractional matches between two aligned
* character strings <asq1> and <asq2>, in the pairHMM
* sense, where a match state M is any aligned residue pair
* (not necessarily an identity), and I and D are X- and -X
* singlets.
*
* Return the fraction of matches, M / (M+I+D), in
* <opt_pmatch>; return the number of matches M counted in
* <opt_nmatch>; and return the denominator M+I+D, which is
* <alen - double_gaps>, in <*opt_n>.
*
* Alphabetic symbols <[a-zA-Z]> are compared
* case-insensitively for identity. Any nonalphabetic
* character is assumed to be a gap symbol.
*
* This simple comparison rule is unaware of synonyms and
* degeneracies in biological alphabets. For a more
* sophisticated and biosequence-aware comparison, use
* digitized sequences and the <esl_dst_XPairMatch()> function
* instead. Note that currently <esl_dst_XPairMatch()> does
* not correctly handle degeneracies, but is set up to.
*
* Args: as1 - aligned character string 1
* as2 - aligned character string 2
* opt_pm - optRETURN: fraction of M states, M/(M+D+I) [0..1]
* opt_nm - optRETURN: # of match states, M
* opt_n - optRETURN: denominator alen - double_gaps, M+D+1
*
* Returns: <eslOK> on success. <opt_pm>, <opt_nm>, <opt_n>
* contain the answers (for whichever were passed non-NULL).
*
* Throws: <eslEINVAL> if the strings are different lengths
* (not aligned).
*/
int
esl_dst_CPairMatch(const char *as1, const char *as2, double *opt_pm, int *opt_nm, int *opt_n)
{
int nm; // total matched positions
int len; // length of alignment (no double gaps)
int i; // position in aligned seqs
int status;
nm = len = 0;
for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
{
if (isalpha(as1[i]) || isalpha(as2[i])) len++;
if (isalpha(as1[i]) && isalpha(as2[i])) nm++;
}
if (as1[i] != '\0' || as2[i] != '\0')
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
if (opt_pm) *opt_pm = ( len==0 ? 0. : (double)nm / (double)len);
if (opt_nm) *opt_nm = nm;
if (opt_n) *opt_n = len;
return eslOK;
ERROR:
if (opt_pm) *opt_pm = 0.;
if (opt_nm) *opt_nm = 0;
if (opt_n) *opt_n = 0;
return status;
}
/* Function: esl_dst_CJukesCantor()
* Synopsis: Jukes-Cantor distance for two aligned strings.
* Incept: SRE, Tue Apr 18 14:00:37 2006 [St. Louis]
*
* Purpose: Calculate the generalized Jukes-Cantor distance between
* two aligned character strings <as1> and <as2>, in
* substitutions/site, for an alphabet of <K> residues
* (<K=4> for nucleic acid, <K=20> for proteins). The
* maximum likelihood estimate for the distance is
* optionally returned in <opt_distance>. The large-sample
* variance for the distance estimate is
* optionally returned in <opt_variance>.
*
* Alphabetic symbols <[a-zA-Z]> are compared
* case-insensitively to count the number of identities
* (<n1>) and mismatches (<n2>>). Any nonalphabetic
* character is assumed to be a gap symbol, and aligned
* columns containing gap symbols are ignored. The
* fractional difference <D> used to calculate the
* Jukes/Cantor distance is <n2/n1+n2>.
*
* Args: K - size of the alphabet (4 or 20)
* as1 - 1st aligned seq, 0..L-1, \0-terminated
* as2 - 2nd aligned seq, 0..L-1, \0-terminated
* opt_distance - optRETURN: ML estimate of distance d
* opt_variance - optRETURN: large-sample variance of d
*
* Returns: <eslOK> on success.
*
* Infinite distances are possible, in which case distance
* and variance are both <HUGE_VAL>. Caller has to deal
* with this case as it sees fit, perhaps by enforcing
* an arbitrary maximum distance.
*
* Throws: <eslEINVAL> if the two strings aren't the same length (and
* thus can't have been properly aligned).
* <eslEDIVZERO> if no aligned residues were counted.
* On either failure, distance and variance are both returned
* as <HUGE_VAL>.
*/
int
esl_dst_CJukesCantor(int K, const char *as1, const char *as2,
double *opt_distance, double *opt_variance)
{
int n1, n2; /* number of observed identities, substitutions */
int i; /* position in aligned seqs */
int status;
n1 = n2 = 0;
for (i = 0; as1[i] != '\0' && as2[i] != '\0'; i++)
{
if (isalpha(as1[i]) && isalpha(as2[i]))
{
if (toupper(as1[i]) == toupper(as2[i])) n1++; else n2++;
}
}
if (as1[i] != '\0' || as2[i] != '\0')
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
return jukescantor(n1, n2, K, opt_distance, opt_variance); /* can throw eslEDIVZERO */
ERROR:
if (opt_distance != NULL) *opt_distance = HUGE_VAL;
if (opt_variance != NULL) *opt_variance = HUGE_VAL;
return status;
}
/*------- end, pairwise distances for aligned text seqs ---------*/
/*****************************************************************
* 2. Pairwise distances for aligned digitized sequences.
*****************************************************************/
/* Function: esl_dst_XPairId()
* Synopsis: Pairwise identity of two aligned digital seqs.
* Incept: SRE, Tue Apr 18 09:24:05 2006 [St. Louis]
*
* Purpose: Digital version of <esl_dst_CPairId()>: <ax1> and
* <ax2> are digitized aligned sequences, in alphabet
* <abc>.
*
* Only exactly matching codes count as identities;
* canonical residues, of course, but also IUPAC degeneracy
* codes. (YY is an identity; YC is not.) It would be more
* sophisticated to use <esl_abc_Match()> to handle
* degeneracies, but doing that would require that
* <opt_nid> be changed to an expectation, and a double.
*
* Args: abc - digital alphabet in use
* ax1 - aligned digital seq 1
* ax2 - aligned digital seq 2
* opt_pid - optRETURN: pairwise identity, 0<=x<=1
* opt_nid - optRETURN: # of identities
* opt_n - optRETURN: denominator MIN(len1,len2)
*
* Returns: <eslOK> on success. <opt_pid>, <opt_nid>, <opt_n>
* contain the answers, for any of these that were passed
* non-<NULL> pointers.
*
* Throws: <eslEINVAL> if the strings are different lengths (not aligned).
*/
int
esl_dst_XPairId(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2,
double *opt_pid, int *opt_nid, int *opt_n)
{
int nid; /* total identical positions */
int len1, len2; /* lengths of seqs */
int i; /* position in aligned seqs */
int status;
nid = len1 = len2 = 0;
for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
{
if (esl_abc_XIsResidue(abc, ax1[i])) len1++;
if (esl_abc_XIsResidue(abc, ax2[i])) len2++;
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
}
len1 = ESL_MIN(len1, len2);
if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
if (opt_pid) *opt_pid = ( len1==0 ? 0. : (double) nid / (double) len1 );
if (opt_nid) *opt_nid = nid;
if (opt_n) *opt_n = len1;
return eslOK;
ERROR:
if (opt_pid) *opt_pid = 0.;
if (opt_nid) *opt_nid = 0;
if (opt_n) *opt_n = 0;
return status;
}
/* Function: esl_dst_XPairMatch()
* Synopsis: Pairwise matches of two aligned digital seqs.
* Incept: ER, Wed Oct 29 09:09:07 EDT 2014 [janelia]
*
* Purpose: Digital version of <esl_dst_CPairMatch()>: <ax1> and
* <ax2> are digitized aligned sequences, in alphabet
* <abc>.
*
* IUPAC degeneracy codes count as residues both in
* counting match (XX residue/residue) and delete/insert
* (X-, -X) states.
*
* Args: abc - digital alphabet in use
* ax1 - aligned digital seq 1
* ax2 - aligned digital seq 2
* opt_pm - optRETURN: pairwise fractional match states, M/(M+D+I), 0<=x<=1
* opt_nm - optRETURN: # of match states, M
* opt_n - optRETURN: denominator alen-double_gaps, (M+D+I)
*
* Returns: <eslOK> on success. <opt_pm>, <opt_nm>, <opt_n>
* contain the answers, for any of these that were passed
* non-<NULL> pointers.
*
* Throws: <eslEINVAL> if the strings are different lengths (not aligned).
*/
int
esl_dst_XPairMatch(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2, double *opt_pm, int *opt_nm, int *opt_n)
{
int nm; // total matched positions
int len; // length of alignment (no double gaps)
int i; // position in aligned seqs
int status;
nm = len = 0;
for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
{
if (esl_abc_XIsResidue(abc, ax1[i]) || esl_abc_XIsResidue(abc, ax2[i])) len++;
if (esl_abc_XIsResidue(abc, ax1[i]) && esl_abc_XIsResidue(abc, ax2[i])) nm++;
}
if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
if (opt_pm) *opt_pm = ( len==0 ? 0. : (double)nm / (double)len );
if (opt_nm) *opt_nm = nm;
if (opt_n) *opt_n = len;
return eslOK;
ERROR:
if (opt_pm) *opt_pm = 0.;
if (opt_nm) *opt_nm = 0;
if (opt_n) *opt_n = 0;
return status;
}
/* Function: esl_dst_XJukesCantor()
* Synopsis: Jukes-Cantor distance for two aligned digitized seqs.
* Incept: SRE, Tue Apr 18 15:26:51 2006 [St. Louis]
*
* Purpose: Calculate the generalized Jukes-Cantor distance between two
* aligned digital strings <ax1> and <ax2>, in substitutions/site,
* using alphabet <abc> to evaluate identities and differences.
* The maximum likelihood estimate for the distance is optionally returned in
* <opt_distance>. The large-sample variance for the distance
* estimate is optionally returned in <opt_variance>.
*
* Identical to <esl_dst_CJukesCantor()>, except that it takes
* digital sequences instead of character strings.
*
* Args: abc - bioalphabet to use for comparisons
* ax1 - 1st digital aligned seq
* ax2 - 2nd digital aligned seq
* opt_distance - optRETURN: ML estimate of distance d
* opt_variance - optRETURN: large-sample variance of d
*
* Returns: <eslOK> on success. As in <esl_dst_CJukesCantor()>, the
* distance and variance may be infinite, in which case they
* are returned as <HUGE_VAL>.
*
* Throws: <eslEINVAL> if the two strings aren't the same length (and
* thus can't have been properly aligned).
* <eslEDIVZERO> if no aligned residues were counted.
* On either failure, the distance and variance are set
* to <HUGE_VAL>.
*/
int
esl_dst_XJukesCantor(const ESL_ALPHABET *abc, const ESL_DSQ *ax1, const ESL_DSQ *ax2, double *opt_distance, double *opt_variance)
{
int n1, n2; // number of observed identities, substitutions
int i; // position in aligned seqs
int status;
n1 = n2 = 0;
for (i = 1; ax1[i] != eslDSQ_SENTINEL && ax2[i] != eslDSQ_SENTINEL; i++)
{
if (esl_abc_XIsCanonical(abc, ax1[i]) && esl_abc_XIsCanonical(abc, ax2[i]))
{
if (ax1[i] == ax2[i]) n1++;
else n2++;
}
}
if (ax1[i] != eslDSQ_SENTINEL || ax2[i] != eslDSQ_SENTINEL)
ESL_XEXCEPTION(eslEINVAL, "strings not same length, not aligned");
return jukescantor(n1, n2, abc->K, opt_distance, opt_variance);
ERROR:
if (opt_distance) *opt_distance = HUGE_VAL;
if (opt_variance) *opt_variance = HUGE_VAL;
return status;
}
/*---------- end pairwise distances, digital seqs --------------*/
/*****************************************************************
* 3. Distance matrices for aligned text sequences.
*****************************************************************/
/* Function: esl_dst_CPairIdMx()
* Synopsis: NxN identity matrix for N aligned text sequences.
* Incept: SRE, Thu Apr 27 08:46:08 2006 [New York]
*
* Purpose: Given a multiple sequence alignment <as>, consisting
* of <N> aligned character strings; calculate
* a symmetric fractional pairwise identity matrix by $N(N-1)/2$
* calls to <esl_dst_CPairId()>, and return it in
* <opt_D>.
*
* Args: as - aligned seqs (all same length), [0..N-1]
* N - # of aligned sequences
* ret_S - RETURN: symmetric fractional identity matrix
*
* Returns: <eslOK> on success, and <ret_S> contains the fractional
* identity matrix. Caller free's <S> with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if a seq has a different
* length than others. On failure, <ret_D> is returned <NULL>
* and state of inputs is unchanged.
*
* <eslEMEM> on allocation failure.
*/
int
esl_dst_CPairIdMx(char **as, int N, ESL_DMATRIX **opt_S)
{
ESL_DMATRIX *S = NULL;
int status;
int i,j;
if (( S = esl_dmatrix_Create(N,N) ) == NULL) { status = eslEMEM; goto ERROR; }
for (i = 0; i < N; i++)
{
S->mx[i][i] = 1.;
for (j = i+1; j < N; j++)
{
status = esl_dst_CPairId(as[i], as[j], &(S->mx[i][j]), NULL, NULL);
if (status != eslOK)
ESL_XEXCEPTION(status, "Pairwise identity calculation failed at seqs %d,%d\n", i,j);
S->mx[j][i] = S->mx[i][j];
}
}
if (opt_S) *opt_S = S; else esl_dmatrix_Destroy(S);
return eslOK;
ERROR:
esl_dmatrix_Destroy(S);
if (opt_S) *opt_S = NULL;
return status;
}
/* Function: esl_dst_CDiffMx()
* Synopsis: NxN difference matrix for N aligned text sequences.
* Incept: SRE, Fri Apr 28 06:27:20 2006 [New York]
*
* Purpose: Same as <esl_dst_CPairIdMx()>, but calculates
* the fractional difference <d=1-s> instead of the
* fractional identity <s> for each pair.
*
* Args: as - aligned seqs (all same length), [0..N-1]
* N - # of aligned sequences
* opt_D - RETURN: symmetric fractional difference matrix
*
* Returns: <eslOK> on success, and <opt_D> contains the
* fractional difference matrix. Caller free's <D> with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if any seq has a different
* length than others. On failure, <opt_D> is returned <NULL>
* and state of inputs is unchanged.
*/
int
esl_dst_CDiffMx(char **as, int N, ESL_DMATRIX **opt_D)
{
ESL_DMATRIX *D = NULL;
int status;
int i,j;
if ((status = esl_dst_CPairIdMx(as, N, &D)) != eslOK) goto ERROR;
for (i = 0; i < N; i++)
{
D->mx[i][i] = 0.;
for (j = i+1; j < N; j++)
{
D->mx[i][j] = 1. - D->mx[i][j];
D->mx[j][i] = D->mx[i][j];
}
}
if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
return eslOK;
ERROR:
esl_dmatrix_Destroy(D);
if (opt_D) *opt_D = NULL;
return status;
}
/* Function: esl_dst_CJukesCantorMx()
* Synopsis: NxN Jukes/Cantor distance matrix for N aligned text seqs.
* Incept: SRE, Tue Apr 18 16:00:16 2006 [St. Louis]
*
* Purpose: Given a multiple sequence alignment <aseq>, consisting of
* <nseq> aligned character sequences in an alphabet of
* <K> letters (usually 4 for DNA, 20 for protein);
* calculate a symmetric Jukes/Cantor pairwise distance
* matrix for all sequence pairs, and optionally return the distance
* matrix in <ret_D>, and optionally return a symmetric matrix of the
* large-sample variances for those ML distance estimates
* in <ret_V>.
*
* Infinite distances (and variances) are possible; they
* are represented as <HUGE_VAL> in <D> and <V>. Caller must
* be prepared to deal with them as appropriate.
*
* Args: K - size of the alphabet (usually 4 or 20)
* as - aligned sequences [0.nseq-1][0..L-1]
* N - number of aseqs
* opt_D - optRETURN: [0..nseq-1]x[0..nseq-1] symmetric distance mx
* opt_V - optRETURN: matrix of variances.
*
* Returns: <eslOK> on success. <D> and <V> contain the
* distance matrix (and variances); caller frees these with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if any pair of sequences have differing lengths
* (and thus cannot have been properly aligned).
* <eslEDIVZERO> if some pair of sequences had no aligned
* residues. On failure, <D> and <V> are both returned <NULL>
* and state of inputs is unchanged.
*
* <eslEMEM> on allocation failure.
*/
int
esl_dst_CJukesCantorMx(int K, char **as, int N, ESL_DMATRIX **opt_D, ESL_DMATRIX **opt_V)
{
ESL_DMATRIX *D = NULL;
ESL_DMATRIX *V = NULL;
int i,j;
int status;
if (( D = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
if (( V = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
for (i = 0; i < N; i++)
{
D->mx[i][i] = 0.;
V->mx[i][i] = 0.;
for (j = i+1; j < N; j++)
{
if ((status = esl_dst_CJukesCantor(K, as[i], as[j], &(D->mx[i][j]), &(V->mx[i][j]))) != eslOK)
ESL_XEXCEPTION(status, "J/C calculation failed at seqs %d,%d", i,j);
D->mx[j][i] = D->mx[i][j];
V->mx[j][i] = V->mx[i][j];
}
}
if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
if (opt_V) *opt_V = V; else esl_dmatrix_Destroy(V);
return eslOK;
ERROR:
esl_dmatrix_Destroy(D);
esl_dmatrix_Destroy(V);
if (opt_D) *opt_D = NULL;
if (opt_V) *opt_V = NULL;
return status;
}
/*----------- end, distance matrices for aligned text seqs ---------*/
/*****************************************************************
* 4. Distance matrices for aligned digital sequences.
*****************************************************************/
/* Function: esl_dst_XPairIdMx()
* Synopsis: NxN identity matrix for N aligned digital seqs.
* Incept: SRE, Thu Apr 27 09:08:11 2006 [New York]
*
* Purpose: Given a digitized multiple sequence alignment <ax>, consisting
* of <N> aligned digital sequences in alphabet <abc>; calculate
* a symmetric pairwise fractional identity matrix by $N(N-1)/2$
* calls to <esl_dst_XPairId()>, and return it in <ret_S>.
*
* Args: abc - digital alphabet in use
* ax - aligned dsq's, [0..N-1][1..alen]
* N - number of aligned sequences
* opt_S - RETURN: NxN matrix of fractional identities
*
* Returns: <eslOK> on success, and <opt_S> contains the distance
* matrix. Caller is obligated to free <S> with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if a seq has a different
* length than others. On failure, <opt_S> is returned <NULL>
* and state of inputs is unchanged.
*
* <eslEMEM> on allocation failure.
*/
int
esl_dst_XPairIdMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_S)
{
ESL_DMATRIX *S = NULL;
int i,j;
int status;
if (( S = esl_dmatrix_Create(N,N) ) == NULL) { status = eslEMEM; goto ERROR; }
for (i = 0; i < N; i++)
{
S->mx[i][i] = 1.;
for (j = i+1; j < N; j++)
{
status = esl_dst_XPairId(abc, ax[i], ax[j], &(S->mx[i][j]), NULL, NULL);
if (status != eslOK)
ESL_XEXCEPTION(status, "Pairwise identity calculation failed at seqs %d,%d\n", i,j);
S->mx[j][i] = S->mx[i][j];
}
}
if (opt_S) *opt_S = S; else esl_dmatrix_Destroy(S);
return eslOK;
ERROR:
esl_dmatrix_Destroy(S);
if (opt_S) *opt_S = NULL;
return status;
}
/* Function: esl_dst_XDiffMx()
* Synopsis: NxN difference matrix for N aligned digital seqs.
* Incept: SRE, Fri Apr 28 06:37:29 2006 [New York]
*
* Purpose: Same as <esl_dst_XPairIdMx()>, but calculates fractional
* difference <1-s> instead of fractional identity <s> for
* each pair.
*
* Args: abc - digital alphabet in use
* ax - aligned dsq's, [0..N-1][1..alen]
* N - number of aligned sequences
* opt_D - RETURN: NxN matrix of fractional differences
*
* Returns: <eslOK> on success, and <opt_D> contains the difference
* matrix; caller is obligated to free <D> with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if a seq has a different
* length than others. On failure, <opt_D> is returned <NULL>
* and state of inputs is unchanged.
*/
int
esl_dst_XDiffMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_D)
{
ESL_DMATRIX *D = NULL;
int i,j;
int status;
if ((status = esl_dst_XPairIdMx(abc, ax, N, &D)) != eslOK) goto ERROR;
for (i = 0; i < N; i++)
{
D->mx[i][i] = 0.;
for (j = i+1; j < N; j++)
{
D->mx[i][j] = 1. - D->mx[i][j];
D->mx[j][i] = D->mx[i][j];
}
}
if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
return eslOK;
ERROR:
esl_dmatrix_Destroy(D);
if (opt_D) *opt_D = NULL;
return status;
}
/* Function: esl_dst_XJukesCantorMx()
* Synopsis: NxN Jukes/Cantor distance matrix for N aligned digital seqs.
* Incept: SRE, Thu Apr 27 08:38:08 2006 [New York City]
*
* Purpose: Given a digitized multiple sequence alignment <ax>,
* consisting of <nseq> aligned digital sequences in
* bioalphabet <abc>, calculate a symmetric Jukes/Cantor
* pairwise distance matrix for all sequence pairs;
* optionally return the distance matrix in <ret_D> and
* a matrix of the large-sample variances for those ML distance
* estimates in <ret_V>.
*
* Infinite distances (and variances) are possible. They
* are represented as <HUGE_VAL> in <D> and <V>. Caller must
* be prepared to deal with them as appropriate.
*
* Args: abc - bioalphabet for <aseq>
* ax - aligned digital sequences [0.nseq-1][1..L]
* N - number of aseqs
* opt_D - optRETURN: [0..nseq-1]x[0..nseq-1] symmetric distance mx
* opt_V - optRETURN: matrix of variances.
*
* Returns: <eslOK> on success. <opt_D> and <opt_V>, if provided, contain the
* distance matrix and variances. Caller frees these with
* <esl_dmatrix_Destroy()>.
*
* Throws: <eslEINVAL> if any pair of sequences have differing lengths
* (and thus cannot have been properly aligned).
* <eslEDIVZERO> if some pair of sequences had no aligned
* residues. On failure, <opt_D> and <opt_V> are both returned <NULL>
* and state of inputs is unchanged.
*
* <eslEMEM> on allocation failure.
*/
int
esl_dst_XJukesCantorMx(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, ESL_DMATRIX **opt_D, ESL_DMATRIX **opt_V)
{
ESL_DMATRIX *D = NULL;
ESL_DMATRIX *V = NULL;
int status;
int i,j;
if (( D = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
if (( V = esl_dmatrix_Create(N, N) ) == NULL) { status = eslEMEM; goto ERROR; }
for (i = 0; i < N; i++)
{
D->mx[i][i] = 0.;
V->mx[i][i] = 0.;
for (j = i+1; j < N; j++)
{
if ((status = esl_dst_XJukesCantor(abc, ax[i], ax[j], &(D->mx[i][j]), &(V->mx[i][j]))) != eslOK)
ESL_XEXCEPTION(status, "J/C calculation failed at digital aseqs %d,%d", i,j);
D->mx[j][i] = D->mx[i][j];
V->mx[j][i] = V->mx[i][j];
}
}
if (opt_D) *opt_D = D; else esl_dmatrix_Destroy(D);
if (opt_V) *opt_V = V; else esl_dmatrix_Destroy(V);
return eslOK;
ERROR:
esl_dmatrix_Destroy(D);
esl_dmatrix_Destroy(V);
if (opt_D) *opt_D = NULL;
if (opt_V) *opt_V = NULL;
return status;
}
/*------- end, distance matrices for digital alignments ---------*/
/*****************************************************************
* 5. Average pairwise identity for multiple alignments
*****************************************************************/
/* Function: esl_dst_CAverageId()
* Synopsis: Calculate avg identity for multiple alignment
* Incept: SRE, Fri May 18 15:02:38 2007 [Janelia]
*
* Purpose: Calculates the average pairwise fractional identity in
* a multiple sequence alignment <as>, consisting of <N>
* aligned character sequences of identical length.
*
* If an exhaustive calculation would require more than
* <max_comparisons> pairwise comparisons, then instead of
* looking at all pairs, calculate the average over a
* stochastic sample of <max_comparisons> random pairs.
* This allows the routine to work efficiently even on very
* deep MSAs.
*
* Each fractional pairwise identity (range $[0..$ pid $..1]$
* is calculated using <esl_dst_CPairId()>.
*
* Returns: <eslOK> on success, and <*opt_avgid> contains the average
* fractional identity.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEINVAL> if any of the aligned sequence pairs aren't
* of the same length.
* In either case, <*opt_avgid> is set to 0.
*/
int
esl_dst_CAverageId(char **as, int N, int max_comparisons, double *opt_avgid)
{
ESL_RANDOMNESS *rng = NULL;
double avgid = 0.;
double id;
int i,j,k;
int status;
if (N <= 1) // by convention, with no pairwise comparisons for N=0|1, set pid = 1.0
{
avgid = 1.0;
}
else if (N <= max_comparisons && // if N is small enough that we can average exhaustively over all pairwise comparisons...
N <= sqrt(2. * max_comparisons) && // (beware numerical overflow of N^2)
(N * (N-1) / 2) <= max_comparisons)
{
for (i = 0; i < N; i++)
for (j = i+1; j < N; j++)
{
if ((status = esl_dst_CPairId(as[i], as[j], &id, NULL, NULL)) != eslOK) return status;
avgid += id;
}
avgid /= (double) (N * (N-1) / 2);
}
else // If nseq is large, calculate average over a stochastic sample.
{
if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
for (k = 0; k < max_comparisons; k++)
{
do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
if ((status = esl_dst_CPairId(as[i], as[j], &id, NULL, NULL)) != eslOK) return status;
avgid += id;
}
avgid /= (double) max_comparisons;
}
esl_randomness_Destroy(rng);
if (opt_avgid) *opt_avgid = avgid;
return eslOK;
ERROR:
esl_randomness_Destroy(rng);
if (opt_avgid) *opt_avgid = 0.;
return status;
}
/* Function: esl_dst_CAverageMatch()
* Synopsis: Calculate avg matches for multiple alignment
* Incept: ER, Wed Oct 29 09:25:09 EDT 2014 [Janelia]
*
* Purpose: Calculates the average pairwise fractional matches M/(M+D+I) in
* a multiple sequence alignment <as>, consisting of <N>
* aligned character sequences of identical length. M,D,I
* are in the pair-HMM state sense: M means any aligned pair,
* including both mismatches and identities.
*
* If an exhaustive calculation would require more than
* <max_comparisons> pairwise comparisons, then instead of
* looking at all pairs, calculate the average over a
* stochastic sample of <max_comparisons> random pairs.
* This allows the routine to work efficiently even on very
* deep MSAs.
*
* Each fractional pairwise matches (range $[0..$ pm $..1]$
* is calculated using <esl_dst_CPairMatch()>.
*
* Returns: <eslOK> on success, and <*ret_avgpm> contains the average
* fractional matches.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEINVAL> if any of the aligned sequence pairs aren't
* of the same length.
* In either case, <*ret_avgpm> is set to 0.
*/
int
esl_dst_CAverageMatch(char **as, int N, int max_comparisons, double *opt_avgpm)
{
ESL_RANDOMNESS *rng = NULL;
double avgpm = 0.;
double pmatch;
int i,j,k;
int status;
if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
{ // Set a convention of id = 1.0 for the case of no pairwise comparisons
avgpm = 1.0;
}
else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
(N * (N-1) / 2) <= max_comparisons)
{
for (i = 0; i < N; i++)
for (j = i+1; j < N; j++)
{
if ((status = esl_dst_CPairMatch(as[i], as[j], &pmatch, NULL, NULL)) != eslOK) return status;
avgpm += pmatch;
}
avgpm /= (double) (N * (N-1) / 2);
}
else /* If nseq is large, calculate average over a stochastic sample. */
{
if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
for (k = 0; k < max_comparisons; k++)
{
do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
if ((status = esl_dst_CPairMatch(as[i], as[j], &pmatch, NULL, NULL)) != eslOK) return status;
avgpm += pmatch;
}
avgpm /= (double) max_comparisons;
}
esl_randomness_Destroy(rng);
if (opt_avgpm) *opt_avgpm = avgpm;
return eslOK;
ERROR:
esl_randomness_Destroy(rng);
if (opt_avgpm) *opt_avgpm = 0.;
return status;
}
/* Function: esl_dst_XAverageId()
* Synopsis: Calculate avg identity for digital MSA
* Incept: SRE, Fri May 18 15:19:14 2007 [Janelia]
*
* Purpose: Calculates the average pairwise fractional identity in
* a digital multiple sequence alignment <ax>, consisting of <N>
* aligned digital sequences of identical length.
*
* If an exhaustive calculation would require more than
* <max_comparisons> pairwise comparisons, then instead of
* looking at all pairs, calculate the average over a
* stochastic sample of <max_comparisons> random pairs.
* This allows the routine to work efficiently even on very
* deep MSAs.
*
* Each fractional pairwise identity (range $[0..$ pid $..1]$
* is calculated using <esl_dst_XPairId()>.
*
* Returns: <eslOK> on success, and <*ret_id> contains the average
* fractional identity.
*
* Throws: <eslEMEM> on allocation failure.
* <eslEINVAL> if any of the aligned sequence pairs aren't
* of the same length.
* In either case, <*ret_id> is set to 0.
*/
int
esl_dst_XAverageId(const ESL_ALPHABET *abc, ESL_DSQ **ax, int N, int max_comparisons, double *opt_avgid)
{
ESL_RANDOMNESS *rng = NULL;
double avgid = 0.;
double id;
int i,j,k;
int status;
if (N <= 1) // Edge case: a single sequence by itself has no pairwise comparisons
{ // Set a convention of id = 1.0 for the case of no pairwise comparisons
avgid = 1.;
}
else if (N <= max_comparisons && // Is N small enough that we can average over all pairwise comparisons?
N <= sqrt(2. * max_comparisons) && // Watch out for numerical overflow in this: for large MSAs, N(N-1)/2 can overflow.
(N * (N-1) / 2) <= max_comparisons)
{
for (i = 0; i < N; i++)
for (j = i+1; j < N; j++)
{
if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) return status;
avgid += id;
}
avgid /= (double) (N * (N-1) / 2);
}
else /* If nseq is large, calculate average over a stochastic sample. */
{
if (( rng = esl_randomness_Create(42) ) == NULL) { status = eslEMEM; goto ERROR; } // fixed seed, suppress stochastic variation
for (k = 0; k < max_comparisons; k++)
{
do { i = esl_rnd_Roll(rng, N); j = esl_rnd_Roll(rng, N); } while (j == i); // make sure j != i
if ((status = esl_dst_XPairId(abc, ax[i], ax[j], &id, NULL, NULL)) != eslOK) return status;