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 <utility>
11#include <vector>
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 { return nx_; }
22 int ny() const { return ny_; }
23 int nz() const { return nz_; }
24 double dx() const { return dx_; }
25 int size() const { return nx_ * ny_ * nz_; }
26
27 real& operator()(int i, int j, int k) { return data_[flat(i, j, k)]; }
28 real operator()(int i, int j, int k) const { return data_[flat(i, j, k)]; }
29
30 void set(int i, int j, int k, real v) { data_[flat(i, j, k)] = v; }
31 void fill(real v);
32
33 /// Fill every cell with f(i, j, k).
34 template<typename F>
35 void fill(F&& f) {
36 for (int k = 0; k < nz_; ++k)
37 for (int j = 0; j < ny_; ++j)
38 for (int i = 0; i < nx_; ++i)
39 data_[flat(i, j, k)] = f(i, j, k);
40 }
41
42 /// Construct and fill from callable f(i, j, k) -> real.
43 template<typename F>
44 Grid3D(int nx, int ny, int nz, double dx, F&& f)
45 : Grid3D(nx, ny, nz, dx) {
46 fill(std::forward<F>(f));
47 }
48
49 /// Copy contents into a new Vector (for solver interop).
50 Vector to_vector() const;
51 /// Copy solver result back into grid.
52 void from_vector(const Vector& v);
53
54 private:
55 int nx_, ny_, nz_;
56 double dx_;
57 std::vector<real> data_; // plain array for easy indexing
58
59 idx flat(int i, int j, int k) const { return (idx)(k * ny_ * nx_ + j * nx_ + i); }
60};
61
62} // namespace num
int size() const
Definition grid3d.hpp:25
double dx() const
Definition grid3d.hpp:24
void from_vector(const Vector &v)
Copy solver result back into grid.
Definition grid3d.cpp:27
int ny() const
Definition grid3d.hpp:22
real & operator()(int i, int j, int k)
Definition grid3d.hpp:27
Grid3D(int nx, int ny, int nz, double dx, F &&f)
Construct and fill from callable f(i, j, k) -> real.
Definition grid3d.hpp:44
void fill(F &&f)
Fill every cell with f(i, j, k).
Definition grid3d.hpp:35
int nz() const
Definition grid3d.hpp:23
int nx() const
Definition grid3d.hpp:21
real operator()(int i, int j, int k) const
Definition grid3d.hpp:28
Vector to_vector() const
Copy contents into a new Vector (for solver interop).
Definition grid3d.cpp:19
void fill(real v)
Definition grid3d.cpp:15
void set(int i, int j, int k, real v)
Definition grid3d.hpp:30
Core type definitions.
double real
Definition types.hpp:10
std::size_t idx
Definition types.hpp:11
Dense vector storage and operations.