WarpX
PoissonSolver.H
Go to the documentation of this file.
1 /* Copyright 2019-2022 Axel Huebl, Remi Lehe
2  *
3  * This file is part of WarpX.
4  *
5  * License: BSD-3-Clause-LBNL
6  */
7 #ifndef ABLASTR_POISSON_SOLVER_H
8 #define ABLASTR_POISSON_SOLVER_H
9 
10 #include <ablastr/constant.H>
12 #include <ablastr/utils/TextMsg.H>
14 
15 
16 #include <AMReX_Array.H>
17 #include <AMReX_Array4.H>
18 #include <AMReX_BLassert.H>
19 #include <AMReX_Box.H>
20 #include <AMReX_BoxArray.H>
21 #include <AMReX_Config.H>
23 #include <AMReX_FArrayBox.H>
24 #include <AMReX_FabArray.H>
25 #include <AMReX_Geometry.H>
26 #include <AMReX_GpuControl.H>
27 #include <AMReX_GpuLaunch.H>
28 #include <AMReX_GpuQualifiers.H>
29 #include <AMReX_IndexType.H>
30 #include <AMReX_IntVect.H>
31 #include <AMReX_LO_BCTYPES.H>
32 #include <AMReX_MFIter.H>
33 #include <AMReX_MFInterp_C.H>
34 #include <AMReX_MLMG.H>
35 #include <AMReX_MLLinOp.H>
37 #include <AMReX_MultiFab.H>
38 #include <AMReX_Parser.H>
39 #include <AMReX_REAL.H>
40 #include <AMReX_SPACE.H>
41 #include <AMReX_Vector.H>
42 #if defined(AMREX_USE_EB) || defined(WARPX_DIM_RZ)
44 #endif
45 #ifdef AMREX_USE_EB
46 # include <AMReX_EBFabFactory.H>
47 #endif
48 
49 #include <array>
50 #include <optional>
51 
52 
53 namespace ablastr::fields {
54 
55 namespace details
56 {
68  {
70  amrex::Array4<amrex::Real> const phi_fp_arr,
71  amrex::Array4<amrex::Real const> const phi_cp_arr,
72  amrex::IntVect const refratio)
73  : m_phi_fp_arr(phi_fp_arr), m_phi_cp_arr(phi_cp_arr), m_refratio(refratio)
74  {}
75 
77  void
78  operator() (int i, int j, int k) const noexcept
79  {
81  0, m_refratio);
82  }
83 
87  };
88 }
89 
120 template<
121  typename T_BoundaryHandler,
122  typename T_PostPhiCalculationFunctor = std::nullopt_t,
123  typename T_FArrayBoxFactory = void
124 >
125 void
128  std::array<amrex::Real, 3> const beta,
129  amrex::Real const relative_tolerance,
130  amrex::Real absolute_tolerance,
131  int const max_iters,
132  int const verbosity,
135  amrex::Vector<amrex::BoxArray> const grids,
136  T_BoundaryHandler const boundary_handler,
137  bool const do_single_precision_comms = false,
138  std::optional<amrex::Vector<amrex::IntVect> > rel_ref_ratio = std::nullopt,
139  [[maybe_unused]] T_PostPhiCalculationFunctor post_phi_calculation = std::nullopt,
140  [[maybe_unused]] std::optional<amrex::Real const> current_time = std::nullopt, // only used for EB
141  [[maybe_unused]] std::optional<amrex::Vector<T_FArrayBoxFactory const *> > eb_farray_box_factory = std::nullopt // only used for EB
142 )
143 {
144  using namespace amrex::literals;
145 
146  if (!rel_ref_ratio.has_value()) {
148  "rel_ref_ratio must be set if mesh-refinement is used");
149  rel_ref_ratio = amrex::Vector<amrex::IntVect>{{amrex::IntVect(AMREX_D_DECL(1, 1, 1))}};
150  }
151 
152  auto const finest_level = static_cast<int>(rho.size() - 1);
153 
154  // scale rho appropriately; also determine if rho is zero everywhere
155  amrex::Real max_norm_b = 0.0;
156  for (int lev=0; lev<=finest_level; lev++) {
157  using namespace ablastr::constant::SI;
158  rho[lev]->mult(-1._rt/ep0); // TODO: when do we "un-multiply" this? We need to document this side-effect!
159  max_norm_b = amrex::max(max_norm_b, rho[lev]->norm0());
160  }
162 
163  const bool always_use_bnorm = (max_norm_b > 0);
164  if (!always_use_bnorm) {
165  if (absolute_tolerance == 0.0) { absolute_tolerance = amrex::Real(1e-6); }
167  "ElectrostaticSolver",
168  "Max norm of rho is 0",
170  );
171  }
172 
173  amrex::LPInfo info;
174  for (int lev=0; lev<=finest_level; lev++) {
175  // Set the value of beta
177 #if defined(WARPX_DIM_1D_Z)
178  {{ beta[2] }}; // beta_x and beta_z
179 #elif defined(WARPX_DIM_XZ) || defined(WARPX_DIM_RZ)
180  {{ beta[0], beta[2] }}; // beta_x and beta_z
181 #else
182  {{ beta[0], beta[1], beta[2] }};
183 #endif
184 
185 #if !(defined(AMREX_USE_EB) || defined(WARPX_DIM_RZ))
186  // Determine whether to use semi-coarsening
188  {AMREX_D_DECL(geom[lev].CellSize(0)/std::sqrt(1._rt-beta_solver[0]*beta_solver[0]),
189  geom[lev].CellSize(1)/std::sqrt(1._rt-beta_solver[1]*beta_solver[1]),
190  geom[lev].CellSize(2)/std::sqrt(1._rt-beta_solver[2]*beta_solver[2]))};
191  int max_semicoarsening_level = 0;
192  int semicoarsening_direction = -1;
193  const auto min_dir = static_cast<int>(std::distance(dx_scaled.begin(),
194  std::min_element(dx_scaled.begin(),dx_scaled.end())));
195  const auto max_dir = static_cast<int>(std::distance(dx_scaled.begin(),
196  std::max_element(dx_scaled.begin(),dx_scaled.end())));
197  if (dx_scaled[max_dir] > dx_scaled[min_dir]) {
198  semicoarsening_direction = max_dir;
199  max_semicoarsening_level = static_cast<int>
200  (std::log2(dx_scaled[max_dir]/dx_scaled[min_dir]));
201  }
202  if (max_semicoarsening_level > 0) {
203  info.setSemicoarsening(true);
204  info.setMaxSemicoarseningLevel(max_semicoarsening_level);
205  info.setSemicoarseningDirection(semicoarsening_direction);
206  }
207 #endif
208 
209 #if defined(AMREX_USE_EB) || defined(WARPX_DIM_RZ)
210  // In the presence of EB or RZ: the solver assumes that the beam is
211  // propagating along one of the axes of the grid, i.e. that only *one*
212  // of the components of `beta` is non-negligible.
213  amrex::MLEBNodeFDLaplacian linop( {geom[lev]}, {grids[lev]}, {dmap[lev]}, info
214 #if defined(AMREX_USE_EB)
215  , {eb_farray_box_factory.value()[lev]}
216 #endif
217  );
218 
219  // Note: this assumes that the beam is propagating along
220  // one of the axes of the grid, i.e. that only *one* of the
221  // components of `beta` is non-negligible. // we use this
222 #if defined(WARPX_DIM_RZ)
223  linop.setSigma({0._rt, 1._rt-beta_solver[1]*beta_solver[1]});
224 #else
225  linop.setSigma({AMREX_D_DECL(
226  1._rt-beta_solver[0]*beta_solver[0],
227  1._rt-beta_solver[1]*beta_solver[1],
228  1._rt-beta_solver[2]*beta_solver[2])});
229 #endif
230 
231 #if defined(AMREX_USE_EB)
232  // if the EB potential only depends on time, the potential can be passed
233  // as a float instead of a callable
234  if (boundary_handler.phi_EB_only_t) {
235  linop.setEBDirichlet(boundary_handler.potential_eb_t(current_time.value()));
236  }
237  else
238  linop.setEBDirichlet(boundary_handler.getPhiEB(current_time.value()));
239 #endif
240 #else
241  // In the absence of EB and RZ: use a more generic solver
242  // that can handle beams propagating in any direction
243  amrex::MLNodeTensorLaplacian linop( {geom[lev]}, {grids[lev]},
244  {dmap[lev]}, info );
245  linop.setBeta( beta_solver ); // for the non-axis-aligned solver
246 #endif
247 
248  // Solve the Poisson equation
249  linop.setDomainBC( boundary_handler.lobc, boundary_handler.hibc );
250 #ifdef WARPX_DIM_RZ
251  linop.setRZ(true);
252 #endif
253  amrex::MLMG mlmg(linop); // actual solver defined here
254  mlmg.setVerbose(verbosity);
255  mlmg.setMaxIter(max_iters);
256  mlmg.setAlwaysUseBNorm(always_use_bnorm);
257 
258  // Solve Poisson equation at lev
259  mlmg.solve( {phi[lev]}, {rho[lev]},
260  relative_tolerance, absolute_tolerance );
261 
262  // needed for solving the levels by levels:
263  // - coarser level is initial guess for finer level
264  // - coarser level provides boundary values for finer level patch
265  // Interpolation from phi[lev] to phi[lev+1]
266  // (This provides both the boundary conditions and initial guess for phi[lev+1])
267  if (lev < finest_level) {
268 
269  // Allocate phi_cp for lev+1
270  amrex::BoxArray ba = phi[lev+1]->boxArray();
271  const amrex::IntVect& refratio = rel_ref_ratio.value()[lev];
272  ba.coarsen(refratio);
273  const int ncomp = linop.getNComp();
274  amrex::MultiFab phi_cp(ba, phi[lev+1]->DistributionMap(), ncomp, 1);
275 
276  // Copy from phi[lev] to phi_cp (in parallel)
278  const amrex::Periodicity& crse_period = geom[lev].periodicity();
279 
281  phi_cp,
282  *phi[lev],
283  0,
284  0,
285  1,
286  ng,
287  ng,
288  do_single_precision_comms,
289  crse_period
290  );
291 
292  // Local interpolation from phi_cp to phi[lev+1]
293 #ifdef AMREX_USE_OMP
294 #pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
295 #endif
296  for (amrex::MFIter mfi(*phi[lev + 1], amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi) {
297  amrex::Array4<amrex::Real> const phi_fp_arr = phi[lev + 1]->array(mfi);
298  amrex::Array4<amrex::Real const> const phi_cp_arr = phi_cp.array(mfi);
299 
300  details::PoissonInterpCPtoFP const interp(phi_fp_arr, phi_cp_arr, refratio);
301 
302  amrex::Box const b = mfi.tilebox(phi[lev + 1]->ixType().toIntVect());
304  }
305 
306  }
307 
308  // Run additional operations, such as calculation of the E field for embedded boundaries
310  if (post_phi_calculation.has_value()) {
311  post_phi_calculation.value()(mlmg, lev);
312  }
313  }
314 
315  } // loop over lev(els)
316 }
317 
318 } // namespace ablastr::fields
319 
320 #endif // ABLASTR_POISSON_SOLVER_H
#define AMREX_FORCE_INLINE
#define AMREX_GPU_DEVICE
#define AMREX_D_DECL(a, b, c)
#define ABLASTR_ALWAYS_ASSERT_WITH_MESSAGE(EX, MSG)
Definition: TextMsg.H:75
BoxArray & coarsen(int refinement_ratio)
Array4< typename FabArray< FArrayBox >::value_type const > array(const MFIter &mfi) const noexcept
AMREX_GPU_HOST_DEVICE static constexpr AMREX_FORCE_INLINE IntVect TheUnitVector() noexcept
void setSigma(Array< Real, AMREX_SPACEDIM > const &a_sigma) noexcept
void setVerbose(int v) noexcept
void setAlwaysUseBNorm(int flag) noexcept
RT solve(const Vector< AMF * > &a_sol, const Vector< AMF const * > &a_rhs, RT a_tol_rel, RT a_tol_abs, const char *checkpoint_file=nullptr)
void setMaxIter(int n) noexcept
void setBeta(Array< Real, AMREX_SPACEDIM > const &a_beta) noexcept
Long size() const noexcept
AMREX_GPU_DEVICE AMREX_FORCE_INLINE void interp(int j, int k, int l, amrex::Array4< amrex::Real > const &fine, amrex::Array4< amrex::Real const > const &crse, const amrex::IntVect r_ratio, IntVect const &type) noexcept
Definition: Interpolate_K.H:9
Definition: constant.H:40
static constexpr auto ep0
vacuum permittivity: dielectric permittivity of vacuum [F/m]
Definition: constant.H:46
Definition: PoissonSolver.H:53
void computePhi(amrex::Vector< amrex::MultiFab * > const &rho, amrex::Vector< amrex::MultiFab * > &phi, std::array< amrex::Real, 3 > const beta, amrex::Real const relative_tolerance, amrex::Real absolute_tolerance, int const max_iters, int const verbosity, amrex::Vector< amrex::Geometry > const geom, amrex::Vector< amrex::DistributionMapping > const dmap, amrex::Vector< amrex::BoxArray > const grids, T_BoundaryHandler const boundary_handler, bool const do_single_precision_comms=false, std::optional< amrex::Vector< amrex::IntVect > > rel_ref_ratio=std::nullopt, [[maybe_unused]] T_PostPhiCalculationFunctor post_phi_calculation=std::nullopt, [[maybe_unused]] std::optional< amrex::Real const > current_time=std::nullopt, [[maybe_unused]] std::optional< amrex::Vector< T_FArrayBoxFactory const * > > eb_farray_box_factory=std::nullopt)
Definition: PoissonSolver.H:126
void ParallelCopy(amrex::MultiFab &dst, const amrex::MultiFab &src, int src_comp, int dst_comp, int num_comp, const amrex::IntVect &src_nghost, const amrex::IntVect &dst_nghost, bool do_single_precision_comms, const amrex::Periodicity &period, amrex::FabArrayBase::CpOp op)
Definition: Communication.cpp:28
void WMRecordWarning(std::string topic, std::string text, WarnPriority priority=WarnPriority::medium)
Helper function to abbreviate the call to WarnManager::GetInstance().RecordWarning (recording a warni...
Definition: WarnManager.cpp:318
void ReduceRealMax(Vector< std::reference_wrapper< Real > > &&)
AMREX_GPU_HOST_DEVICE constexpr AMREX_FORCE_INLINE const T & max(const T &a, const T &b) noexcept
std::enable_if_t< std::is_integral< T >::value > ParallelFor(TypeList< CTOs... >, std::array< int, sizeof...(CTOs)> const &runtime_options, T N, F &&f)
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE void mf_nodebilin_interp(int i, int, int, int n, Array4< Real > const &fine, int fcomp, Array4< Real const > const &crse, int ccomp, IntVect const &ratio) noexcept
bool TilingIfNotGPU() noexcept
std::array< T, N > Array
i
Definition: check_interp_points_and_weights.py:174
beta
Definition: stencil.py:434
value
Definition: updateAMReX.py:141
Definition: PoissonSolver.H:68
PoissonInterpCPtoFP(amrex::Array4< amrex::Real > const phi_fp_arr, amrex::Array4< amrex::Real const > const phi_cp_arr, amrex::IntVect const refratio)
Definition: PoissonSolver.H:69
amrex::Array4< amrex::Real > const m_phi_fp_arr
Definition: PoissonSolver.H:84
amrex::Array4< amrex::Real const > const m_phi_cp_arr
Definition: PoissonSolver.H:85
amrex::IntVect const m_refratio
Definition: PoissonSolver.H:86
AMREX_GPU_DEVICE AMREX_FORCE_INLINE void operator()(int i, int j, int k) const noexcept
Definition: PoissonSolver.H:78
LPInfo & setSemicoarsening(bool x) noexcept
LPInfo & setMaxSemicoarseningLevel(int n) noexcept
LPInfo & setSemicoarseningDirection(int n) noexcept
int verbosity()