This example demonstrates the usage of the sparse matrix interface. It solves a discretization of the Poisson equation in 1D.
#include <iostream>
#include <string>
#include <cassert>
#include <allium/main/init.hpp>
#include <allium/ipc/comm.hpp>
#include <allium/la/cg.hpp>
#include <allium/la/default.hpp>
using namespace allium;
int main(int argc, char** argv) {
Init init(argc, argv);
if (argc != 2) {
std::cerr << "Usage: " << argv[0] << " dimension" << std::endl;
return EXIT_FAILURE;
}
size_t N = std::stoi(argv[1]);
auto comm = Comm::world();
assert(N % comm.size() == 0);
size_t N_loc = N / comm.size();
VectorSpec spec(comm, N_loc, N);
std::cout
<< "Rank " << comm.rank()
<< " [" << spec.local_start() << ", " << spec.local_end() << ")"
<< std::endl;
LocalCooMatrix<double> lmat;
for (global_size_t i = spec.local_start(); i < spec.local_end(); ++i) {
if (i > 0) {
lmat.add(i, i-1, -1.0);
}
lmat.add(i, i, 2.0);
if (i < N-1) {
lmat.add(i, i+1, -1.0);
}
}
auto mat = std::make_shared<DefaultSparseMatrix<double>>(spec, spec);
mat->set_entries(lmat);
DefaultVector<double> v(spec);
auto v_loc = local_slice(v);
for (global_size_t i_glob = spec.local_start(); i_glob < spec.local_end(); i_glob++)
{
global_size_t i_loc = i_glob - spec.local_start();
if (i_glob == 0 || i_glob == spec.global_size() - 1) {
v_loc[i_loc] = 1.0;
} else {
v_loc[i_loc] = 0.0;
}
}
v_loc.release();
DefaultVector<double> result(spec);
for (int i_rank = 0; i_rank < comm.size(); ++i_rank) {
comm.barrier();
if (i_rank == comm.rank()) {
auto loc = local_slice(result);
for (size_t i_loc = 0; i_loc < spec.local_size(); ++i_loc) {
std::cout << loc[i_loc] << std::endl;
}
}
}
return EXIT_SUCCESS;
}
void cg(V &solution, std::shared_ptr< M > mat, const V &rhs, real_part_t< typename V::Number > tol=1e-8)
The conjugate gradient method.
Definition: cg.hpp:104