发布者:
发布日期:2009年9月17日(最后更新:2009年9月21日)

C++ LAPACK

评分:4.1/5 (18 票)
*****
以下是一个使用 LAPACK 与 C++ 的框架。

有关更多信息,请查看 LAPACK 论坛
http://icl.cs.utk.edu/lapack-forum/
以及 netlib 存储库
http://www.netlib.org/clapack/
在上述网站上有 CLAPACK 和 BLAS 的编译/安装详细信息。

测试程序(可执行文件 'fmat')的编译命令
1
2
3
4
CLAPACKPATH = path to clapack
g++  Fmatrix_test.cpp -I$(CLAPACKPATH)/SRC -I$(CLAPACKPATH) -c
g++  Fmatrix_test.o -o fmat $(CLAPACKPATH)/lapack_LINUX.a $(CLAPACKPATH)/blas_LINUX.a $(CLAPACKPATH)/F2CLIBS/libf2c.a -lm

Matrix 类:这只是一个容器 - 全部是 C++
我们使用模板来存储 LAPACK 允许的不同数据类型。

矩阵“数据”(mat 成员)是一个一维数组,必须这样,以便 FORTRAN 可以使用它。
这意味着我们必须跟踪矩阵中的位置。 A<i>[j]A[ j*m+i ] 给出,其中 m 是行数。

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
#ifndef _FMATRIX_H
#define _FMATRIX_H

#include<iostream>

template <class T>
class Fmatrix
{
public:
    //default
    Fmatrix(): m(0), n(0), flag(0), mat(new T[0]){ this->settype(); }
    //blank
    Fmatrix(size_t _m): m(_m), n(1), flag(0), mat(new T[_m]){ this->settype(); }
    Fmatrix(size_t _m, size_t _n): m(_m), n(_n), flag(0), mat(new T[_m*_n])
    { this->settype(); }
    //copy
    Fmatrix(const Fmatrix<T>& B) :
    m(B.numrows()), n(B.numcols()), mat(new T[B.numelms()])
    {
        for(size_t i=0; i<B.numelms(); i++){ this->mat<i> = B<i>; }
        this->type=B.gettype();
    }

    ~Fmatrix(){ if(mat) delete[] mat; }

    inline T& operator() (size_t i, size_t j)
    { return this->mat[j*(this->m)+i]; }
    inline T  operator() (size_t i, size_t j) const
    { return this->mat[j*(this->m)+i]; }

    inline T& operator[] (size_t i)       { return mat<i>; }
    inline T  operator[] (size_t i) const { return mat<i>; }

    Fmatrix operator = (const Fmatrix<T>& B)
    {
        if(&B!=this){
            delete[] mat;
            this->m=B.numrows();
            this->n=B.numcols();
            this->flag=B.error();
            mat=new T[(this->m)*(this->n)];
            for(size_t i=0; i<B.numelms(); i++){ this->mat<i> = B<i>;}
        }
        return *this;
    }
    //these (+-*/) won't work for complex
    Fmatrix operator += (const Fmatrix<T>& B)
    {  for(size_t i=0; i< this->numelms(); i++){ this->mat<i>+=B<i>; }  }
    Fmatrix operator -= (const Fmatrix<T>& B)
    {  for(size_t i=0; i< this->numelms(); i++){ this->mat<i>-=B<i>; }  }
    Fmatrix operator *= (const T alpha)
    {  for(size_t i=0; i< this->numelms(); i++){ this->mat<i>*=alpha; }  }
    Fmatrix operator /= (const T beta)
    {  for(size_t i=0; i< this->numelms(); i++){ this->mat<i>/=beta; }  }

    inline T* begin(){ return mat; }

    inline const size_t numrows() const { return this->m; }
    inline const size_t numcols() const { return this->n; }
    inline const size_t numelms() const { return (this->m)*(this->n); }
    inline const bool   error()   const { return this->flag; }
    inline const char   gettype() const { return this->type; }
    
    void print(std::ostream &os=std::cout, char delim='\t')
    {
        for(size_t i=0;i<this->m;i++){for(size_t j=0;j<this->n;j++){
            os << (*this)(i,j) << delim;
        } os << std::endl; } os << std::endl;
    }
    
    void read(std::istream &is=std::cin)
    {
        for(size_t i=0;i<this->m;i++){for(size_t j=0;j<this->n;j++){
            is >> (*this)(i,j);
        } }
    }

private:
    size_t m,n;
    T *mat;
    char type;
    bool flag;

    inline const char settype()
    {
        char tstr[20], otyp[]="czu";
        strcpy(tstr,typeid(T).name());
        if(tstr[0]=='f'||tstr[0]=='d'||tstr[0]=='e') type=tstr[0];
        else if( strcmp(tstr,"7complex")==0 )        type=otyp[0];
        else if( strcmp(tstr,"13doublecomplex")==0 ) type=otyp[1];
        else                                         type=otyp[2];
    }
};

#endif /* _FMATRIX_H */


线性代数模块:这与 CLAPACK 挂钩
注意包含项的 extern,它们是用 C 编写的。
这里的大多数函数都调用 LAPACK 函数,我会根据需要添加功能(LAPACK 非常庞大)。
要向 LAPACK 添加新的函数调用,您需要在 netlib 或其他地方查找该函数,以确定需要传递的内容。
要传递矩阵数据,请使用 myMatrix.begin()
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
#ifndef _LINALG_H
#define _LINALG_H

#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <iostream>
#include <fstream>

extern "C" {
    #include "f2c.h"
    #include "blaswrap.h"
    #include "clapack.h"
}

#include "Fmatrix.h"

//these scalar ops (+-*/) won't work for complex
template <class T>
const Fmatrix<T> operator + (const Fmatrix<T>& A, const Fmatrix<T>& B)
{  return Fmatrix<T>(A)+=B;  }
template <class T>
const Fmatrix<T> operator - (const Fmatrix<T>& A, const Fmatrix<T>& B)
{  return Fmatrix<T>(A)+=B;  }
template <class T>
const Fmatrix<T> operator * (const T alpha, const Fmatrix<T>& A)
{  return Fmatrix<T>(A)*=alpha;  }
template <class T>
const Fmatrix<T> operator / (const Fmatrix<T>& A, const T beta)
{  return Fmatrix<T>(A)/=beta;  }
template <class T>
const Fvector<T> operator * ( Fmatrix<T>& A, Fvector<T>& x)
{
    Fvector<T> y(A.numrows());
    gmv(A,x,y);
    return y;
}
template <class T>
const Fmatrix<T> operator * ( Fmatrix<T>& A, Fmatrix<T>& B)
{
    Fmatrix<T> C(A.numrows(),B.numcols());
    gmm(A,B,C);
    return C;
}

template <class T>
int gmv(Fmatrix<T>& A, Fvector<T>& x, Fvector<T>& y, char TRANSA='N',
            T alpha=1, T beta=0, integer INCX=1, integer INCY=1)
{
    integer M, N, LDA;

    M=(TRANSA=='N') ? A.numrows():A.numcols();
    N=(TRANSA=='N') ? A.numcols():A.numrows();
    LDA=M;

    //this still needs a switch on data type
    dgemv_(&TRANSA, &M, &N,
                        (doublereal*)&alpha,
                        (doublereal*)A.begin(), &LDA,
                        (doublereal*)x.begin(), &INCX,
                        (doublereal*)&beta,
                        (doublereal*)y.begin(), &INCY);


}


template <class T>
int gmm(Fmatrix<T>& A, Fmatrix<T>& B, Fmatrix<T>& C,
            char TRANSA='N', char TRANSB='N', T alpha=1, T beta=0)
{
    integer M, N, K, LDA, LDB, LDC;

    M=(TRANSA=='N') ? A.numrows():A.numcols();
    N=(TRANSB=='N') ? B.numcols():B.numrows();
    K=(TRANSA=='N') ? A.numcols():A.numrows();
    LDA=(TRANSA=='N') ? M:K;
    LDB=(TRANSB=='N') ? K:N;
    LDC=C.numrows();

    switch(A.gettype()){//cast explicitly otherwise compiler is cranky
        case 'f':
            sgemm_(&TRANSA, &TRANSB, &M, &N, &K,
                        (real*)&alpha,
                        (real*)A.begin(), &LDA,
                        (real*)B.begin(), &LDB,
                        (real*)&beta,
                        (real*)C.begin(), &LDC);
        break;
        case 'd':
            dgemm_(&TRANSA, &TRANSB, &M, &N, &K,
                        (doublereal*)&alpha,
                        (doublereal*)A.begin(), &LDA,
                        (doublereal*)B.begin(), &LDB,
                        (doublereal*)&beta,
                        (doublereal*)C.begin(), &LDC);
        break;
        case 'c':
            cgemm_(&TRANSA, &TRANSB, &M, &N, &K,
                        (complex*)&alpha,
                        (complex*)A.begin(), &LDA,
                        (complex*)B.begin(), &LDB,
                        (complex*)&beta,
                        (complex*)C.begin(), &LDC);
        break;
        case 'z':
            zgemm_(&TRANSA, &TRANSB, &M, &N, &K,
                        (doublecomplex*)&alpha,
                        (doublecomplex*)A.begin(), &LDA,
                        (doublecomplex*)B.begin(), &LDB,
                        (doublecomplex*)&beta,
                        (doublecomplex*)C.begin(), &LDC);
        break;
        default:
            std::cout << "\nERROR: Something wrong in GMM switch.\n\n";
    }
    return 0;
}

template <class T>
int pca(Fmatrix<T>& A, Fmatrix<T>& U, Fmatrix<T>& S, Fmatrix<T>& PC)
{
   std::ofstream PCoutx("pcx"), PCouty("pcy"), PCoutz("pcz"), PCoutw("pcw");
        PCoutx.precision(16); PCouty.precision(16);
        PCoutz.precision(16); PCoutw.precision(16);
        Fmatrix<T> Y(A.numcols(),A.numrows());
        T s,*mean;

        mean = new T[A.numrows()];
        for(int i=0; i<A.numrows(); i++) mean<i>=0;

        //find means
        for(int i=0; i<A.numrows(); i++){ for(int j=0; j<A.numcols(); j++){
            mean<i>+=A(i,j);
        } }
        for(int i=0; i<A.numrows(); i++) mean<i>/=A.numcols();

        //subtract means from data
        for(int i=0; i<A.numrows(); i++){ for(int j=0; j<A.numcols(); j++){
            A(i,j)-=mean<i>;
        } }

        //form matrix for SVD
        s=sqrt(A.numcols()-1);
        for(int i=0; i<A.numrows(); i++){ for(int j=0; j<A.numcols(); j++){
            Y(j,i)=A(i,j)/s;
        } }

        return svd(Y,U,S,PC);
}

template <class T>
int svd(Fmatrix<T>& A, Fmatrix<T>& U, Fmatrix<T>& S, Fmatrix<T>& V,
            char JOBU='A', char JOBVT='A')
{
    float  *wkf,*rwkc;
    double *wkd,*rwkz;
    complex *wkc;
    doublecomplex *wkz;
    integer M, N, mn, MN, LDA, LDU, LDVT, LWORK, INFO;

    M=A.numrows(); N=A.numcols(); LDA=M; LDU=M; LDVT=N;
    mn=min(M,N);
    MN=max(M,N);
    LWORK=2*max(3*mn+MN,5*mn);

    switch(A.gettype()){//cast explicitly otherwise compiler is cranky
        case 'f':
            wkf = new real[LWORK];
            sgesvd_(&JOBU, &JOBVT, &M, &N,
                        (real*)A.begin(), &LDA,
                        (real*)S.begin(),
                        (real*)U.begin(), &LDU,
                        (real*)V.begin(), &LDVT,
                        wkf, &LWORK, &INFO);
            delete[] wkf;
        break;
        case 'd':
            wkd = new doublereal[LWORK];
            dgesvd_(&JOBU, &JOBVT, &M, &N,
                        (doublereal*)A.begin(), &LDA,
                        (doublereal*)S.begin(),
                        (doublereal*)U.begin(), &LDU,
                        (doublereal*)V.begin(), &LDVT,
                        wkd, &LWORK, &INFO);
            delete[] wkd;
        break;
        case 'c':
            wkc = new complex[LWORK];
            rwkc = new real[5*mn];
            cgesvd_(&JOBU, &JOBVT, &M, &N,
                        (complex*)A.begin(), &LDA,
                        (real*)S.begin(),
                        (complex*)U.begin(), &LDU,
                        (complex*)V.begin(), &LDVT,
                        wkc, &LWORK, rwkc, &INFO);
            delete[] wkc; delete[] rwkc;
        break;
        case 'z':
            wkz = new doublecomplex[LWORK];
            rwkz = new doublereal[5*mn];
            zgesvd_(&JOBU, &JOBVT, &M, &N,
                        (doublecomplex*)A.begin(), &LDA,
                        (doublereal*)S.begin(),
                        (doublecomplex*)U.begin(), &LDU,
                        (doublecomplex*)V.begin(), &LDVT,
                        wkz, &LWORK, rwkz, &INFO);
            delete[] wkz; delete[] rwkz;
        break;
        default:
            std::cout << "\nERROR: Something wrong in SVD switch.\n\n";
    }

    return INFO;
}

#endif /* _LINALG_H */

Fmatrix_test.cpp:显示一些功能

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
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <iostream>

#include "Flinalg.h"

using namespace std;

int main(int argc, char** argv)
{
    cout.precision(2);
    size_t M,N;

    cout << "input numrows: ";
    cin >> M;
    cout << "input numcols: ";
    cin >> N;
    Fmatrix<double> A(M,N); //instantiate MxN matrix
    Fmatrix<double> v(N),u(M); //instantiate Mx1 matrix i.e. vector
    cout << "A is " <<  A.numrows() << 'x' << A.numcols() << ", numelms: " << A.numelms() << endl;
    cout << "v is " <<  v.numrows() << 'x' << v.numcols() << ", numelms: " << v.numelms() << endl;
    cout << "u is " <<  u.numrows() << 'x' << u.numcols() << ", numelms: " << u.numelms() << endl << endl;

    cout << "Input data for matrix A by rows (" << A.numelms() << " numbers):" << endl;
    A.read();
    cout << endl << "A =" << endl;
    A.print();
    
    //Matrix-vector multiply by operator overload
    cout << endl << "Setting v to ones vector..." << endl;
    for(int i=0;i<v.numelms();i++)
        v<i>=1;
    cout << "A*v =" << endl;
    u=A*v;
    u.print();
    
    //generic matrix-matrix multiply
    Fmatrix<double> C(A.numrows(),A.numrows());
    gmm(A,A,C,'N','T');
    cout << "A*A' =" << endl; 
    C.print();
    
    cout << "computing svd..." << endl;
    Fmatrix<double> U(M,M),S(min(M,N)),V(N,N); //min is defined in clapack.h
    cout << "INFO: " << svd(A,U,S,V) << endl; //do svd, output error code
    cout << "singular values:" << endl;
    for (size_t i=0; i < min(M,N); i++)
    { cout << "S[ " << i+1 << " ]\t= " << S<i> << endl; } cout << endl;
    cout << "singular vectors:" << endl;     //rows of V so print transpose
    for(int i=0; i<V.numrows(); i++){ cout << "v" << i+1 <<'\t'; } cout << endl;
    for(int i=0; i<V.numrows(); i++){ for(size_t j=0;j<V.numcols();j++){
        cout << V(j,i) << '\t';
    } cout << endl; }

    return 0;
}


示例运行(输入为粗体)

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
input numrows: <b>6</b>
input numcols: <b>5</b>
A is 6x5, numelms: 30
v is 5x1, numelms: 5
u is 6x1, numelms: 6

Input data for matrix A by rows (30 numbers):
<b>2 5 2 6 4
3 3.4 2 6 7
2 2 2 2 0
0 0 0 1.234 0
3 23 46 93 .001
1 2 3 4 5</b>

A =
2       5       2       6       4
3       3.4     2       6       7
2       2       2       2       0
0       0       0       1.2     0
3       23      46      93      0.001
1       2       3       4       5


Setting v to ones vector...
A*v =
19
21
8
1.2
1.7e+02
15



A*A' =
85      91      30      7.4     7.7e+02 62
91      1.1e+02 29      7.4     7.4e+02 75
30      29      16      2.5     3.3e+02 20
7.4     7.4     2.5     1.5     1.1e+02 4.9
7.7e+02 7.4e+02 3.3e+02 1.1e+02 1.1e+04 5.6e+02
62      75      20      4.9     5.6e+02 55

computing svd...
INFO: 0
singular values:
S[ 1 ]  = 1.1e+02
S[ 2 ]  = 11
S[ 3 ]  = 2.9
S[ 4 ]  = 1.9
S[ 5 ]  = 1.2

singular vectors:
v1      v2      v3      v4      v5
-0.032  -0.33   0.48    -0.35   -0.74
-0.22   -0.34   0.72    0.16    0.54
-0.43   0.088   -0.12   -0.84   0.29
-0.87   0.062   -0.13   0.39    -0.26
-0.0092 -0.88   -0.47   0.0089  0.079

 

它将求解方程组。是的,但是设置单变量单方程系统所需的工作量等同于求解它。

例如
要让它解决
4x+2=54-7x+3
您需要告诉它 11x=55

这简直是浪费时间(为 lapack 制定输入)。

但是像这样
1
2
3
12x +14y - 8z = 2
14x - 5y +  z = 4
  x +  y +  z = 4

才值得。
您还可以(某种程度上)求解欠定系统(变量多于方程的系统)。

你需要一个计算机代数系统 (CAS)。 Maple 在符号操作方面非常好(但价格昂贵)。 Octave/Matlab 也可以做到。 Octave 和 Matlab 实际上都使用 LAPACK