File: eigen_gsl.c

package info (click to toggle)
theseus 3.3.0-14
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 91,424 kB
  • sloc: ansic: 41,682; makefile: 267; sh: 121
file content (327 lines) | stat: -rw-r--r-- 9,767 bytes parent folder | download | duplicates (5)
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
/*
    Theseus - maximum likelihood superpositioning of macromolecular structures

    Copyright (C) 2004-2015 Douglas L. Theobald

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the:

    Free Software Foundation, Inc.,
    59 Temple Place, Suite 330,
    Boston, MA  02111-1307  USA

    -/_|:|_|_\-
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_linalg.h>
#include <gsl/gsl_sort.h>
#include <gsl/gsl_sort_vector.h>
#include "DLTmath.h"


/*
Calculate eigenvalues of a square, symmetric, real matrix, using GSL.
Eigenvalues are returned in ascending order, smallest first.
Pointer *eval must be allocated.
Input matrix **cov is NOT perturbed.
*/
void
EigenvalsGSL(const double **mat, const int dim, double *eval)
{
    double        *mat_cpy = NULL;

    mat_cpy = malloc(dim * dim * sizeof(double));
    memcpy(mat_cpy, &mat[0][0], dim * dim * sizeof(double));
    gsl_matrix_view m = gsl_matrix_view_array(mat_cpy, dim, dim);
    gsl_vector_view evalv = gsl_vector_view_array(eval, dim);
    gsl_eigen_symm_workspace *w = gsl_eigen_symm_alloc(dim);

    gsl_eigen_symm(&m.matrix, &evalv.vector, w);
    gsl_sort_vector(&evalv.vector);

    gsl_eigen_symm_free(w);
    free(mat_cpy);
}


/* This one destroys half of the input matrix **mat */
void
EigenvalsGSLDest(double **mat, const int dim, double *eval)
{
    gsl_matrix_view m = gsl_matrix_view_array(mat[0], dim, dim);
    gsl_vector_view evalv = gsl_vector_view_array(eval, dim);
    gsl_eigen_symm_workspace *w = gsl_eigen_symm_alloc(dim);
    gsl_eigen_symm(&m.matrix, &evalv.vector, w);
    gsl_eigen_symm_free(w);
}


/*
gsl_eigen_symmv()

This function computes the eigenvalues and eigenvectors of the real
symmetric matrix A. Additional workspace of the appropriate size must be
provided in w. The diagonal and lower triangular part of A are destroyed
during the computation, but the strict upper triangular part is not
referenced. The eigenvalues are stored in the vector eval and are
unordered. The corresponding eigenvectors are stored in the columns of
the matrix evec. For example, the eigenvector in the first column
corresponds to the first eigenvalue. The eigenvectors are guaranteed to
be mutually orthogonal and normalised to unit magnitude.
*/
void
EigenGSL(const double **mat, const int dim, double *eval, double **evec, int order)
{
    double        *mat_cpy = NULL;

    mat_cpy = malloc(dim * dim * sizeof(double));
    memcpy(mat_cpy, &mat[0][0], dim * dim * sizeof(double));
    gsl_matrix_view m = gsl_matrix_view_array(mat_cpy, dim, dim);
    gsl_matrix_view v = gsl_matrix_view_array(evec[0], dim, dim);
    gsl_vector_view evalv = gsl_vector_view_array(eval, dim);
    gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(dim);

    gsl_eigen_symmv(&m.matrix, &evalv.vector, &v.matrix, w);

    if (order == 0)
        gsl_eigen_symmv_sort(&evalv.vector, &v.matrix, GSL_EIGEN_SORT_VAL_ASC);
    else if (order == 1)
        gsl_eigen_symmv_sort(&evalv.vector, &v.matrix, GSL_EIGEN_SORT_VAL_DESC);

    gsl_eigen_symmv_free(w);
    free(mat_cpy);
}


/* This one destroys half of the input matrix **mat */
void
EigenGSLDest(double **mat, const int dim, double *eval, double **evec, int order)
{
    gsl_matrix_view m = gsl_matrix_view_array(mat[0], dim, dim);
    gsl_matrix_view v = gsl_matrix_view_array(evec[0], dim, dim);
    gsl_vector_view evalv = gsl_vector_view_array(eval, dim);
    gsl_eigen_symmv_workspace *w = gsl_eigen_symmv_alloc(dim);
    gsl_eigen_symmv(&m.matrix, &evalv.vector, &v.matrix, w);

    if (order == 0)
        gsl_eigen_symmv_sort(&evalv.vector, &v.matrix, GSL_EIGEN_SORT_VAL_ASC);
    else if (order == 1)
        gsl_eigen_symmv_sort(&evalv.vector, &v.matrix, GSL_EIGEN_SORT_VAL_DESC);

    gsl_eigen_symmv_free(w);
}


void
CalcGSLSVD3(double **a, double **u, double *s, double **vt)
{
    memcpy(u[0], a[0], 9 * sizeof(double));
    // GSL says Jacobi SVD is more accurate the Golub
    svdGSLJacobiDest(u, 3, s, vt);
    Mat3TransposeIp(vt);
}


void
svdGSLDest(double **A, const int dim, double *singval, double **V)
{
    gsl_matrix_view a = gsl_matrix_view_array(A[0], dim, dim);
    gsl_matrix_view v = gsl_matrix_view_array(V[0], dim, dim);
    gsl_vector_view singv = gsl_vector_view_array(singval, dim);
    gsl_vector *work = gsl_vector_alloc(dim);

    gsl_linalg_SV_decomp(&a.matrix, &v.matrix, &singv.vector, work);

    gsl_vector_free(work);
}


void
svdGSLJacobiDest(double **A, const int dim, double *singval, double **V)
{
    gsl_matrix_view a = gsl_matrix_view_array(A[0], dim, dim);
    gsl_matrix_view v = gsl_matrix_view_array(V[0], dim, dim);
    gsl_vector_view singv = gsl_vector_view_array(singval, dim);

    gsl_linalg_SV_decomp_jacobi(&a.matrix, &v.matrix, &singv.vector);
}


void
CholeskyGSLDest(double **A, const int dim)
{
    gsl_matrix_view a = gsl_matrix_view_array(A[0], dim, dim);
    gsl_linalg_cholesky_decomp(&a.matrix);
}


/* static void */
/* write_C_mat(const double **mat, const int dim, int precision, int wrap) */
/* { */
/*     int i, j; */
/*  */
/*     if (wrap == 0) */
/*         wrap = 5; */
/*  */
/*     if (precision == 0) */
/*         precision = 6; */
/*  */
/*     printf("\n\nstatic double mat[%d][%d] = \n{\n", dim, dim); */
/*  */
/*     for (i = 0; i < dim; ++i) */
/*     { */
/*         printf("    {"); */
/*         for (j = 0; j < dim; ++j) */
/*         { */
/*             if (j < dim - 1) */
/*                 printf("% *.*f, ", precision + 1, precision, mat[i][j]); */
/*             else */
/*                 printf("% *.*f", precision + 1, precision, mat[i][j]); */
/*  */
/*             if ((j+1) % wrap == 0 && j != dim - 1) */
/*                 printf("     \n"); */
/*         } */
/*  */
/*         if (i != dim - 1) */
/*             printf("},\n"); */
/*         else */
/*             printf("}\n"); */
/*     } */
/*     printf("};\n\n"); */
/*     fflush(NULL); */
/* } */


/* Calculates the Moore-Penrose pseudoinverse of a symmetric, square matrix.
   Uses GSL to do the singular value decomposition inmat = U S V^T .
   Then constructs the pseudoinverse by V S^-1 U^T .
   Note that here S^-1 is the inverse of only the nonzero elements of S.
   Also note that GSL returns V and not V^T (unlike LAPACK), so we have
   to account for that in the matrix multiplication, since U & V are
   asymmetric in general. */
void
PseudoinvSymGSL(const double **inmat, double **outmat, int n, double tol)
{
    double        **u = MatAlloc(n, n);
    double        **v = MatAlloc(n, n);
    double         *s = malloc(n * sizeof(double));
    int             i, j, k;

    memcpy(u[0], inmat[0], n * n * sizeof(double));

    svdGSLDest(u, n, s, v);

/*     write_C_mat((const double **) u, n, 5, 10); */
/*     write_C_mat((const double **) v, n, 5, 10); */

    for (i = 0; i < n; ++i)
    {
        if (s[i] > tol)
            s[i] = 1.0 / s[i];
        else
            s[i] = 0.0;
    }

    memset(outmat[0], 0, n*n*sizeof(double));

//     for (i = 0; i < n; ++i)
//         for (j = 0; j < n; ++j)
//             outmat[i][j] = 0.0;

    /* (i x k)(k x j) = (i x j) */
    for (i = 0; i < n; ++i)
        for (j = 0; j < n; ++j)
            for (k = 0; k < n; ++k)
                outmat[i][j] += (v[i][k] * s[k] * u[j][k]);

/*     write_C_mat((const double **) outmat, n, 5, 10); */

    free(s);
    MatDestroy(&u);
    MatDestroy(&v);
}




/* Calculates the Moore-Penrose pseudoinverse of a symmetric matrix
   (if necessary). Returns the condition number of the matrix.
   */
double
InvSymEigenOp(double **invmat, const double **mat, int n,
              double *evals, double **evecs, const double tol)
{
    double                   cond;
    int                      i, j, k;
    double                 **tmpmat = MatAlloc(n, n);

    memcpy(tmpmat[0], mat[0], n * n * sizeof(double));

    EigenGSLDest(tmpmat, n, evals, evecs, 0);

    cond = evals[n-1] / evals[0];

    for (i = 0; i < n; ++i)
    {
        if (evals[i] > tol)
            evals[i] = 1.0 / evals[i];
        else
            evals[i] = 0.0;
    }

    memset(invmat[0], 0, n * n * sizeof(double));

    for (i = 0; i < n; ++i)
        for (j = 0; j <= i; ++j)
            for (k = 0; k < n; ++k)
                invmat[i][j] += (evecs[i][k] * evals[k] * evecs[j][k]);

    for (i = 0; i < n; ++i)
        for (j = i + 1; j < n; ++j)
            invmat[i][j] = invmat[j][i];

    MatDestroy(&tmpmat);

    return(cond);
}


/* Calculates A = LDL^t, where L is a matrix of right eigenvectors and D is
   a diagonal matrix of eigenvalues, in one fell swoop. Except here the
   eigenvalues are delivered as a 1 x n vector. */
/* This function is consistent with eigensym() above - 2006-05-10 */
void
EigenReconSym(double **mat, const double **evecs, const double *evals, const int n)
{
    int             i, j, k;

    /* (i x k)(k x j) = (i x j) */
    for (i = 0; i < n; ++i)
    {
        for (j = 0; j < n; ++j)
        {
            mat[i][j] = 0.0;
            for (k = 0; k < n; ++k)
                mat[i][j] += (evecs[i][k] * evals[k] * evecs[j][k]);
        }
    }
}