Debian Codegraph @

easel/esl_ratematrix.c

raw symbols SCIP
1 /* Routines for manipulating evolutionary rate matrices.
2 *
3 * There is no specific object for this module. Rate matrix
4 * operations use square nxn ESL_DMATRIX data objects. (The rmx
5 * module essentially subclasses the dmx module.)
6 *
7 * An instantaneous rate matrix is usually denoted by Q. A
8 * conditional probability matrix (for a specific t) is usually
9 * denoted by P. An exchangeability matrix is denoted by E.
10 * A stationary residue probability vector is denoted by pi.
11 *
12 * Two important relations among these:
13 *
14 * Q in terms of E and pi:
15 * $Q_{ij} = E_{ij} \pi_j$ for $i \neq j$;
16 * $Q_{ii} = -\sum_{j \neq i} Q_{ij}$
17 *
18 * P in terms of Q and t:
19 * $P = e^{tQ}$
20 *
21 * Contents:
22 * 1. Setting standard rate matrix models.
23 * 2. Debugging routines for validating or dumping rate matrices.
24 * 3. Other routines in the exposed ratematrix API.
25 * 4. Benchmark driver.
26 * 5. Regression test driver.
27 * 6. Unit tests.
28 * 7. Test driver.
29 * 8. Example.
30 *
31 * See also:
32 * paml - i/o of rate matrices from/to data files in PAML format
33 */
34 #include <esl_config.h>
35
36 #include <math.h>
37
38 #include "easel.h"
39 #include "esl_composition.h"
40 #include "esl_dmatrix.h"
41 #include "esl_vectorops.h"
42 #include "esl_ratematrix.h"
43
44
45 /*****************************************************************
46 * 1. Setting standard rate matrix models.
47 *****************************************************************/
48
49 /* Function: esl_rmx_SetWAG()
50 * Incept: SRE, Thu Mar 8 18:00:00 2007 [Janelia]
51 *
52 * Purpose: Sets a $20 \times 20$ rate matrix <Q> to WAG parameters.
53 * The caller allocated <Q>.
54 *
55 * If <pi> is non-<NULL>, it provides a vector of 20 amino
56 * acid stationary probabilities in Easel alphabetic order,
57 * A..Y, and the WAG stationary probabilities are set to
58 * these desired $\pi_i$. If <pi> is <NULL>, the default
59 * WAG stationary probabilities are used.
60 *
61 * The WAG parameters are a maximum likelihood
62 * parameterization obtained by Whelan and Goldman
63 * \citep{WhelanGoldman01}.
64 *
65 * Note: The data table was reformatted from wag.dat by the UTILITY1
66 * executable in the paml module. The wag.dat file was obtained from
67 * \url{http://www.ebi.ac.uk/goldman/WAG/wag.dat}. A copy
68 * is in formats/wag.dat.
69 *
70 * Args: Q - a 20x20 rate matrix to set, allocated by caller.
71 * pi - desired stationary probabilities A..Y, or
72 * NULL to use WAG defaults.
73 *
74 * Returns: <eslOK> on success.
75 *
76 * Throws: <eslEINVAL> if <Q> isn't a 20x20 general matrix; and
77 * the state of <Q> is undefined.
78 */
79 int
80 esl_rmx_SetWAG(ESL_DMATRIX *Q, double *pi)
81 {
82 static double wagE[190] = {
83 1.027040, 0.738998, 0.030295, 1.582850, 0.021352, 6.174160, 0.210494, 0.398020, 0.046730, 0.081134,
84 1.416720, 0.306674, 0.865584, 0.567717, 0.049931, 0.316954, 0.248972, 0.930676, 0.570025, 0.679371,
85 0.249410, 0.193335, 0.170135, 0.039437, 0.127395, 1.059470, 0.030450, 0.138190, 0.906265, 0.074034,
86 0.479855, 2.584430, 0.088836, 0.373558, 0.890432, 0.323832, 0.397915, 0.384287, 0.084805, 0.154263,
87 2.115170, 0.061304, 0.499462, 3.170970, 0.257555, 0.893496, 0.390482, 0.103754, 0.315124, 1.190630,
88 0.174100, 0.404141, 4.257460, 0.934276, 4.854020, 0.509848, 0.265256, 5.429420, 0.947198, 0.096162,
89 1.125560, 3.956290, 0.554236, 3.012010, 0.131528, 0.198221, 1.438550, 0.109404, 0.423984, 0.682355,
90 0.161444, 0.243570, 0.696198, 0.099929, 0.556896, 0.415844, 0.171329, 0.195081, 0.908598, 0.098818,
91 0.616783, 5.469470, 0.099921, 0.330052, 4.294110, 0.113917, 3.894900, 0.869489, 1.545260, 1.543640,
92 0.933372, 0.551571, 0.528191, 0.147304, 0.439157, 0.102711, 0.584665, 2.137150, 0.186979, 5.351420,
93 0.497671, 0.683162, 0.635346, 0.679489, 3.035500, 3.370790, 1.407660, 1.071760, 0.704939, 0.545931,
94 1.341820, 0.740169, 0.319440, 0.967130, 0.344739, 0.493905, 3.974230, 1.613280, 1.028870, 1.224190,
95 2.121110, 0.512984, 0.374866, 0.822765, 0.171903, 0.225833, 0.473307, 1.458160, 1.386980, 0.326622,
96 1.516120, 2.030060, 0.795384, 0.857928, 0.554413, 4.378020, 2.006010, 1.002140, 0.152335, 0.588731,
97 0.649892, 0.187247, 0.118358, 7.821300, 0.305434, 1.800340, 2.058450, 0.196246, 0.314887, 0.301281,
98 0.251849, 0.232739, 1.388230, 0.113133, 0.717070, 0.129767, 0.156557, 1.529640, 0.336983, 0.262569,
99 0.212483, 0.137505, 0.665309, 0.515706, 0.071917, 0.139405, 0.215737, 1.163920, 0.523742, 0.110864,
100 0.365369, 0.240735, 0.543833, 0.325711, 0.196303, 6.454280, 0.103604, 3.873440, 0.420170, 0.133264,
101 0.398618, 0.428437, 1.086000, 0.216046, 0.227710, 0.381533, 0.786993, 0.291148, 0.314730, 2.485390};
102 static double wagpi[20];
103 int i,j,z;
104
105 if (Q->m != 20 || Q->n != 20 || Q->type != eslGENERAL)
106 ESL_EXCEPTION(eslEINVAL, "Q must be a 20x20 general matrix");
107 esl_composition_WAG(wagpi);
108
109 /* 1. Transfer the wag E lower triagonal matrix directly into Q. */
110 z = 0;
111 for (i = 0; i < 20; i++)
112 {
113 Q->mx[i][i] = 0.; /* code below depends on this zero initialization */
114 for (j = 0; j < i; j++) {
115 Q->mx[i][j] = wagE[z++];
116 Q->mx[j][i] = Q->mx[i][j];
117 }
118 }
119
120 /* 2. Set offdiagonals Q_ij = E_ij * pi_j */
121 for (i = 0; i < 20; i++)
122 for (j = 0; j < 20; j++)
123 if (pi != NULL) Q->mx[i][j] *= pi[j];
124 else Q->mx[i][j] *= wagpi[j];
125
126 /* 3. Set diagonal Q_ii to -\sum_{i \neq j} Q_ij */
127 for (i = 0; i < 20; i++)
128 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 20);
129
130 /* 4. Renormalize matrix to units of 1 substitution/site. */
131 if (pi != NULL) esl_rmx_ScaleTo(Q, pi, 1.0);
132 else esl_rmx_ScaleTo(Q, wagpi, 1.0);
133
134 return eslOK;
135 }
136
137
138 /* Function: esl_rmx_SetJukesCantor()
139 * Incept: SRE, Thu Mar 15 13:04:56 2007 [Janelia]
140 *
141 * Purpose: Sets a 4x4 rate matrix to a Jukes-Cantor model,
142 * scaled to units of 1t = 1.0 substitutions/site.
143 *
144 * Note: eigenvalues of Q are 0, -4\alpha, -4\alpha, -4\alpha
145 */
146 int
147 esl_rmx_SetJukesCantor(ESL_DMATRIX *Q)
148 {
149 int i,j;
150 double pi[4] = { 0.25, 0.25, 0.25, 0.25 };
151
152 if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
153 ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
154
155 for (i = 0; i < 4; i++) {
156 for (j = 0; j < 4; j++)
157 {
158 if (i != j) Q->mx[i][j] = 1.0;
159 else Q->mx[i][j] = 0.0;
160 }
161 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
162 }
163 esl_rmx_ScaleTo(Q, pi, 1.0);
164 return eslOK;
165 }
166
167
168 /* Function: esl_rmx_SetKimura()
169 * Incept: SRE, Thu Mar 15 13:08:08 2007 [Janelia]
170 *
171 * Purpose: Sets a 4x4 rate matrix to a Kimura 2-parameter
172 * model, given transition and transversion
173 * relative rates <alpha> and <beta>, respectively,
174 * scaled to units of 1t = 1.0 substitutions/site.
175 *
176 * Note: eigenvalues of Q are 0, -4\alpha, -2(\alpha+\beta), -2(\alpha+\beta)
177 */
178 int
179 esl_rmx_SetKimura(ESL_DMATRIX *Q, double alpha, double beta)
180 {
181 int i,j;
182 double pi[4] = { 0.25, 0.25, 0.25, 0.25 };
183
184 if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
185 ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
186
187 for (i = 0; i < 4; i++) {
188 for (j = 0; j < 4; j++)
189 {
190 if (i != j) Q->mx[i][j] = ((i+j)%2)? beta : alpha; /* even=0=transition;odd=1=transversion */
191 else Q->mx[i][j] = 0.0;
192 }
193 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
194 }
195 esl_rmx_ScaleTo(Q, pi, 1.0);
196 return eslOK;
197 }
198
199
200
201 /* Function: esl_rmx_SetF81()
202 * Incept: SRE, Thu Mar 15 13:33:30 2007 [Janelia]
203 *
204 * Purpose: Sets a 4x4 rate matrix to the F81 model (aka
205 * equal-input model) given stationary base
206 * compositions <pi>,
207 * scaled to units of 1t = 1.0 substitutions/site.
208 */
209 int
210 esl_rmx_SetF81(ESL_DMATRIX *Q, double *pi)
211 {
212 int i,j;
213
214 if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
215 ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
216
217 for (i = 0; i < 4; i++) {
218 for (j = 0; j < 4; j++)
219 {
220 if (i != j) Q->mx[i][j] = pi[j];
221 else Q->mx[i][j] = 0.0;
222 }
223 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
224 }
225 esl_rmx_ScaleTo(Q, pi, 1.0);
226 return eslOK;
227 }
228
229
230 /* Function: esl_rmx_SetHKY()
231 * Incept: SRE, Thu Aug 12 08:26:39 2004 [St. Louis]
232 *
233 * Purpose: Given stationary base composition <pi> for ACGT, and
234 * transition and transversion relative rates <alpha> and
235 * <beta> respectively, sets the matrix <Q> to be the
236 * corresponding HKY (Hasegawa/Kishino/Yano) DNA rate
237 * matrix, scaled in units of 1t= 1.0 substitutions/site
238 * \citep{Hasegawa85}.
239 *
240 * Args: pi - stationary base composition A..T
241 * alpha - relative transition rate
242 * beta - relative transversion rate
243 *
244 *
245 * Returns: <eslOK>
246 *
247 * Xref:
248 */
249 int
250 esl_rmx_SetHKY( ESL_DMATRIX *Q, double *pi, double alpha, double beta)
251 {
252 int i,j;
253
254 if (Q->m != 4 || Q->n != 4 || Q->type != eslGENERAL)
255 ESL_EXCEPTION(eslEINVAL, "Q must be a 4x4 general matrix");
256
257 for (i = 0; i < 4; i++) {
258 for (j = 0; j < 4; j++)
259 {
260 if (i != j) Q->mx[i][j] = ((i+j)%2)? pi[j]*beta : pi[j]*alpha; /* even=0=transition;odd=1=transversion */
261 else Q->mx[i][j] = 0.;
262 }
263 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], 4);
264 }
265 esl_rmx_ScaleTo(Q, pi, 1.0);
266 return eslOK;
267 }
268
269 /*****************************************************************
270 * 2. Debugging routines for validating or dumping rate matrices.
271 *****************************************************************/
272
273 /* Function: esl_rmx_ValidateP()
274 * Incept: SRE, Sun Mar 11 10:30:50 2007 [Janelia]
275 *
276 * Purpose: Validates a conditional probability matrix <P>, whose
277 * elements $P_{ij}$ represent conditional probabilities
278 * $P(j \mid i)$; for example in a first-order Markov
279 * chain, or a continuous-time Markov transition process
280 * where <P> is for a particular $t$.
281 *
282 * Rows must sum to one, and each element $P_{ij}$ is a
283 * probability $0 \leq P_{ij} \leq 1$.
284 *
285 * <tol> specifies the floating-point tolerance to which
286 * the row sums must equal one: <fabs(sum-1.0) <= tol>.
287 *
288 * <errbuf> is an optional error message buffer. The caller
289 * may pass <NULL> or a pointer to a buffer of at least
290 * <eslERRBUFSIZE> characters.
291 *
292 * Args: P - matrix to validate
293 * tol - floating-point tolerance (0.00001, for example)
294 * errbuf - OPTIONAL: ptr to an error buffer of at least
295 * <eslERRBUFSIZE> characters.
296 *
297 * Returns: <eslOK> on successful validation.
298 * <eslFAIL> on failure, and if a non-<NULL> <errbuf> was
299 * provided by the caller, a message describing
300 * the reason for the failure is put there.
301 *
302 * Throws: (no abnormal error conditions)
303 */
304 int
305 esl_rmx_ValidateP(ESL_DMATRIX *P, double tol, char *errbuf)
306 {
307 int i,j;
308 double sum;
309
310 if (P->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "P must be type eslGENERAL to be validated");
311
312 for (i = 0; i < P->n; i++)
313 {
314 sum = esl_vec_DSum(P->mx[i], P->m);
315 if (fabs(sum-1.0) > tol) ESL_FAIL(eslFAIL, errbuf, "row %d does not sum to 1.0", i);
316
317 for (j = 0; j < P->m; j++)
318 if (P->mx[i][j] < 0.0 || P->mx[i][j] > 1.0)
319 ESL_FAIL(eslFAIL, errbuf, "element %d,%d is not a probability (%f)", i,j,P->mx[i][j]);
320 }
321 return eslOK;
322 }
323
324 /* Function: esl_rmx_ValidateQ()
325 * Incept: SRE, Sun Mar 11 10:30:50 2007 [Janelia]
326 *
327 * Purpose: Validates an instantaneous rate matrix <Q> for a
328 * continuous-time Markov process, whose elements $q_{ij}$
329 * represent instantaneous transition rates $i \rightarrow
330 * j$.
331 *
332 * Rows satisfy the condition that
333 * $q_{ii} = -\sum_{i \neq j} q_{ij}$, and also
334 * that $q_{ij} \geq 0$ for all $j \neq i$.
335 *
336 * <tol> specifies the floating-point tolerance to which
337 * that condition must hold: <fabs(sum-q_ii) <= tol>.
338 *
339 * <errbuf> is an optional error message buffer. The caller
340 * may pass <NULL> or a pointer to a buffer of at least
341 * <eslERRBUFSIZE> characters.
342 *
343 * Args: Q - rate matrix to validate
344 * tol - floating-point tolerance (0.00001, for example)
345 * errbuf - OPTIONAL: ptr to an error buffer of at least
346 * <eslERRBUFSIZE> characters.
347 *
348 * Returns: <eslOK> on successful validation.
349 * <eslFAIL> on failure, and if a non-<NULL> <errbuf> was
350 * provided by the caller, a message describing
351 * the reason for the failure is put there.
352 *
353 * Throws: (no abnormal error conditions)
354 */
355 int
356 esl_rmx_ValidateQ(ESL_DMATRIX *Q, double tol, char *errbuf)
357 {
358 int i,j;
359 double qi;
360
361 if (Q->type != eslGENERAL) ESL_EXCEPTION(eslEINVAL, "Q must be type eslGENERAL to be validated");
362 if (Q->n != Q->m) ESL_EXCEPTION(eslEINVAL, "a rate matrix Q must be square");
363
364 for (i = 0; i < Q->n; i++)
365 {
366 qi = 0.;
367 for (j = 0; j < Q->m; j++)
368 {
369 if (i != j) {
370 if (Q->mx[i][j] < 0.) ESL_FAIL(eslFAIL, errbuf, "offdiag elem %d,%d < 0",i,j);
371 qi += Q->mx[i][j];
372 } else {
373 if (Q->mx[i][j] > 0.) ESL_FAIL(eslFAIL, errbuf, "diag elem %d,%d < 0", i,j);
374 }
375 }
376 if (fabs(qi + Q->mx[i][i]) > tol) ESL_FAIL(eslFAIL, errbuf, "row %d does not sum to 0.0", i);
377 }
378 return eslOK;
379 }
380
381
382
383 /*****************************************************************
384 * 3. Other routines in the exposed ratematrix API.
385 *****************************************************************/
386
387 /* Function: esl_rmx_ScaleTo()
388 * Incept: SRE, Tue Jul 13 16:05:16 2004 [St. Louis]
389 *
390 * Purpose: Rescales rate matrix <Q> so that expected substitution
391 * rate per dt is <unit>.
392 *
393 * Expected substitution rate is:
394 * $\sum_i \sum_j pi_i Q_ij \forall i \neq j$
395 *
396 * <unit> typically taken to be 1.0, so time units are substitutions/site.
397 * An exception is PAM, where <unit> = 0.01 for 1 PAM unit.
398 *
399 * Args: Q - rate matrix to normalize
400 * pi - stationary residue frequencies
401 * unit - expected subsitution rate per dt
402 * (1.0 = substitutions/site; 0.01 = PAMs)
403 *
404 * Returns: <eslOK> on success, and matrix Q is rescaled.
405 *
406 * Xref: STL8/p56.
407 */
408 int
409 esl_rmx_ScaleTo(ESL_DMATRIX *Q, double *pi, double unit)
410 {
411 int i,j;
412 double sum = 0.;
413
414 if (Q->m != Q->n || Q->type != eslGENERAL)
415 ESL_EXCEPTION(eslEINVAL, "Q must be a square general matrix");
416
417 for (i = 0; i < Q->m; i++)
418 for (j = 0; j < Q->n; j++)
419 if (i != j) sum += pi[i] * Q->mx[i][j];
420
421 for (i = 0; i < Q->m; i++)
422 for (j = 0; j < Q->n; j++)
423 Q->mx[i][j] *= (unit / sum);
424
425 return eslOK;
426 }
427
428
429
430 /* Function: esl_rmx_E2Q()
431 * Incept: SRE, Tue Jul 13 15:52:41 2004 [St. Louis]
432 *
433 * Purpose: Given a lower triangular matrix ($j<i$) of
434 * residue exchangeabilities <E>, and a stationary residue
435 * frequency vector <pi>; assuming $E_{ij} = E_{ji}$;
436 * calculates a rate matrix <Q> as
437 *
438 * $Q_{ij} = E_{ij} * \pi_j$
439 *
440 * The resulting <Q> is not normalized to any particular
441 * number of substitutions/site/time unit. See
442 * <esl_rmx_ScaleTo()> for that.
443 *
444 * Args: E - symmetric residue "exchangeabilities";
445 * only lower triangular entries are used.
446 * pi - residue frequencies at stationarity.
447 * Q - RETURN: rate matrix, square (NxN).
448 * Caller allocates the memory for this.
449 *
450 * Returns: <eslOK> on success; Q is calculated and filled in.
451 *
452 * Xref: STL8/p56.
453 */
454 int
455 esl_rmx_E2Q(ESL_DMATRIX *E, double *pi, ESL_DMATRIX *Q)
456 {
457 int i,j;
458
459 if (E->n != Q->n) ESL_EXCEPTION(eslEINVAL, "E and Q sizes differ");
460
461 /* Scale all off-diagonals to pi[j] * E[i][j].
462 */
463 for (i = 0; i < E->n; i++)
464 for (j = 0; j < i; j++) /* only look at lower triangle of E. */
465 {
466 Q->mx[i][j] = pi[j] * E->mx[i][j];
467 Q->mx[j][i] = pi[i] * E->mx[i][j];
468 }
469
470 /* Set diagonal to -\sum of all j != i.
471 */
472 for (i = 0; i < Q->n; i++)
473 {
474 Q->mx[i][i] = 0.; /* makes the vector sum work for j != i */
475 Q->mx[i][i] = -1. * esl_vec_DSum(Q->mx[i], Q->n);
476 }
477 return eslOK;
478 }
479
480
481 /* Function: esl_rmx_RelativeEntropy()
482 * Incept: SRE, Fri Mar 23 09:18:26 2007 [Janelia]
483 *
484 * Purpose: Given a conditional substitution probability matrix <P>,
485 * with stationary probabilities <pi>, calculate its
486 * relative entropy $H$:
487 *
488 * $H_t = \sum_{ij} P(j \mid i,t) \pi_i \log_2 \frac{P(j \mid i,t)} {\pi_j}$
489 *
490 * This assumes that the stationary probabilities are the
491 * same as the background (null model) probabilities.
492 *
493 * Returns: the relative entropy, $H$, in bits
494 */
495 double
496 esl_rmx_RelativeEntropy(ESL_DMATRIX *P, double *pi)
497 {
498 double H = 0.;
499 int i,j;
500
501 for (i = 0; i < P->m; i++)
502 for (j = 0; j < P->n; j++)
503 H += P->mx[i][j] * pi[i] * log(P->mx[i][j] / pi[j]);
504 return H / eslCONST_LOG2;
505 }
506
507 /* Function: esl_rmx_ExpectedScore()
508 * Incept: SRE, Fri Mar 23 09:32:05 2007 [Janelia]
509 *
510 * Purpose: Given a conditional substitution probability matrix <P>
511 * with stationary probabilities <pi>, calculate its
512 * expected score:
513 *
514 * $ = \sum_{ij} \pi_j \pi_i \log_2 \frac{P(j \mid i,t)} {\pi_j}$
515 *
516 * This assumes that the stationary probabilities are the
517 * same as the background (null model) probabilities.
518 *
519 * Returns: the expected score, in bits
520 */
521 double
522 esl_rmx_ExpectedScore(ESL_DMATRIX *P, double *pi)
523 {
524 double S = 0.;
525 int i,j;
526
527 for (i = 0; i < P->m; i++)
528 for (j = 0; j < P->n; j++)
529 S += pi[j] * pi[i] * log(P->mx[i][j] / pi[j]);
530 return S / eslCONST_LOG2;
531 }
532
533
534
535
536 /*****************************************************************
537 * 4. Benchmark driver
538 *****************************************************************/
539
540 #ifdef eslRATEMATRIX_BENCHMARK
541
542 /*
543 without GSL:
544 gcc -O2 -I. -L. -o benchmark -DeslRATEMATRIX_BENCHMARK esl_ratematrix.c -leasel -lm
545
546 with GSL:
547 gcc -g -Wall -I. -L. -o benchmark -DeslRATEMATRIX_BENCHMARK -DHAVE_LIBGSL esl_dmatrix.c esl_ratematrix.c -leasel -lgsl -lgslcblas -lm
548 */
549 #ifdef HAVE_LIBGSL
550 #include <gsl/gsl_matrix.h>
551 #include <gsl/gsl_linalg.h>
552 #endif
553
554 #include "easel.h"
555 #include "esl_stopwatch.h"
556 #include "esl_dmatrix.h"
557 #include "esl_ratematrix.h"
558
559 int
560 main(void)
561 {
562 ESL_STOPWATCH *w = NULL;
563 ESL_DMATRIX *Q = NULL;
564 ESL_DMATRIX *P = NULL;
565 double t = 5.0;
566 int esl_iterations = 100;
567 int i;
568 #ifdef HAVE_LIBGSL
569 gsl_matrix *Qg = NULL;
570 gsl_matrix *Pg = NULL;
571 int gsl_iterations = 100;
572 #endif
573
574 w = esl_stopwatch_Create();
575 Q = esl_dmatrix_Create(20, 20);
576 P = esl_dmatrix_Create(20, 20);
577 esl_rmx_SetWAG(Q, NULL);
578
579 esl_stopwatch_Start(w);
580 for (i = 0; i < esl_iterations; i++)
581 esl_dmx_Exp(Q, t, P);
582 esl_stopwatch_Stop(w);
583 printf("Easel takes: %g sec\n", w->user / (double) esl_iterations);
584
585 #ifdef HAVE_LIBGSL
586 if (esl_dmx_MorphGSL(Q, &Qg) != eslOK) esl_fatal("morph to gsl_matrix failed");
587 if ((Pg = gsl_matrix_alloc(20, 20)) == NULL) esl_fatal("gsl alloc failed");
588 gsl_matrix_scale(Qg, t);
589
590 esl_stopwatch_Start(w);
591 for (i = 0; i < gsl_iterations; i++)
592 gsl_linalg_exponential_ss(Qg, Pg, GSL_PREC_DOUBLE);
593 esl_stopwatch_Stop(w);
594 printf(" GSL takes: %g sec\n", w->user / (double) gsl_iterations);
595
596 gsl_matrix_free(Qg);
597 gsl_matrix_free(Pg);
598 #endif /*HAVE_LIBGSL*/
599
600 esl_dmatrix_Destroy(Q);
601 esl_dmatrix_Destroy(P);
602 esl_stopwatch_Destroy(w);
603 return 0;
604 }
605
606 #endif /*eslRATEMATRIX_BENCHMARK*/
607
608
609 /*****************************************************************
610 * 5. Regression test driver
611 *****************************************************************/
612 #ifdef eslRATEMATRIX_REGRESSION
613 #ifdef HAVE_LIBGSL
614
615 /* This tests rate matrix exponentiation against the GSL's
616 * undocumented implementation of a matrix exponential.
617 */
618 /*
619 gcc -g -Wall -I. -L. -o ratematrix_regression -DeslRATEMATRIX_REGRESSION -DHAVE_LIBGSL esl_dmatrix.c esl_ratematrix.c -leasel -lgsl -lgslcblas -lm
620 */
621
622 #include <esl_config.h>
623
624 #include <gsl/gsl_matrix.h>
625 #include <gsl/gsl_linalg.h>
626
627 #include "easel.h"
628 #include "esl_dmatrix.h"
629 #include "esl_ratematrix.h"
630
631 int
632 main(void)
633 {
634 char errbuf[eslERRBUFSIZE];
635 char *alphabet = "ACDEFGHIKLMNPQRSTVWY";
636 ESL_DMATRIX *Q = NULL;
637 ESL_DMATRIX *P = NULL;
638 gsl_matrix *Qg = NULL;
639 gsl_matrix *Pg = NULL;
640 ESL_DMATRIX *Pge = NULL;
641 double t = 15.0;
642
643 if ((Q = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
644 if ((P = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
645
646 if (esl_rmx_SetWAG(Q, NULL) != eslOK) esl_fatal("_SetWAG() failed");
647 if (esl_rmx_ValidateQ(Q, 0.0001, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
648
649 if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
650 if (esl_rmx_ValidateP(P, 0.0001, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
651
652 if (esl_dmx_MorphGSL(Q, &Qg) != eslOK) esl_fatal("morph to gsl_matrix failed");
653 if ((Pg = gsl_matrix_alloc(20, 20)) == NULL) esl_fatal("gsl alloc failed");
654 gsl_matrix_scale(Qg, t);
655 if (gsl_linalg_exponential_ss(Qg, Pg, GSL_PREC_DOUBLE) != 0) esl_fatal("gsl's exponentiation failed");
656 if (esl_dmx_UnmorphGSL(Pg, &Pge) != eslOK) esl_fatal("morph from gsl_matrix failed");
657
658 esl_dmatrix_Dump(stdout, P, alphabet, alphabet);
659
660 if (esl_dmatrix_Compare(Pge, P, 0.00001) != eslOK) esl_fatal("whoops, different answers.");
661
662 esl_dmatrix_Destroy(Q);
663 esl_dmatrix_Destroy(P);
664 esl_dmatrix_Destroy(Pge);
665 gsl_matrix_free(Qg);
666 gsl_matrix_free(Pg);
667 return 0;
668 }
669 #else
670 /* if we don't have GSL, then compile in a dummy main(), solely
671 * to quiet any tests that are verifying that all drivers compile
672 * and run. */
673 int main(void) { return 0; }
674 #endif /*HAVE_LIBGSL*/
675
676 #endif /*eslRATEMATRIX_REGRESSION*/
677
678
679 /*****************************************************************
680 * 6. Unit tests.
681 *****************************************************************/
682 #ifdef eslRATEMATRIX_TESTDRIVE
683
684 static void
685 utest_SetWAG(void)
686 {
687 char errbuf[eslERRBUFSIZE];
688 ESL_DMATRIX *Q = NULL;
689 ESL_DMATRIX *P = NULL;
690 double t = 50.0; /* sufficiently large to drive e^tQ to stationarity */
691 double pi[20];
692 int i;
693
694 if ((Q = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
695 if ((P = esl_dmatrix_Create(20, 20)) == NULL) esl_fatal("malloc failed");
696
697 /* This tests that exponentiating WAG gives a stable conditional
698 * probability matrix solution. (It doesn't particularly test that
699 * WAG was set correctly, but how could we have screwed that up?)
700 */
701 if (esl_rmx_SetWAG(Q, NULL) != eslOK) esl_fatal("_SetWAG() failed");
702 if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
703 if (esl_rmx_ValidateP(P, 1e-7, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
704 if (esl_rmx_ValidateQ(Q, 1e-7, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
705
706 /* This tests setting WAG to different stationary pi's than default,
707 * then tests that exponentiating to large t reaches those stationaries.
708 */
709 esl_vec_DSet(pi, 20, 0.05);
710 if (esl_rmx_SetWAG(Q, pi) != eslOK) esl_fatal("_SetWAG() failed");
711 if (esl_dmx_Exp(Q, t, P) != eslOK) esl_fatal("matrix exponentiation failed");
712 if (esl_rmx_ValidateP(P, 1e-7, errbuf) != eslOK) esl_fatal("P validation failed: %s", errbuf);
713 if (esl_rmx_ValidateQ(Q, 1e-7, errbuf) != eslOK) esl_fatal("Q validation failed: %s", errbuf);
714 for (i = 0; i < 20; i++)
715 if (esl_vec_DCompare(P->mx[i], pi, 20, 1e-7) != eslOK) esl_fatal("P didn't converge to right pi's");
716
717 esl_dmatrix_Destroy(Q);
718 esl_dmatrix_Destroy(P);
719 return;
720 }
721
722 #ifdef HAVE_LIBLAPACK
723 static void
724 utest_Diagonalization(void)
725 {
726 ESL_DMATRIX *P = NULL;
727 ESL_DMATRIX *P2 = NULL;
728 ESL_DMATRIX *C = NULL;
729 ESL_DMATRIX *D = NULL;
730 double *lambda = NULL; /* eigenvalues */
731 ESL_DMATRIX *U = NULL; /* left eigenvectors */
732 ESL_DMATRIX *Ui = NULL; /* inverse of U */
733 int i,j;
734
735 /* Create a J/C probability matrix for t=1:
736 * 1/4 + 3/4 e^{-4/3 at}
737 * 1/4 - 1/4 e^{-4/3 at}
738 */
739 if ((P = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
740 if ((C = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
741 if ((Ui = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
742 if ((D = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
743 if ((P2 = esl_dmatrix_Create(4, 4)) == NULL) esl_fatal("malloc failed");
744 for (i = 0; i < 4; i++)
745 for (j = 0; j < 4; j++)
746 if (i == j) P->mx[i][j] = 0.25 + 0.75 * exp(-4./3.);
747 else P->mx[i][j] = 0.25 - 0.25 * exp(-4./3.);
748
749 /* Diagonalize it
750 */
751 if (esl_dmx_Diagonalize(P, &lambda, NULL, &U, NULL) != eslOK) esl_fatal("diagonalization failed");
752
753 /* Calculate P^k by U [diag(lambda_i)]^k U^{-1}
754 */
755 esl_dmatrix_SetZero(D);
756 for (i = 0; i < P->n; i++) D->mx[i][i] = lambda[i];
757 esl_dmx_Invert(U, Ui);
758 esl_dmx_Multiply(U, D, C);
759 esl_dmx_Multiply(C, Ui, P2);
760
761 if (esl_dmatrix_Compare(P, P2, 1e-7) != eslOK) esl_fatal("diagonalization unit test failed");
762
763 free(lambda);
764 esl_dmatrix_Destroy(P2);
765 esl_dmatrix_Destroy(Ui);
766 esl_dmatrix_Destroy(U);
767 esl_dmatrix_Destroy(D);
768 esl_dmatrix_Destroy(C);
769 esl_dmatrix_Destroy(P);
770 return;
771 }
772 #endif /*HAVE_LIBLAPACK*/
773
774 #endif /*eslRATEMATRIX_TESTDRIVE*/
775
776 /*****************************************************************
777 * 7. Test driver
778 *****************************************************************/
779
780 #ifdef eslRATEMATRIX_TESTDRIVE
781 /* gcc -g -Wall -o test -I. -L. -DeslRATEMATRIX_TESTDRIVE esl_ratematrix.c -leasel -lm
782 * ./test
783 *
784 * gcc -g -Wall -o test -I. -L. -DHAVE_LIBLAPACK -DeslRATEMATRIX_TESTDRIVE esl_ratematrix.c esl_dmatrix.c -leasel -llapack -lm
785 */
786 #include <esl_config.h>
787
788 #include "easel.h"
789 #include "esl_ratematrix.h"
790
791 int
792 main(void)
793 {
794 utest_SetWAG();
795 #ifdef HAVE_LIBLAPACK
796 utest_Diagonalization();
797 #endif
798
799 return 0;
800
801 }
802 #endif /*eslRATEMATRIX_TESTDRIVE*/
803