Created
July 14, 2021 11:56
-
-
Save linuxaged/4b1be7db1e9668c1721591179ac92add to your computer and use it in GitHub Desktop.
SparseLU
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "eigen/Eigen/Dense" | |
#include "eigen/Eigen/SparseLU" | |
#include "eigen/Eigen/IterativeLinearSolvers" | |
#include <iostream> | |
#include <fstream> | |
using namespace Eigen; | |
int main() { | |
std::vector<Eigen::Triplet<double>> tripletList; | |
std::ifstream ifs("triplets.txt"); | |
int vertNum; | |
ifs >> vertNum; | |
while (ifs) { | |
int col, row; | |
double value; | |
ifs >> col >> row >> value; | |
if (ifs) { | |
tripletList.emplace_back(col, row, value); | |
} | |
} | |
// fill matrix A(n*n) | |
SparseMatrix<double, ColMajor> A; | |
A.resize(vertNum, vertNum); | |
A.setZero(); | |
A.setFromTriplets(tripletList.begin(), tripletList.end()); | |
// compress sparse matrix(necessary) | |
A.makeCompressed(); | |
// fill right hand side matrix B(n*3) | |
MatrixXd X(vertNum, 2), B(vertNum, 2); | |
for (int i = 0; i < vertNum; ++i) { | |
B.coeffRef(i, 0) = i / double(vertNum); | |
B.coeffRef(i, 1) = 0; | |
} | |
// Solve sparse linear system with supernodal LU factorization | |
SparseLU<SparseMatrix<double, ColMajor>> solver; | |
solver.compute(A); | |
if (solver.info() != Success) { | |
std::cout << "err" << std::endl; | |
return 1; | |
} | |
// solve | |
X = solver.solve(B); | |
if (solver.info() != Success) { | |
std::cout << "err" << std::endl; | |
return 1; | |
} | |
for (int i = 0; i < 10; ++i) { | |
std::cout << X.coeffRef(i, 0) << ","; | |
} | |
std::cout << std::endl; | |
// Solve sparse linear system with bi conjugate gradient stabilized algorithm | |
BiCGSTAB<SparseMatrix<double, ColMajor>> solver1; | |
solver1.setMaxIterations(10000); | |
solver1.setTolerance(1.0e-6); | |
solver1.compute(A); | |
if (solver1.info() != Success) { | |
std::cout << "err" << std::endl; | |
return 1; | |
} | |
X = solver1.solve(B); | |
if (solver1.info() != Success) { | |
std::cout << "err" << std::endl; | |
return 1; | |
} | |
for (int i = 0; i < 10; ++i) { | |
std::cout << X.coeffRef(i, 0) << ","; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment