06_poisson_equation.cpp¶
Solve the Poisson equation in three dimensions, and measure the error as the grid is refined.
field_solver::solve_poisson(phi, s) solves \(\Delta\phi = s\) with zero Dirichlet boundaries. It runs CG on the 7-point Laplacian and uses the field's own storage as the solution vector. The manufactured solution \(\phi = e^x\sin\pi x\sin\pi y\sin\pi z\) vanishes on the boundary, and halving the grid spacing divides the error by about four.
#include <cmath>
#include <io/json.hpp>
#include <numbers>
#include <numerics.hpp>
#include <string_view>
#include <vector>
using namespace num;
int main(int argc, char **argv) {
const bool plot = argc > 1 && std::string_view(argv[1]) == "--plot";
constexpr real pi = std::numbers::pi;
io::json results = io::json::array();
real previous = 0.0;
std::vector<double> slice_x, slice_phi;
for (idx n : {9, 17, 33}) {
const real h = 1.0 / static_cast<real>(n - 1);
const int m = static_cast<int>(n);
const auto spacing = static_cast<float>(h);
scalar_field_3d exact(m, m, m, spacing), source(m, m, m, spacing), phi(m, m, m, spacing);
for (idx i = 0; i < n; ++i) {
for (idx j = 0; j < n; ++j) {
for (idx k = 0; k < n; ++k) {
const real x = i * h, y = j * h, z = k * h;
const real yz = std::sin(pi * y) * std::sin(pi * z);
exact(i, j, k) = std::exp(x) * std::sin(pi * x) * yz;
// Laplacian of the above, worked out by hand.
source(i, j, k) = std::exp(x) * yz *
(((1.0 - (3.0 * pi * pi)) * std::sin(pi * x)) +
(2.0 * pi * std::cos(pi * x)));
}
}
}
const solver_result result = field_solver::solve_poisson(phi, source, 1e-12, 2000);
real error = 0.0;
for (idx s = 0; s < phi.size(); ++s) {
error = std::max(error, std::abs(phi.as_vec()[s] - exact.as_vec()[s]));
}
results.push_back({{"grid_points", n}, {"spacing", h},
{"cg_iterations", result.iterations}, {"max_error", error},
{"error_ratio", previous > 0.0 ? previous / error : 0.0}});
previous = error;
if (n == 33) {
for (idx i = 0; i < n; ++i) {
slice_x.push_back(i * h);
slice_phi.push_back(phi(i, n / 2, n / 2));
}
}
}
io::write_json(results, "result.json");
if (plot) {
plt::plot(slice_x, slice_phi, "phi(x, 1/2, 1/2)", "lines");
plt::title("06 Poisson solution, centre slice");
plt::savefig("plot.png");
}
}
Saved result:
[
{
"cg_iterations": 10,
"error_ratio": 0.0,
"grid_points": 9,
"max_error": 0.02016886745819435,
"spacing": 0.125
},
{
"cg_iterations": 26,
"error_ratio": 4.0165706681721876,
"grid_points": 17,
"max_error": 0.005021414814885494,
"spacing": 0.0625
},
{
"cg_iterations": 59,
"error_ratio": 4.004108985850633,
"grid_points": 33,
"max_error": 0.0012540654694039866,
"spacing": 0.03125
}
]
