]> git.donarmstrong.com Git - ape.git/blob - src/mat_expo.c
cleaning of C files and update on simulation of OU process
[ape.git] / src / mat_expo.c
1 /* matexpo.c       2011-06-23 */
2
3 /* Copyright 2007-2011 Emmanuel Paradis
4
5 /* This file is part of the R-package `ape'. */
6 /* See the file ../COPYING for licensing issues. */
7
8 #include <R.h>
9 #include <R_ext/Lapack.h>
10
11 void mat_expo(double *P, int *nr)
12 /* This function computes the exponential of a nr x nr matrix */
13 {
14         double *U, *vl, *WR, *Uinv, *WI, *work;
15         int i, j, k, l, info, *ipiv, n = *nr, nc = n*n, lw = nc << 1;
16         char yes = 'V', no = 'N';
17
18         U = (double *)R_alloc(nc, sizeof(double));
19         vl = (double *)R_alloc(n, sizeof(double));
20         WR = (double *)R_alloc(n, sizeof(double));
21         Uinv = (double *)R_alloc(nc, sizeof(double));
22         WI = (double *)R_alloc(n, sizeof(double));
23         work = (double *)R_alloc(lw, sizeof(double));
24
25         ipiv = (int *)R_alloc(nc, sizeof(int));
26
27 /* The matrix is not symmetric, so we use 'dgeev'.
28    We take the real part of the eigenvalues -> WR
29    and the right eigenvectors (vr) -> U */
30         F77_CALL(dgeev)(&no, &yes, &n, P, &n, WR, WI, vl, &n,
31                         U, &n, work, &lw, &info);
32
33 /* It is not necessary to sort the eigenvalues...
34    Copy U -> P */
35         memcpy(P, U, nc*sizeof(double));
36
37 /* For the inversion, we first make Uinv an identity matrix */
38         memset(Uinv, 0, nc*sizeof(double));
39         for (i = 0; i < nc; i += n + 1) Uinv[i] = 1;
40
41 /* The matrix is not symmetric, so we use 'dgesv'.
42    This subroutine puts the result in Uinv (B)
43    (P [= U] is erased) */
44         F77_CALL(dgesv)(&n, &n, P, &n, ipiv, Uinv, &n, &info);
45
46 /* The matrix product of U with the eigenvalues diagonal matrix: */
47         for (i = 0; i < n; i++)
48                 for (j = 0; j < n; j++)
49                         U[j + i*n] *= exp(WR[i]);
50
51 /* The second matrix product with U^-1 */
52         memset(P, 0, nc*sizeof(double));
53
54         for (k = 0; k < n; k++) {
55                 for (l = 0; l < n; l++) {
56                         lw = l + k*n;
57                         for (i = 0 + n*k, j = l; j < nc; i++, j += n)
58                                 P[lw] += U[j]*Uinv[i];
59                 }
60         }
61 }