-
Notifications
You must be signed in to change notification settings - Fork 4
/
systemsolver.cpp
85 lines (74 loc) · 1.86 KB
/
systemsolver.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
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
#include "systemsolver.h"
#include <iostream>
#include <eigen/eigen/Eigen/Dense>
extern "C"
{
#include "tdavis/csparse/cs.h"
}
using namespace Eigen;
vector<double> SystemSolver::SolveSparse(vector<double> valuesB)
{
//THe matrix A
vector<double> values;
vector<int> rows;
vector<int> nums;
int num=0;
for(sparseMatrix::const_iterator it=matrix.begin();it!=matrix.end();it++)
{
const sparseCol& col=it->second;
for(sparseCol::const_iterator it2=col.begin();it2!=col.end();it2++)
{
values.push_back(it2->second);
rows.push_back(it2->first);
}
nums.push_back(num);
num+=col.size();
}
nums.push_back(num);
cs_sparse A;
int nnz=values.size();
A.nzmax=nnz;
A.m=num_row;
A.n=num_col;
A.x=new double[nnz];
A.nz=-1;//column-compressed (not triplet)
A.p =new ptrdiff_t[num_col+1]; /// column pointers (size n+1) or col indices (size nzmax)
A.i=new ptrdiff_t[nnz] ; /* row indices, size nzmax */
unsigned int i;
for(i=0;i<nnz;i++)
{
A.x[i]=values[i];
A.i[i]=rows[i];
}
for(i=0;i<nums.size();i++)
{
A.p[i]=nums[i];
}
double* b=new double [valuesB.size()];
memcpy(b,&valuesB[0],sizeof(double)*valuesB.size());
cs_cholsol(1,&A,b);
std::vector<double> ret(valuesB.size());
memcpy(&ret[0],b,sizeof(double)*valuesB.size());
return ret;
}
vector<double> SystemSolver::SolveDense(vector<double> valuesB)
{
int size=max(num_col,num_row);
MatrixXd A=MatrixXd::Zero(size,size);
for(sparseMatrix::const_iterator it=matrix.begin();it!=matrix.end();it++)
{
const sparseCol& col=it->second;
for(sparseCol::const_iterator it2=col.begin();it2!=col.end();it2++)
{
A(it->first,it2->first)=it2->second;
}
}
VectorXd b(valuesB.size());
for(int i=0;i<valuesB.size();i++)
b(i)=valuesB[i];
VectorXd sol=A.colPivHouseholderQr().solve(b);
vector<double> ret(valuesB.size());
for(int i=0;i<ret.size();i++)
ret[i]=sol(i);
return ret;
}