forked from EddyRivasLab/easel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esl_dmatrix.c
1587 lines (1378 loc) · 49.2 KB
/
esl_dmatrix.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
/* Linear algebra operations in double-precision matrices.
*
* Implements ESL_DMATRIX (double-precision matrix) and
* ESL_PERMUTATION (permutation matrix) objects.
*
* Table of contents:
* 1. The ESL_DMATRIX object
* 2. Debugging/validation code for ESL_DMATRIX
* 3. Visualization tools
* 4. The ESL_PERMUTATION object
* 5. Debugging/validation code for ESL_PERMUTATION
* 6. The rest of the dmatrix API
* 7. Optional: Interoperability with GSL
* 8. Optional: Interfaces to LAPACK
* 9. Unit tests
* 10. Test driver
* 11. Examples
*
* To do:
* - eventually probably want additional matrix types
* - unit tests poor
*/
#include "esl_config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "easel.h"
#include "esl_vectorops.h"
#include "esl_dmatrix.h"
/*****************************************************************
* 1. The ESL_DMATRIX object.
*****************************************************************/
/* Function: esl_dmatrix_Create()
*
* Purpose: Creates a general <n> x <m> matrix (<n> rows, <m>
* columns).
*
* Args: <n> - number of rows; $>= 1$
* <m> - number of columns; $>= 1$
*
* Returns: a pointer to a new <ESL_DMATRIX> object. Caller frees
* with <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> if an allocation failed.
*/
ESL_DMATRIX *
esl_dmatrix_Create(int n, int m)
{
ESL_DMATRIX *A = NULL;
int r;
int status;
ESL_ALLOC(A, sizeof(ESL_DMATRIX));
A->mx = NULL;
A->n = n;
A->m = m;
ESL_ALLOC(A->mx, sizeof(double *) * n);
A->mx[0] = NULL;
ESL_ALLOC(A->mx[0], sizeof(double) * n * m);
for (r = 1; r < n; r++)
A->mx[r] = A->mx[0] + r*m;
A->type = eslGENERAL;
A->ncells = n * m;
return A;
ERROR:
esl_dmatrix_Destroy(A);
return NULL;
}
/* Function: esl_dmatrix_CreateUpper()
* Incept: SRE, Wed Feb 28 08:45:45 2007 [Janelia]
*
* Purpose: Creates a packed upper triangular matrix of <n> rows and
* <n> columns. Caller may only access cells $i \leq j$.
* Cells $i > j$ are not stored and are implicitly 0.
*
* Not all matrix operations in Easel can work on packed
* upper triangular matrices.
*
* Returns: a pointer to a new <ESL_DMATRIX> object of type
* <eslUPPER>. Caller frees with <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> if allocation fails.
*
* Xref: J1/10
*/
ESL_DMATRIX *
esl_dmatrix_CreateUpper(int n)
{
int status;
ESL_DMATRIX *A = NULL;
int r; /* counter over rows */
int nc; /* cell counter */
/* matrix structure allocation */
ESL_ALLOC(A, sizeof(ESL_DMATRIX));
A->mx = NULL;
A->n = n;
A->m = n;
/* n row ptrs */
ESL_ALLOC(A->mx, sizeof(double *) * n);
A->mx[0] = NULL;
/* cell storage */
ESL_ALLOC(A->mx[0], sizeof(double) * n * (n+1) / 2);
/* row pointers set in a tricksy overlapping way, so
* mx[i][j] access works normally but only i<=j are valid.
* xref J1/10.
*/
nc = n; /* nc is the number of valid cells assigned to rows so far */
for (r = 1; r < n; r++) {
A->mx[r] = A->mx[0] + nc - r; /* -r overlaps this row w/ previous row */
nc += n-r;
}
A->type = eslUPPER;
A->ncells = n * (n+1) / 2;
return A;
ERROR:
esl_dmatrix_Destroy(A);
return NULL;
}
/* Function: esl_dmatrix_Destroy()
*
* Purpose: Frees an <ESL_DMATRIX> object <A>.
*/
int
esl_dmatrix_Destroy(ESL_DMATRIX *A)
{
if (A != NULL && A->mx != NULL && A->mx[0] != NULL) free(A->mx[0]);
if (A != NULL && A->mx != NULL) free(A->mx);
if (A != NULL) free(A);
return eslOK;
}
/* Function: esl_dmatrix_Copy()
*
* Purpose: Copies <src> matrix into <dest> matrix. <dest> must
* be allocated already by the caller.
*
* You may copy to a matrix of a different type, so long as
* the copy makes sense. If <dest> matrix is a packed type
* and <src> is not, the values that should be zeros must
* be zero in <src>, else the routine throws
* <eslEINCOMPAT>. If the <src> matrix is a packed type and
* <dest> is not, the values that are implicitly zeros are
* set to zeros in the <dest> matrix.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEINCOMPAT> if <src>, <dest> are different sizes,
* or if their types differ and <dest> cannot represent
* <src>.
*/
int
esl_dmatrix_Copy(const ESL_DMATRIX *src, ESL_DMATRIX *dest)
{
int i,j;
if (dest->n != src->n || dest->m != src->m)
ESL_EXCEPTION(eslEINCOMPAT, "matrices of different size");
if (src->type == dest->type) /* simple case. */
memcpy(dest->mx[0], src->mx[0], src->ncells * sizeof(double));
else if (src->type == eslGENERAL && dest->type == eslUPPER)
{
for (i = 1; i < src->n; i++)
for (j = 0; j < i; j++)
if (src->mx[i][j] != 0.)
ESL_EXCEPTION(eslEINCOMPAT, "general matrix isn't upper triangular, can't be copied/packed");
for (i = 0; i < src->n; i++)
for (j = i; j < src->m; j++)
dest->mx[i][j] = src->mx[i][j];
}
else if (src->type == eslUPPER && dest->type == eslGENERAL)
{
for (i = 1; i < src->n; i++)
for (j = 0; j < i; j++)
dest->mx[i][j] = 0.;
for (i = 0; i < src->n; i++)
for (j = i; j < src->m; j++)
dest->mx[i][j] = src->mx[i][j];
}
return eslOK;
}
/* Function: esl_dmatrix_Clone()
* Incept: SRE, Tue May 2 14:38:45 2006 [St. Louis]
*
* Purpose: Duplicates matrix <A>, making a copy in newly
* allocated space.
*
* Returns: a pointer to the copy. Caller frees with
* <esl_dmatrix_Destroy()>.
*
* Throws: <NULL> on allocation failure.
*/
ESL_DMATRIX *
esl_dmatrix_Clone(const ESL_DMATRIX *A)
{
ESL_DMATRIX *new;
switch (A->type) {
case eslUPPER: if ( (new = esl_dmatrix_CreateUpper(A->n)) == NULL) return NULL; break;
default: case eslGENERAL: if ( (new = esl_dmatrix_Create(A->n, A->m)) == NULL) return NULL; break;
}
esl_dmatrix_Copy(A, new);
return new;
}
/* Function: esl_dmatrix_Compare()
*
* Purpose: Compares matrix <A> to matrix <B> element by element,
* using <esl_DCompare()> on each cognate element pair,
* with relative equality defined by a fractional tolerance
* <tol>. If all elements are equal, return <eslOK>; if
* any elements differ, return <eslFAIL>.
*
* <A> and <B> may be of different types; for example,
* a packed upper triangular matrix A is compared to
* a general matrix B by assuming <A->mx[i][j] = 0.> for
* all $i>j$.
*/
int
esl_dmatrix_Compare(const ESL_DMATRIX *A, const ESL_DMATRIX *B, double tol)
{
int i,j,c;
double x1,x2;
if (A->n != B->n) return eslFAIL;
if (A->m != B->m) return eslFAIL;
if (A->type == B->type)
{ /* simple case. */
for (c = 0; c < A->ncells; c++) /* can deal w/ packed or unpacked storage */
if (esl_DCompare(A->mx[0][c], B->mx[0][c], tol) == eslFAIL) return eslFAIL;
}
else
{ /* comparing matrices of different types */
for (i = 0; i < A->n; i++)
for (j = 0; j < A->m; j++)
{
if (A->type == eslUPPER && i > j) x1 = 0.;
else x1 = A->mx[i][j];
if (B->type == eslUPPER && i > j) x2 = 0.;
else x2 = B->mx[i][j];
if (esl_DCompare(x1, x2, tol) == eslFAIL) return eslFAIL;
}
}
return eslOK;
}
/* Function: esl_dmatrix_CompareAbs()
*
* Purpose: Compares matrix <A> to matrix <B> element by element,
* using <esl_DCompareAbs()> on each cognate element pair,
* with absolute equality defined by a absolute difference tolerance
* <tol>. If all elements are equal, return <eslOK>; if
* any elements differ, return <eslFAIL>.
*
* <A> and <B> may be of different types; for example,
* a packed upper triangular matrix A is compared to
* a general matrix B by assuming <A->mx[i][j] = 0.> for
* all $i>j$.
*/
int
esl_dmatrix_CompareAbs(const ESL_DMATRIX *A, const ESL_DMATRIX *B, double tol)
{
int i,j,c;
double x1,x2;
if (A->n != B->n) return eslFAIL;
if (A->m != B->m) return eslFAIL;
if (A->type == B->type)
{ /* simple case. */
for (c = 0; c < A->ncells; c++) /* can deal w/ packed or unpacked storage */
if (esl_DCompareAbs(A->mx[0][c], B->mx[0][c], tol) == eslFAIL) return eslFAIL;
}
else
{ /* comparing matrices of different types */
for (i = 0; i < A->n; i++)
for (j = 0; j < A->m; j++)
{
if (A->type == eslUPPER && i > j) x1 = 0.;
else x1 = A->mx[i][j];
if (B->type == eslUPPER && i > j) x2 = 0.;
else x2 = B->mx[i][j];
if (esl_DCompareAbs(x1, x2, tol) == eslFAIL) return eslFAIL;
}
}
return eslOK;
}
/* Function: esl_dmatrix_Set()
*
* Purpose: Set all elements $a_{ij}$ in matrix <A> to <x>,
* and returns <eslOK>.
*/
int
esl_dmatrix_Set(ESL_DMATRIX *A, double x)
{
int i;
for (i = 0; i < A->ncells; i++) A->mx[0][i] = x;
return eslOK;
}
/* Function: esl_dmatrix_SetZero()
*
* Purpose: Sets all elements $a_{ij}$ in matrix <A> to 0,
* and returns <eslOK>.
*/
int
esl_dmatrix_SetZero(ESL_DMATRIX *A)
{
int i;
for (i = 0; i < A->ncells; i++) A->mx[0][i] = 0.;
return eslOK;
}
/* Function: esl_dmatrix_SetIdentity()
*
* Purpose: Given a square matrix <A>, sets all diagonal elements
* $a_{ii}$ to 1, and all off-diagonal elements $a_{ij},
* j \ne i$ to 0. Returns <eslOK> on success.
*
* Throws: <eslEINVAL> if the matrix isn't square.
*/
int
esl_dmatrix_SetIdentity(ESL_DMATRIX *A)
{
int i;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
esl_dmatrix_SetZero(A);
for (i = 0; i < A->n; i++) A->mx[i][i] = 1.;
return eslOK;
}
/*****************************************************************
* 2. Debugging, validation code
*****************************************************************/
/* Function: esl_dmatrix_Dump()
* Incept: SRE, Mon Nov 29 19:21:20 2004 [St. Louis]
*
* Purpose: Given a matrix <A>, dump it to output stream <ofp> in human-readable
* format.
*
* If <rowlabel> or <collabel> are non-NULL, they specify a
* string of single-character labels to put on the rows and
* columns, respectively. (For example, these might be a
* sequence alphabet for a 4x4 or 20x20 rate matrix or
* substitution matrix.) Numbers <1..ncols> or <1..nrows> are
* used if <collabel> or <rowlabel> are passed as <NULL>.
*
* Args: ofp - output file pointer; stdout, for example.
* A - matrix to dump.
* rowlabel - optional: NULL, or character labels for rows
* collabel - optional: NULL, or character labels for cols
*
* Returns: <eslOK> on success.
*/
int
esl_dmatrix_Dump(FILE *ofp, const ESL_DMATRIX *A, const char *rowlabel, const char *collabel)
{
int a,b;
fprintf(ofp, " ");
if (collabel != NULL)
for (b = 0; b < A->m; b++) fprintf(ofp, " %c ", collabel[b]);
else
for (b = 0; b < A->m; b++) fprintf(ofp, "%8d ", b+1);
fprintf(ofp, "\n");
for (a = 0; a < A->n; a++) {
if (rowlabel != NULL) fprintf(ofp, " %c ", rowlabel[a]);
else fprintf(ofp, "%5d ", a+1);
for (b = 0; b < A->m; b++) {
switch (A->type) {
case eslUPPER:
if (a > b) fprintf(ofp, "%8s ", "");
else fprintf(ofp, "%8.4f ", A->mx[a][b]);
break;
default: case eslGENERAL:
fprintf(ofp, "%8.4f ", A->mx[a][b]);
break;
}
}
fprintf(ofp, "\n");
}
return eslOK;
}
/*****************************************************************
* 3. Visualization tools
*****************************************************************/
/* Function: esl_dmatrix_PlotHeatMap()
* Synopsis: Export a heat map visualization, in PostScript
*
* Purpose: Export a heat map visualization of the matrix in <D>
* to open stream <fp>, in PostScript format.
*
* All values between <min> and <max> in <D> are rescaled
* linearly and assigned to shades. Values below <min>
* are assigned to the lowest shade; values above <max>, to
* the highest shade.
*
* The plot is hardcoded to be a full US 8x11.5" page,
* with at least a 20pt margin.
*
* Several color schemes are enumerated in the code
* but all but one is commented out. The currently enabled
* scheme is a 10-class scheme consisting of the 9-class
* Reds from colorbrewer2.org plus a blue background class.
*
* Note: Binning rules basically follow same convention as
* esl_histogram. nb = xmax-xmin/w, so w = xmax-xmin/nb;
* picking bin is (int) ceil((x - xmin)/w) - 1. (xref
* esl_histogram_Score2Bin()). This makes bin b contain
* values bw+min < x <= (b+1)w+min. (Which means that
* min itself falls in bin -1, whoops - but we catch
* all bin<0 and bin>=nshades and put them in the extremes.
*
* Returns: <eslOK> on success.
*
* Throws: (no abnormal error conditions)
*/
int
esl_dmatrix_PlotHeatMap(FILE *fp, ESL_DMATRIX *D, double min, double max)
{
#if 0
/*
* This color scheme roughly follows Tufte, Envisioning Information,
* p.91, where he shows a beautiful bathymetric chart. The CMYK
* values conjoin two recommendations from ColorBrewer (Cindy Brewer
* and Mark Harrower, colorbrewer2.org), specifically the 9-class
* sequential2 Blues and 9-class sequential YlOrBr.
*/
int nshades = 18;
double cyan[] = { 1.00, 1.00, 0.90, 0.75, 0.57, 0.38, 0.24, 0.13, 0.03,
0.00, 0.00, 0.00, 0.00, 0.00, 0.07, 0.20, 0.40, 0.60};
double magenta[] = { 0.55, 0.45, 0.34, 0.22, 0.14, 0.08, 0.06, 0.03, 0.01,
0.00, 0.03, 0.11, 0.23, 0.40, 0.55, 0.67, 0.75, 0.80};
double yellow[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.10, 0.25, 0.40, 0.65, 0.80, 0.90, 1.00, 1.00, 1.00};
double black[] = { 0.30, 0.07, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00,
0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00};
#endif
#if 0
/* colorbrewer2.org 5-class YlOrBr scheme: sequential, multihue, 5-class, CMYK */
int nshades = 5;
double cyan[] = { 0.00, 0.00, 0.00, 0.15, 0.40 };
double magenta[] = { 0.00, 0.15, 0.40, 0.60, 0.75 };
double yellow[] = { 0.17, 0.40, 0.80, 0.95, 1.00 };
double black[] = { 0, 0, 0, 0, 0 };
#endif
#if 0
/* colorbrewer2.org 9-class YlOrBr scheme, +zero class */
int nshades = 10;
double cyan[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.07, 0.20, 0.40, 0.60 };
double magenta[] = { 0.00, 0.00, 0.03, 0.11, 0.23, 0.40, 0.55, 0.67, 0.75, 0.80 };
double yellow[] = { 0.00, 0.10, 0.25, 0.40, 0.65, 0.80, 0.90, 1.00, 1.00, 1.00 };
double black[] = { 0.05, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 };
#endif
/* colorbrewer2.org 9-class Reds + zero class as dim blue */
int nshades = 10;
double cyan[] = { 0.30, 0.00, 0.00, 0.00, 0.00, 0.00, 0.05, 0.20, 0.35, 0.60 };
double magenta[] = { 0.03, 0.04, 0.12, 0.27, 0.43, 0.59, 0.77, 0.90, 0.95, 1.00 };
double yellow[] = { 0.00, 0.04, 0.12, 0.27, 0.43, 0.59, 0.72, 0.80, 0.85, 0.90 };
double black[] = { 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 };
int pageheight = 792;
int pagewidth = 612;
double w;
int i,j;
int bin;
float boxsize; /* box size in points */
float xcoord, ycoord; /* postscript coords in points */
float leftmargin;
float bottommargin;
/* Set some defaults that might become arguments later.
*/
leftmargin = 20.;
bottommargin = 20.;
/* Determine some working parameters
*/
w = (max-min) / (double) nshades; /* w = bin size for assigning values->colors*/
boxsize = ESL_MIN( (pageheight - (bottommargin * 2.)) / (float) D->n,
(pagewidth - (leftmargin * 2.)) / (float) D->m);
/* or start from j=i, to do diagonals */
for (i = 0; i < D->n; i++)
for (j = 0; j < D->m; j++)
{
xcoord = (float) j * boxsize + leftmargin;
ycoord = (float) (D->n-i+1) * boxsize + bottommargin;
if (D->mx[i][j] == -eslINFINITY) bin = 0;
else if (D->mx[i][j] == eslINFINITY) bin = nshades-1;
else {
bin = (int) ceil((D->mx[i][j] - min) / w) - 1;
if (bin < 0) bin = 0;
if (bin >= nshades) bin = nshades-1;
}
fprintf(fp, "newpath\n");
fprintf(fp, " %.2f %.2f moveto\n", xcoord, ycoord);
fprintf(fp, " 0 %.2f rlineto\n", boxsize);
fprintf(fp, " %.2f 0 rlineto\n", boxsize);
fprintf(fp, " 0 -%.2f rlineto\n", boxsize);
fprintf(fp, " closepath\n");
fprintf(fp, " %.2f %.2f %.2f %.2f setcmykcolor\n",
cyan[bin], magenta[bin], yellow[bin], black[bin]);
fprintf(fp, " fill\n");
}
fprintf(fp, "showpage\n");
return eslOK;
}
/*****************************************************************
* 4. The ESL_PERMUTATION object.
*****************************************************************/
/* Function: esl_permutation_Create()
*
* Purpose: Creates a new permutation "matrix" of size <n> for
* permuting <n> x <n> square matrices; returns a
* pointer to it.
*
* A permutation matrix consists of 1's and 0's such that
* any given row or column contains only one 1. We store it
* more efficiently as a vector; each value $p_i$
* represents the column $j$ that has the 1. Thus, on
* initialization, $p_i = i$ for all $i = 0..n-1$.
*
* Returns: a pointer to a new <ESL_PERMUTATION> object. Free with
* <esl_permutation_Destroy()>.
*
* Throws: <NULL> if allocation fails.
*/
ESL_PERMUTATION *
esl_permutation_Create(int n)
{
int status;
ESL_PERMUTATION *P = NULL;
ESL_DASSERT1(( n > 0 ));
ESL_ALLOC(P, sizeof(ESL_PERMUTATION));
P->pi = NULL;
P->n = n;
ESL_ALLOC(P->pi, sizeof(int) * n);
esl_permutation_Reuse(P); /* initialize it */
return P;
ERROR:
esl_permutation_Destroy(P);
return NULL;
}
/* Function: esl_permutation_Destroy()
*
* Purpose: Frees an <ESL_PERMUTATION> object <P>.
*/
int
esl_permutation_Destroy(ESL_PERMUTATION *P)
{
if (P != NULL && P->pi != NULL) free(P->pi);
if (P != NULL) free(P);
return eslOK;
}
/* Function: esl_permutation_Reuse()
*
* Purpose: Resets a permutation matrix <P> to
* $p_i = i$ for all $i = 0..n-1$.
*
* Returns: <eslOK> on success.
*/
int
esl_permutation_Reuse(ESL_PERMUTATION *P)
{
int i;
for (i = 0; i < P->n; i++)
P->pi[i] = i;
return eslOK;
}
/*****************************************************************
* 5. Debugging/validation for ESL_PERMUTATION.
*****************************************************************/
/* Function: esl_permutation_Dump()
*
* Purpose: Given a permutation matrix <P>, dump it to output stream <ofp>
* in human-readable format.
*
* If <rowlabel> or <collabel> are non-NULL, they represent
* single-character labels to put on the rows and columns,
* respectively. (For example, these might be a sequence
* alphabet for a 4x4 or 20x20 rate matrix or substitution
* matrix.) Numbers 1..ncols or 1..nrows are used if
* <collabel> or <rowlabel> are NULL.
*
* Args: ofp - output file pointer; stdout, for example
* P - permutation matrix to dump
* rowlabel - optional: NULL, or character labels for rows
* collabel - optional: NULL, or character labels for cols
*
* Returns: <eslOK> on success.
*/
int
esl_permutation_Dump(FILE *ofp, const ESL_PERMUTATION *P, const char *rowlabel, const char *collabel)
{
int i,j;
fprintf(ofp, " ");
if (collabel != NULL)
for (j = 0; j < P->n; j++) fprintf(ofp, " %c ", collabel[j]);
else
for (j = 0; j < P->n; j++) fprintf(ofp, "%3d ", j+1);
fprintf(ofp, "\n");
for (i = 0; i < P->n; i++) {
if (rowlabel != NULL) fprintf(ofp, " %c ", rowlabel[i]);
else fprintf(ofp, "%3d ", i+1);
for (j = 0; j < P->n; j++)
fprintf(ofp, "%3d ", (j == P->pi[i]) ? 1 : 0);
fprintf(ofp, "\n");
}
return eslOK;
}
/*****************************************************************
* 6. The rest of the dmatrix API.
*****************************************************************/
/* Function: esl_dmx_Max()
* Incept: SRE, Thu Mar 1 14:46:48 2007 [Janelia]
*
* Purpose: Returns the maximum value of all the elements $a_{ij}$ in matrix <A>.
*/
double
esl_dmx_Max(const ESL_DMATRIX *A)
{
int i;
double best;
best = A->mx[0][0];
for (i = 0; i < A->ncells; i++)
if (A->mx[0][i] > best) best = A->mx[0][i];
return best;
}
/* Function: esl_dmx_Min()
* Incept: SRE, Thu Mar 1 14:49:29 2007 [Janelia]
*
* Purpose: Returns the minimum value of all the elements $a_{ij}$ in matrix <A>.
*/
double
esl_dmx_Min(const ESL_DMATRIX *A)
{
int i;
double best;
best = A->mx[0][0];
for (i = 0; i < A->ncells; i++)
if (A->mx[0][i] < best) best = A->mx[0][i];
return best;
}
/* Function: esl_dmx_MinMax()
* Incept: SRE, Wed Mar 14 16:58:03 2007 [Janelia]
*
* Purpose: Finds the maximum and minimum values of the
* elements $a_{ij}$ in matrix <A>, and returns
* them in <ret_min> and <ret_max>.
*
* Returns: <eslOK> on success.
*
*/
int
esl_dmx_MinMax(const ESL_DMATRIX *A, double *ret_min, double *ret_max)
{
double min, max;
int i;
min = max = A->mx[0][0];
for (i = 0; i < A->ncells; i++) {
if (A->mx[0][i] < min) min = A->mx[0][i];
if (A->mx[0][i] > max) max = A->mx[0][i];
}
*ret_min = min;
*ret_max = max;
return eslOK;
}
/* Function: esl_dmx_Sum()
* Incept: SRE, Thu Mar 1 16:45:16 2007
*
* Purpose: Returns the scalar sum of all the elements $a_{ij}$ in matrix <A>,
* $\sum_{ij} a_{ij}$.
*/
double
esl_dmx_Sum(const ESL_DMATRIX *A)
{
int i;
double sum = 0.;
for (i = 0; i < A->ncells; i++)
sum += A->mx[0][i];
return sum;
}
/* Function: esl_dmx_FrobeniusNorm()
* Incept: SRE, Thu Mar 15 17:59:35 2007 [Janelia]
*
* Purpose: Calculates the Frobenius norm of a matrix, which
* is the element-wise equivalant of a
* Euclidean vector norm:
* $ = \sqrt(\sum a_{ij}^2)$
*
* Args: A - matrix
* ret_fnorm - Frobenius norm.
*
* Returns: <eslOK> on success, and the Frobenius norm
* is in <ret_fnorm>.
*/
int
esl_dmx_FrobeniusNorm(const ESL_DMATRIX *A, double *ret_fnorm)
{
double F = 0.;
int i;
for (i = 0; i < A->ncells; i++)
F += A->mx[0][i] * A->mx[0][i];
*ret_fnorm = sqrt(F);
return eslOK;
}
/* Function: esl_dmx_Multiply()
*
* Purpose: Matrix multiplication: calculate <AB>, store result in <C>.
* <A> is $n times m$; <B> is $m \times p$; <C> is $n \times p$.
* Matrix <C> must be allocated appropriately by the caller.
*
* Not supported for anything but general (<eslGENERAL>)
* matrix type, at present.
*
* Throws: <eslEINVAL> if matrices don't have compatible dimensions,
* or if any of them isn't a general (<eslGENERAL>) matrix.
*/
int
esl_dmx_Multiply(const ESL_DMATRIX *A, const ESL_DMATRIX *B, ESL_DMATRIX *C)
{
int i, j, k;
if (A->m != B->n) ESL_EXCEPTION(eslEINVAL, "can't multiply A,B");
if (A->n != C->n) ESL_EXCEPTION(eslEINVAL, "A,C # of rows not equal");
if (B->m != C->m) ESL_EXCEPTION(eslEINVAL, "B,C # of cols not equal");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "A isn't of type eslGENERAL");
if (B->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "B isn't of type eslGENERAL");
if (C->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "B isn't of type eslGENERAL");
/* i,k,j order should optimize stride, relative to a more textbook
* order for the indices
*/
esl_dmatrix_SetZero(C);
for (i = 0; i < A->n; i++)
for (k = 0; k < A->m; k++)
for (j = 0; j < B->m; j++)
C->mx[i][j] += A->mx[i][k] * B->mx[k][j];
return eslOK;
}
/*::cexcerpt::function_comment_example::begin::*/
/* Function: esl_dmx_Exp()
* Synopsis: Calculates matrix exponential $\mathbf{P} = e^{t\mathbf{Q}}$.
* Incept: SRE, Thu Mar 8 18:41:38 2007 [Janelia]
*
* Purpose: Calculates the matrix exponential $\mathbf{P} = e^{t\mathbf{Q}}$,
* using a scaling and squaring algorithm with
* the Taylor series approximation \citep{MolerVanLoan03}.
*
* <Q> must be a square matrix of type <eslGENERAL>.
* Caller provides an allocated <P> matrix of the same size and type as <Q>.
*
* A typical use of this function is to calculate a
* conditional substitution probability matrix $\mathbf{P}$
* (whose elements $P_{xy}$ are conditional substitution
* probabilities $\mathrm{Prob}(y \mid x, t)$ from time $t$
* and instantaneous rate matrix $\mathbf{Q}$.
*
* Args: Q - matrix to exponentiate (an instantaneous rate matrix)
* t - time units
* P - RESULT: $e^{tQ}$.
*
* Returns: <eslOK> on success.
*
* Throws: <eslEMEM> on allocation error.
*
* Xref: J1/19.
*/
int
esl_dmx_Exp(const ESL_DMATRIX *Q, double t, ESL_DMATRIX *P)
{
/*::cexcerpt::function_comment_example::end::*/
ESL_DMATRIX *Qz = NULL; /* Q/2^z rescaled matrix*/
ESL_DMATRIX *Qpow = NULL; /* keeps running product Q^k */
ESL_DMATRIX *C = NULL; /* tmp storage for matrix multiply result */
double factor = 1.0;
double fnorm;
int z;
double zfac;
int k;
int status;
/* Contract checks */
if (Q->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "Q isn't general");
if (Q->n != Q->m) ESL_EXCEPTION(eslEINVAL, "Q isn't square");
if (P->type != Q->type) ESL_EXCEPTION(eslEINVAL, "P isn't of same type as Q");
if (P->n != P->m) ESL_EXCEPTION(eslEINVAL, "P isn't square");
if (P->n != Q->n) ESL_EXCEPTION(eslEINVAL, "P isn't same size as Q");
/* Allocation of working space */
if ((Qz = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
if ((Qpow = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
if ((C = esl_dmatrix_Create(Q->n, Q->n)) == NULL) { status = eslEMEM; goto ERROR; }
/* Figure out how much to scale the matrix down by. This is not
* magical; we're just knocking its magnitude down in an ad hoc way.
*/
esl_dmx_FrobeniusNorm(Q, &fnorm);
zfac = 1.;
z = 0;
while (t*fnorm*zfac > 0.1) { zfac /= 2.; z++; }
/* Make a scaled-down copy of Q in Qz.
*/
esl_dmatrix_Copy(Q, Qz);
esl_dmx_Scale(Qz, zfac);
/* Calculate e^{t Q_z} by the Taylor, to complete convergence. */
esl_dmatrix_SetIdentity(P);
esl_dmatrix_Copy(Qz, Qpow); /* Qpow is now Qz^1 */
for (k = 1; k < 100; k++)
{
factor *= t/k;
esl_dmatrix_Copy(P, C); /* C now holds the previous P */
esl_dmx_AddScale(P, factor, Qpow); /* P += factor*Qpow */
if (esl_dmatrix_Compare(C, P, 0.) == eslOK) break;
esl_dmx_Multiply(Qpow, Qz, C); /* C = Q^{k+1} */
esl_dmatrix_Copy(C, Qpow); /* Qpow = C = Q^{k+1} */
}
/* Now square it back up: e^{tQ} = [e^{tQ_z}]^{2^z} */
while (z--) {
esl_dmx_Multiply(P, P, C);
esl_dmatrix_Copy(C, P);
}
esl_dmatrix_Destroy(Qz);
esl_dmatrix_Destroy(Qpow);
esl_dmatrix_Destroy(C);
return eslOK;
ERROR:
if (Qz != NULL) esl_dmatrix_Destroy(Qz);
if (Qpow != NULL) esl_dmatrix_Destroy(Qpow);
if (C != NULL) esl_dmatrix_Destroy(C);
return status;
}
/* Function: esl_dmx_Transpose()
*
* Purpose: Transpose a square matrix <A> in place.
*
* <A> must be a general (<eslGENERAL>) matrix type.
*
* Throws: <eslEINVAL> if <A> isn't square, or if it isn't
* of type <eslGENERAL>.
*/
int
esl_dmx_Transpose(ESL_DMATRIX *A)
{
int i,j;
double swap;
if (A->n != A->m) ESL_EXCEPTION(eslEINVAL, "matrix isn't square");
if (A->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "A isn't of type eslGENERAL");
for (i = 0; i < A->n; i++)
for (j = i+1; j < A->m; j++)
{ swap = A->mx[i][j]; A->mx[i][j] = A->mx[j][i]; A->mx[j][i] = swap; }
return eslOK;
}
/* Function: esl_dmx_Add()
*
* Purpose: <A = A+B>; adds matrix <B> to matrix <A> and leaves result
* in matrix <A>.
*
* <A> and <B> may be of any type. However, if <A> is a
* packed upper triangular matrix (type
* <eslUPPER>), all values $i>j$ in <B> must be
* zero (i.e. <B> must also be upper triangular, though
* not necessarily packed upper triangular).
*
* Throws: <eslEINVAL> if matrices aren't the same dimensions, or
* if <A> is <eslUPPER> and any cell $i>j$ in
* <B> is nonzero.
*/
int
esl_dmx_Add(ESL_DMATRIX *A, const ESL_DMATRIX *B)
{
int i,j;
if (A->n != B->n) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->m != B->m) ESL_EXCEPTION(eslEINVAL, "matrices of different size");
if (A->type == B->type) /* in this case, can just add cell by cell */
{
for (i = 0; i < A->ncells; i++)
A->mx[0][i] += B->mx[0][i];
}
else if (A->type == eslUPPER || B->type == eslUPPER)
{
/* Logic is: if either matrix is upper triangular, then the operation is
* to add upper triangles only. If we try to add a general matrix <B>
* to packed UT <A>, make sure all lower triangle entries in <B> are zero.
*/
if (B->type != eslUPPER) {
for (i = 1; i < A->n; i++)
for (j = 0; j < i; j++)
if (B->mx[i][j] != 0.) ESL_EXCEPTION(eslEINVAL, "<B> has nonzero cells in lower triangle");
}
for (i = 0; i < A->n; i++)
for (j = i; j < A->m; j++)
A->mx[i][j] += B->mx[i][j];
}
return eslOK;
}
/* Function: esl_dmx_Scale()
*
* Purpose: Calculates <A = kA>: multiply matrix <A> by scalar
* <k> and leave answer in <A>.