numerics 0.1.0
Loading...
Searching...
No Matches
grid3d.hpp
Go to the documentation of this file.
1/// @file spatial/grid3d.hpp
2/// @brief 3D Cartesian scalar grid backed by num::Vector storage.
3///
4/// Flat layout: idx = k*ny*nx + j*nx + i (x is fastest, z is slowest)
5/// Used by the field physics module for Poisson/diffusion solves.
6#pragma once
7
8#include "core/types.hpp"
9#include "core/vector.hpp"
10#include <vector>
11#include <utility>
12
13namespace num {
14
15class Grid3D {
16 public:
17 /// @param nx,ny,nz Number of cells in each dimension
18 /// @param dx Uniform cell size [m]
19 Grid3D(int nx, int ny, int nz, double dx = 1.0);
20
21 int nx() const {
22 return nx_;
23 }
24 int ny() const {
25 return ny_;
26 }
27 int nz() const {
28 return nz_;
29 }
30 double dx() const {
31 return dx_;
32 }
33 int size() const {
34 return nx_ * ny_ * nz_;
35 }
36
37 real& operator()(int i, int j, int k) {
38 return data_[flat(i, j, k)];
39 }
40 real operator()(int i, int j, int k) const {
41 return data_[flat(i, j, k)];
42 }
43
44 void set(int i, int j, int k, real v) {
45 data_[flat(i, j, k)] = v;
46 }
47 void fill(real v);
48
49 /// Fill every cell with f(i, j, k).
50 template<typename F>
51 void fill(F&& f) {
52 for (int k = 0; k < nz_; ++k)
53 for (int j = 0; j < ny_; ++j)
54 for (int i = 0; i < nx_; ++i)
55 data_[flat(i, j, k)] = f(i, j, k);
56 }
57
58 /// Construct and fill from callable f(i, j, k) -> real.
59 template<typename F>
60 Grid3D(int nx, int ny, int nz, double dx, F&& f)
61 : Grid3D(nx, ny, nz, dx) { fill(std::forward<F>(f)); }
62
63 /// Copy contents into a new Vector (for solver interop).
64 Vector to_vector() const;
65 /// Copy solver result back into grid.
66 void from_vector(const Vector& v);
67
68 private:
69 int nx_, ny_, nz_;
70 double dx_;
71 std::vector<real> data_; // plain array for easy indexing
72
73 idx flat(int i, int j, int k) const {
74 return (idx)(k * ny_ * nx_ + j * nx_ + i);
75 }
76};
77
78} // namespace num
int size() const
Definition grid3d.hpp:33
double dx() const
Definition grid3d.hpp:30
void from_vector(const Vector &v)
Copy solver result back into grid.
Definition grid3d.cpp:26
int ny() const
Definition grid3d.hpp:24
real & operator()(int i, int j, int k)
Definition grid3d.hpp:37
Grid3D(int nx, int ny, int nz, double dx, F &&f)
Construct and fill from callable f(i, j, k) -> real.
Definition grid3d.hpp:60
void fill(F &&f)
Fill every cell with f(i, j, k).
Definition grid3d.hpp:51
int nz() const
Definition grid3d.hpp:27
int nx() const
Definition grid3d.hpp:21
real operator()(int i, int j, int k) const
Definition grid3d.hpp:40
Vector to_vector() const
Copy contents into a new Vector (for solver interop).
Definition grid3d.cpp:18
void fill(real v)
Definition grid3d.cpp:14
void set(int i, int j, int k, real v)
Definition grid3d.hpp:44
Core type definitions.
double real
Definition types.hpp:10
std::size_t idx
Definition types.hpp:11
Vector operations.