ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_ProbCommon.H
Go to the documentation of this file.
1 #ifndef ERF_PROBCOMMON_H_
2 #define ERF_PROBCOMMON_H_
3 
4 #include <algorithm>
5 #include <cmath>
6 
7 #include <AMReX_ParmParse.H>
8 #include <AMReX_Geometry.H>
9 #include <AMReX_FArrayBox.H>
10 #include <AMReX_MultiFab.H>
11 #include <AMReX_Reduce.H>
12 
13 #include "ERF_DataStruct.H"
14 #include "ERF_NumericalConstants.H"
15 #include "ERF_EOS.H"
16 #include "ERF_HSEUtils.H"
17 #include "ERF_GridUtils.H"
18 #include "ERF_TileNoZ.H"
19 #include "ERF_ColumnBands.H"
20 
21 #ifdef ERF_USE_NETCDF
22 #include <ERF_NCInterface.H>
23 #endif
24 
28 };
29 
30 template <typename T>
31 T erf_get_single_value (std::istream& is, int n)
32 {
33  T r = 0;
34  std::string line;
35  if (std::getline(is, line)) {
36  std::stringstream ss(line);
37  ss >> r;
38  if (ss.fail()) {
39  amrex::Abort("Failed to read");
40  }
41  if (ss >> r) {
42  amrex::Print() << "Trying to read line " << n << " in this file " << std::endl;
43  amrex::Abort("Wrong format: more than one number in this line");
44  }
45  } else {
46  amrex::Abort("Unable to read this line");
47  }
48  return r;
49 }
50 
51 void
52 init_my_custom_terrain (const amrex::Geometry& geom,
53  amrex::FArrayBox& terrain_fab,
54  const double& time);
55 
56 /**
57  * Class to hold problem-specific routines
58 */
60 {
61 public:
62 
63  /**
64  * Virtual destructor to avoid data leakage with derived class
65  */
66  virtual ~ProblemBase () = default;
67 
68  /**
69  * Function to initialize the hydrostatic reference density
70  *
71  * @param[out] rho_hse hydrostatic reference density
72  * @param[in] z_phys_nd height coordinate at nodes
73  * @param[in] z_phys_cc height coordinate at cell centers
74  * @param[in] geom container for geometric information
75  */
76  virtual void
77  erf_init_dens_hse_dry (amrex::MultiFab& /*rho_hse*/,
78  std::unique_ptr<amrex::MultiFab>& /*z_phys_nd*/,
79  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/,
80  amrex::Geometry const& /*geom*/,
81  const amrex::Vector<amrex::Real>& /*stretched_dz_h*/,
82  bool /*is_constant_dz*/, bool /*is_stretched_dz*/)
83  {
84  amrex::Print() << "Hydrostatically balanced density was NOT set"
85  << " -- an appropriate init_type should probably have been specified"
86  << " (e.g., input_sounding, WRFInput, or Metgrid)"
87  << std::endl;
88  amrex::Error("Should never call this version of erf_init_dens_hse_dry for "+name()+" problem");
89  }
90 
91  virtual void
92  erf_init_const_dens_hse(amrex::MultiFab& /*rho_hse*/)
93  {
94  amrex::Error("Should never call this version of erf_init_const_dens_hse for "+name()+" problem");
95  }
96 
97  virtual void
98  erf_init_const_dens_and_th_hse (amrex::MultiFab& /*rho_hse*/, amrex::MultiFab& /* p_hse*/,
99  amrex::MultiFab& /* pi_hse*/, amrex::MultiFab& /*th_hse*/,
100  amrex::MultiFab& /* qv_hse*/, amrex::Real /*l_rdOcp*/)
101  {
102  amrex::Error("Should never call this version of erf_init_const_dens_and_th_hse for "+name()+" problem");
103  }
104 
105  virtual void
106  erf_init_const_dens_and_linear_th_hse (amrex::MultiFab& /*rho_hse*/, amrex::MultiFab& /* p_hse*/,
107  amrex::MultiFab& /* pi_hse*/, amrex::MultiFab& /*th_hse*/,
108  amrex::MultiFab& /* qv_hse*/, amrex::Real /*l_rdOcp*/,
109  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/)
110  {
111  amrex::Error("Should never call this version of erf_init_const_dens_and_linear_th_hse for "+name()+" problem");
112  }
113 
114  virtual void
115  erf_init_dens_hse_moist (amrex::MultiFab& /*rho_hse*/,
116  std::unique_ptr<amrex::MultiFab>& /*z_phys_nd*/,
117  amrex::Geometry const& /*geom*/)
118  {
119 
120  }
121 
122  /**
123  * Function to perform custom initialization of a test problem
124  *
125  * @param[in] bx cell-centered box on which to initialize scalars
126  * @param[out] state cell-centered variables to be filled in this routine
127  * @param[out] r_hse hydrostatic reference density
128  * @param[out] p_hse hydrostatic reference pressure
129  * @param[in] z_nd height coordinate at nodes
130  * @param[in] z_cc height coordinate at cell centers
131  * @param[in] mf_m map factor on cell centers
132  * @param[in] mf_u map factor on x-faces
133  * @param[in] mf_v map factor on y-faces
134  * @param[in] sc SolverChoice structure that carries parameters
135  * @param[in] lev AMR level
136  */
137  virtual void
138  init_custom_pert (const amrex::Box& /*bx*/,
139  amrex::Array4<amrex::Real const> const& /*state*/,
140  amrex::Array4<amrex::Real > const& /*state_pert*/,
141  amrex::Array4<amrex::Real > const& /*r_hse*/,
142  amrex::Array4<amrex::Real > const& /*p_hse*/,
143  amrex::Array4<amrex::Real const> const& /*z_nd*/,
144  amrex::Array4<amrex::Real const> const& /*z_cc*/,
145  amrex::GeometryData const& /*geomdata*/,
146  amrex::Array4<amrex::Real const> const& /*mf_m*/,
147  const SolverChoice& /*sc*/, const int /*lev*/)
148  {
149  amrex::Print() << "No perturbation to background fields supplied for "
150  << name() << " problem" << std::endl;
151  }
152 
153  /**
154  * Function to perform custom initialization of the velocities
155  *
156  * @param[in] xbx box on which to initialize x_vel_pert
157  * @param[in] ybx box on which to initialize y_vel_pert
158  * @param[in] zbx box on which to initialize z_vel_pert
159  * @param[out] x_vel_pert x-component of velocity perturbation to be filled in this routine
160  * @param[out] y_vel_pert y-component of velocity perturbation to be filled in this routine
161  * @param[out] z_vel_pert z-component of velocity perturbation to be filled in this routine
162  * @param[in] z_nd height coordinate at nodes
163  * @param[in] mf_m map factor on cell centers
164  * @param[in] mf_u map factor on x-faces
165  * @param[in] mf_v map factor on y-faces
166  * @param[in] sc SolverChoice structure that carries parameters
167  * @param[in] lev AMR level
168  */
169  virtual void
170  init_custom_pert_vels (const amrex::Box& /*xbx*/,
171  const amrex::Box& /*ybx*/,
172  const amrex::Box& /*zbx*/,
173  amrex::Array4<amrex::Real > const& /*x_vel_pert*/,
174  amrex::Array4<amrex::Real > const& /*y_vel_pert*/,
175  amrex::Array4<amrex::Real > const& /*z_vel_pert*/,
176  amrex::Array4<amrex::Real const> const& /*z_nd*/,
177  amrex::GeometryData const& /*geomdata*/,
178  amrex::Array4<amrex::Real const> const& /*mf_u*/,
179  amrex::Array4<amrex::Real const> const& /*mf_v*/,
180  const SolverChoice& /*sc*/, const int /*lev*/)
181  {
182  amrex::Print() << "No perturbation velocities supplied for " << name() << " problem" << std::endl;
183  }
184 
185  /**
186  * Function to update user-specified temperature source terms that can
187  * vary with time and height.
188  *
189  * @param[in] time current time
190  * @param[out] rhotheta_source forcing profile
191  * @param[in] geom container for geometric information
192  * @param[in] z_phys_cc height coordinate at cell centers
193  */
194  virtual void
195  update_rhotheta_sources (const double& /*time*/,
196  amrex::MultiFab* src,
197  const amrex::Geometry& /*geom*/,
198  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/)
199  {
200  if (src->empty()) return;
201 
202  amrex::Warning("Temperature forcing not defined for "+name()+" problem");
203  for ( amrex::MFIter mfi(*src, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi )
204  {
205  const auto &box = mfi.tilebox();
206  const amrex::Array4<amrex::Real>& src_arr = src->array(mfi);
207  // src is a spatial function if erf.spatial_rhotheta_forcing = true
208  // otherwise, qsrc_arr is defined only in over Z (box x and y dimensions are 1)
209  ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept {
210  // const amrex::Real z_cc = prob_lo[2] + (k+myhalf)* dx[2];
211  // set RHS term of RhoTheta equation based on time, z_cc here
212  src_arr(i, j, k) = zero;
213  });
214  }
215  }
216 
217  /**
218  * Function to update user-specified moisture source terms that can
219  * vary with time and height.
220  *
221  * @param[in] time current time
222  * @param[out] rhoqt_source moisture forcing profile
223  * @param[in] geom container for geometric information
224  * @param[in] z_phys_cc height coordinate at cell centers
225  */
226  virtual void
227  update_rhoqt_sources (const double& /*time*/,
228  amrex::MultiFab* qsrc,
229  const amrex::Geometry& /*geom*/,
230  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/)
231  {
232  if (qsrc->empty()) return;
233 
234  amrex::Warning("Moisture forcing not defined for "+name()+" problem");
235  for ( amrex::MFIter mfi(*qsrc, amrex::TilingIfNotGPU()); mfi.isValid(); ++mfi )
236  {
237  const auto &box = mfi.tilebox();
238  const amrex::Array4<amrex::Real>& qsrc_arr = qsrc->array(mfi);
239  // src is a spatial function if erf.spatial_moisture_forcing = true
240  // otherwise, qsrc_arr is defined only in over Z (box x and y dimensions are 1)
241  ParallelFor(box, [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept {
242  // const amrex::Real z_cc = prob_lo[2] + (k+myhalf)* dx[2];
243  // set RHS term of RhoQ1 equation based on time, z_cc here
244  qsrc_arr(i, j, k) = zero;
245  });
246  }
247  }
248 
249  /**
250  * Function to update the vertical velocity profile, used to add subsidence
251  * source terms for x-mom, y-mom, rho*theta, rho*Q1, and rho*Q2.
252  *
253  * TODO: Currently, this is only called by InitData, so there is no time
254  * dependence.
255  *
256  * @param[in] time current time
257  * @param[out] wbar w vel forcing profile
258  * @param[in] geom container for geometric information
259  * @param[in] z_phys_cc height coordinate at cell centers
260  */
261  virtual void
262  update_w_subsidence (const double& /*time*/,
263  amrex::Vector<amrex::Real>& wbar,
264  amrex::Gpu::DeviceVector<amrex::Real>& d_wbar,
265  const amrex::MultiFab& /*state*/,
266  const amrex::Geometry& geom,
267  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/)
268  {
269  if (wbar.empty()) return;
270 
271  amrex::Warning("Moisture forcing not defined for "+name()+" problem");
272 
273  const int khi = geom.Domain().bigEnd()[2];
274  // const amrex::Real* prob_lo = geom.ProbLo();
275  // const auto dx = geom.CellSize();
276  for (int k = 0; k <= khi; k++)
277  {
278  // const amrex::Real z_cc = prob_lo[2] + (k+myhalf)* dx[2];
279  // set vertical velocity profile based on time, z_cc here
280  wbar[k] = zero;
281  }
282 
283  // Copy from host version to device version
284  amrex::Gpu::copy(amrex::Gpu::hostToDevice, wbar.begin(), wbar.end(), d_wbar.begin());
285  }
286 
287  /**
288  * Function to update user-specified geostrophic wind profile.
289  *
290  * @param[in] time current time
291  * @param[out] u_geos geostrophic wind profile
292  * @param[out] v_geos geostrophic wind profile
293  * @param[in] geom container for geometric information
294  * @param[in] z_phys_cc height coordinate at cell centers
295  */
296  virtual void
297  update_geostrophic_profile (const double& /*time*/,
298  amrex::Vector<amrex::Real>& u_geos,
299  amrex::Gpu::DeviceVector<amrex::Real>& d_u_geos,
300  amrex::Vector<amrex::Real>& v_geos,
301  amrex::Gpu::DeviceVector<amrex::Real>& d_v_geos,
302  const amrex::Geometry& geom,
303  std::unique_ptr<amrex::MultiFab>& /*z_phys_cc*/)
304  {
305  if (u_geos.empty()) return;
306 
307  amrex::Warning("Geostrophic wind profile not defined for "+name()+" problem");
308 
309  const int khi = geom.Domain().bigEnd()[2];
310  // const amrex::Real* prob_lo = geom.ProbLo();
311  // const auto dx = geom.CellSize();
312  for (int k = 0; k <= khi; k++)
313  {
314  // const amrex::Real z_cc = prob_lo[2] + (k+myhalf)* dx[2];
315  // set RHS term of RhoTheta equation based on time, z_cc here
316  u_geos[k] = zero;
317  v_geos[k] = zero;
318  }
319 
320  // Copy from host version to device version
321  amrex::Gpu::copy(amrex::Gpu::hostToDevice, u_geos.begin(), u_geos.end(), d_u_geos.begin());
322  amrex::Gpu::copy(amrex::Gpu::hostToDevice, v_geos.begin(), v_geos.end(), d_v_geos.begin());
323  }
324 
325  /**
326  * Function to perform custom initialization of buildings
327  *
328  * @param[in] geom container for geometric information
329  * @param[out] z_phys_nd height coordinate at nodes
330  * @param[in] time current time
331  */
332  void
333  init_buildings_surface (const amrex::Geometry& geom,
334  amrex::FArrayBox& buildings_fab,
335  const double& time)
336  {
337  // Check if a valid text file exists for the buildings
338  std::string fname;
339  amrex::ParmParse pp("erf");
340  auto valid_fname = pp.queryAdd("buildings_file_name",fname);
341 
342  if (valid_fname) {
343  read_custom_terrain(fname,false,geom,buildings_fab,time);
344  } else {
345  init_my_custom_terrain(geom, buildings_fab, time);
346  }
347  }
348 
349 
350  /**
351  * Function to perform custom initialization of terrain
352  *
353  * @param[in] geom container for geometric information
354  * @param[out] z_phys_nd height coordinate at nodes
355  * @param[in] time current time
356  */
357  void
358  init_terrain_surface (const amrex::Geometry& geom,
359  amrex::FArrayBox& terrain_fab,
360  const double& time)
361  {
362  amrex::ParmParse pp("erf");
363 
364  // NetCDF terrain file takes priority
365  std::string fname_nc;
366  auto valid_fname_nc = pp.query("terrain_file_name_nc", fname_nc);
367 
368  std::string fname, fname_usgs;
369  auto valid_fname = pp.query("terrain_file_name", fname);
370  auto valid_fname_USGS = pp.query("terrain_file_name_USGS", fname_usgs);
371 
372  if (valid_fname_nc) {
373 #ifdef ERF_USE_NETCDF
374  read_terrain_netcdf(fname_nc, geom, terrain_fab, time);
375 #else
376  amrex::Abort("ERF must be compiled with NetCDF support to use terrain_file_name_nc");
377 #endif
378  } else if (valid_fname) {
379  read_custom_terrain(fname, false, geom, terrain_fab, time);
380 
381  } else if (valid_fname_USGS) {
382  read_custom_terrain(fname_usgs, true, geom, terrain_fab, time);
383 
384  } else {
385  init_my_custom_terrain (geom, terrain_fab, time);
386  }
387  }
388 
389  /**
390  * Function to report whether the user has actually specified a terrain surface,
391  * i.e. whether init_terrain_surface will do anything other than return flat terrain.
392  *
393  * This mirrors the source precedence in init_terrain_surface, and is deliberately
394  * kept next to it so that the two cannot drift apart. A problem that overrides
395  * the terrain unconditionally, rather than keying off prob.custom_terrain_type,
396  * should override this to return true.
397  */
398  virtual bool
400  {
401  amrex::ParmParse pp("erf");
402  std::string fname;
403  if (pp.query("terrain_file_name_nc", fname) ||
404  pp.query("terrain_file_name", fname) ||
405  pp.query("terrain_file_name_USGS", fname)) {
406  return true;
407  }
408 
409  std::string custom_terrain_type = "None";
410  amrex::ParmParse pp_prob("prob");
411  pp_prob.query("custom_terrain_type", custom_terrain_type);
412  return (custom_terrain_type != "None");
413  }
414 
415 #ifdef ERF_USE_NETCDF
416  void
417  read_terrain_netcdf (const std::string& fname,
418  const amrex::Geometry& geom,
419  amrex::FArrayBox& terrain_fab,
420  const amrex::Real& /*time*/)
421  {
422  amrex::Print() << "Reading terrain from NetCDF file: " << fname << std::endl;
423 
424  amrex::Vector<amrex::Real> m_xterrain, m_yterrain, m_zterrain;
425  int nx = 0, ny = 0;
426  // Broadcast this as a trivially broadcastable integer before the
427  // interpolation kernel is launched.
428  int mass_point_terrain = 0;
429 
430  if (amrex::ParallelDescriptor::IOProcessor()) {
431  auto ncf = ncutils::NCFile::open(fname, NC_NOWRITE);
432 
433  // Try common terrain variable names
434  std::string height_varname = "height";
435  if (!ncf.has_var("height")) {
436  if (ncf.has_var("z")) height_varname = "z";
437  else if (ncf.has_var("terrain")) height_varname = "terrain";
438  else if (ncf.has_var("HGT_M")) height_varname = "HGT_M";
439  else if (ncf.has_var("AGL")) height_varname = "AGL";
440  else
441  amrex::Abort("No terrain height variable found in NetCDF file. "
442  "Expected: 'height', 'z', 'terrain', 'HGT_M', or 'AGL'");
443  }
444  amrex::Print() << " Using terrain variable: " << height_varname << std::endl;
445 
446  auto var = ncf.var(height_varname);
447  auto dims = var.shape();
448  const auto dim_names = var.dimnames();
449  const auto is_y_dimension = [] (const std::string& name) {
450  return name == "y" || name == "south_north";
451  };
452  const auto is_x_dimension = [] (const std::string& name) {
453  return name == "x" || name == "west_east";
454  };
455  const auto is_time_dimension = [] (const std::string& name) {
456  return name == "time" || name == "Time";
457  };
458 
459  bool has_time_dimension = false;
460  if (dims.size() == 2) {
461  if (dim_names.size() != 2 || !is_y_dimension(dim_names[0]) ||
462  !is_x_dimension(dim_names[1])) {
463  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" +
464  fname + "' must use dimensions (y,x) or "
465  "(south_north,west_east)");
466  }
467  ny = dims[0];
468  nx = dims[1];
469  } else if (dims.size() == 3) {
470  if (dim_names.size() != 3 || !is_time_dimension(dim_names[0]) ||
471  !is_y_dimension(dim_names[1]) || !is_x_dimension(dim_names[2])) {
472  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" +
473  fname + "' must use dimensions (time,y,x) with time leading; "
474  "accepted layouts are (y,x) and (time,y,x)");
475  }
476  if (dims[0] < 1) {
477  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" +
478  fname + "' has no time records");
479  }
480  has_time_dimension = true;
481  ny = dims[1];
482  nx = dims[2];
483  } else {
484  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" + fname +
485  "' has unsupported rank " + std::to_string(dims.size()) +
486  "; accepted layouts are (y,x) and (time,y,x)");
487  }
488 
489  if (nx < 2 || ny < 2) {
490  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" +
491  fname + "' requires at least two x and y coordinates "
492  "for bilinear interpolation");
493  }
494 
495  const bool has_x = ncf.has_var("x");
496  const bool has_y = ncf.has_var("y");
497  if (has_x != has_y) {
498  amrex::Abort("NetCDF terrain file '" + fname +
499  "' must provide both one-dimensional 'x' and 'y' coordinates");
500  }
501 
502  const std::string terrain_description =
503  "NetCDF terrain field '" + height_varname + "' in '" + fname + "'";
504  m_zterrain.resize(nx * ny);
505  if (!has_x) {
506  if (height_varname != "HGT_M" || !has_time_dimension ||
507  dim_names != std::vector<std::string>{"Time", "south_north", "west_east"}) {
508  amrex::Abort("NetCDF terrain field '" + height_varname + "' in '" + fname +
509  "' requires one-dimensional 'x' and 'y' coordinates; a genuine "
510  "WPS file must provide HGT_M(Time,south_north,west_east)");
511  }
512 
513  const auto require_real_attribute = [&] (const std::string& name) {
514  if (!ncf.has_attr(name)) {
515  amrex::Abort("WPS terrain file '" + fname +
516  "' is missing required global attribute '" + name + "'");
517  }
518  std::vector<double> values;
519  ncf.get_attr(name, values);
520  if (values.size() != 1 || !std::isfinite(values[0])) {
521  amrex::Abort("WPS terrain file '" + fname +
522  "' must have one finite global attribute '" + name + "'");
523  }
524  return values[0];
525  };
526  const auto require_int_attribute = [&] (const std::string& name) {
527  if (!ncf.has_attr(name)) {
528  amrex::Abort("WPS terrain file '" + fname +
529  "' is missing required global attribute '" + name + "'");
530  }
531  std::vector<int> values;
532  ncf.get_attr(name, values);
533  if (values.size() != 1) {
534  amrex::Abort("WPS terrain file '" + fname +
535  "' must have one global attribute '" + name + "'");
536  }
537  return values[0];
538  };
539 
540  const int map_proj = require_int_attribute("MAP_PROJ");
541  // Projection 6 (latitude/longitude) is deliberately excluded.
542  // WPS writes DX/DY in degrees for that projection, whereas
543  // everything below consumes them as metres -- both the
544  // geometry-consistency check and the m_xterrain/m_yterrain
545  // axes built from ProbLo + (i+0.5)*DX. Accepting it would
546  // either abort with a misleading "grid does not match"
547  // message, or, if prob_hi were specified in degrees to get
548  // past that check, silently place metre-valued terrain
549  // heights on a degree-spaced horizontal grid and corrupt the
550  // terrain-fitted metrics with no warning.
551  if (map_proj != 1 && map_proj != 2 && map_proj != 3) {
552  std::string reason =
553  (map_proj == 6)
554  ? "; latitude/longitude WPS grids are not supported because their "
555  "DX/DY are in degrees rather than metres"
556  : "; supported projections are 1 (Lambert), 2 (polar), "
557  "and 3 (Mercator)";
558  amrex::Abort("WPS terrain file '" + fname + "' uses unsupported MAP_PROJ=" +
559  std::to_string(map_proj) + reason);
560  }
561  const double cen_lat = require_real_attribute("CEN_LAT");
562  const double cen_lon = require_real_attribute("CEN_LON");
563  const double stand_lon = require_real_attribute("STAND_LON");
564  const double wps_dx = require_real_attribute("DX");
565  const double wps_dy = require_real_attribute("DY");
566  if (wps_dx <= 0.0 || wps_dy <= 0.0 || std::abs(cen_lat) > 90.0 ||
567  std::abs(cen_lon) > 360.0 || std::abs(stand_lon) > 360.0) {
568  amrex::Abort("WPS terrain file '" + fname +
569  "' has invalid projection or grid metadata");
570  }
571  // TRUELAT1 is required by all three remaining projections.
572  const double truelat1 = require_real_attribute("TRUELAT1");
573  if (std::abs(truelat1) > 90.0) {
574  amrex::Abort("WPS terrain file '" + fname +
575  "' has invalid TRUELAT1");
576  }
577  if (map_proj == 1) {
578  const double truelat2 = require_real_attribute("TRUELAT2");
579  if (std::abs(truelat2) > 90.0) {
580  amrex::Abort("WPS terrain file '" + fname +
581  "' has invalid TRUELAT2");
582  }
583  }
584 
585  const int wps_nx = require_int_attribute("WEST-EAST_GRID_DIMENSION");
586  const int wps_ny = require_int_attribute("SOUTH-NORTH_GRID_DIMENSION");
587  if (wps_nx != nx + 1 || wps_ny != ny + 1) {
588  amrex::Abort("WPS terrain file '" + fname +
589  "' has grid dimensions inconsistent with HGT_M: expected " +
590  std::to_string(nx + 1) + " x " + std::to_string(ny + 1));
591  }
592 
593  const auto validate_wps_coordinate = [&] (const std::string& name) {
594  if (!ncf.has_var(name)) {
595  amrex::Abort("WPS terrain file '" + fname +
596  "' is missing required coordinate variable '" + name + "'");
597  }
598  const auto coordinate = ncf.var(name);
599  if (coordinate.shape() != dims ||
600  coordinate.dimnames() != dim_names) {
601  amrex::Abort("WPS terrain coordinate '" + name + "' in '" + fname +
602  "' must have dimensions (Time,south_north,west_east) "
603  "matching HGT_M");
604  }
605  amrex::Vector<amrex::Real> values(nx * ny);
606  const std::vector<size_t> start{0, 0, 0};
607  const std::vector<size_t> count{
608  1, static_cast<size_t>(ny), static_cast<size_t>(nx)};
609  coordinate.get(values.data(), start, count);
610  if (!std::all_of(values.begin(), values.end(),
611  [] (amrex::Real value) { return std::isfinite(value); })) {
612  amrex::Abort("WPS terrain coordinate '" + name + "' in '" + fname +
613  "' contains nonfinite values");
614  }
615  };
616  validate_wps_coordinate("XLAT_M");
617  validate_wps_coordinate("XLONG_M");
618 
619  const auto dx = geom.CellSizeArray();
620  const auto close_enough = [] (amrex::Real lhs, double rhs) {
621  const amrex::Real scale = std::max(amrex::Real(1.0),
622  std::abs(static_cast<amrex::Real>(rhs)));
623  return std::abs(lhs - static_cast<amrex::Real>(rhs)) <=
624  amrex::Real(1.0e-6) * scale;
625  };
626  if (geom.Domain().length(0) != nx || geom.Domain().length(1) != ny ||
627  !close_enough(dx[0], wps_dx) || !close_enough(dx[1], wps_dy) ||
628  !close_enough(geom.ProbHi(0) - geom.ProbLo(0), wps_dx * nx) ||
629  !close_enough(geom.ProbHi(1) - geom.ProbLo(1), wps_dy * ny)) {
630  amrex::Abort("WPS terrain grid does not match the ERF Geometry; "
631  "HGT_M dimensions, DX/DY, and the ERF domain extent must agree");
632  }
633 
634  // WPS HGT_M/XLAT_M/XLONG_M are mass-point fields. Their
635  // logical grid is anchored at the ERF lower corner, with the
636  // first mass point half a cell from that corner. The
637  // explicit clamp below is the documented one-sided boundary
638  // conversion from mass points to ERF terrain nodes.
639  m_xterrain.resize(nx);
640  m_yterrain.resize(ny);
641  for (int i = 0; i < nx; ++i) {
642  m_xterrain[i] = geom.ProbLo(0) +
643  (static_cast<amrex::Real>(i) + amrex::Real(0.5)) *
644  static_cast<amrex::Real>(wps_dx);
645  }
646  for (int j = 0; j < ny; ++j) {
647  m_yterrain[j] = geom.ProbLo(1) +
648  (static_cast<amrex::Real>(j) + amrex::Real(0.5)) *
649  static_cast<amrex::Real>(wps_dy);
650  }
651  const std::vector<size_t> start{0, 0, 0};
652  const std::vector<size_t> count{
653  1, static_cast<size_t>(ny), static_cast<size_t>(nx)};
654  var.get(m_zterrain.data(), start, count);
655  mass_point_terrain = 1;
656  } else {
657  const auto x_shape = ncf.var("x").shape();
658  const auto y_shape = ncf.var("y").shape();
659  if (x_shape.size() != 1 || x_shape[0] != static_cast<std::size_t>(nx)) {
660  amrex::Abort("NetCDF terrain x coordinate in '" + fname +
661  "' must be one-dimensional with length " + std::to_string(nx));
662  }
663  if (y_shape.size() != 1 || y_shape[0] != static_cast<std::size_t>(ny)) {
664  amrex::Abort("NetCDF terrain y coordinate in '" + fname +
665  "' must be one-dimensional with length " + std::to_string(ny));
666  }
667 
668  m_xterrain.resize(nx);
669  m_yterrain.resize(ny);
670  ncf.var("x").get(m_xterrain.data());
671  ncf.var("y").get(m_yterrain.data());
672 
673  amrex::Real x_origin, x_spacing, y_origin, y_spacing;
674  std::string coordinate_error = erf_grid_utils::validate_uniform_axis(
675  m_xterrain, nx, "x", terrain_description, x_origin, x_spacing);
676  if (coordinate_error.empty()) {
677  coordinate_error = erf_grid_utils::validate_uniform_axis(
678  m_yterrain, ny, "y", terrain_description, y_origin, y_spacing);
679  }
680  if (!coordinate_error.empty()) {
681  amrex::Abort(coordinate_error);
682  }
683 
684  if (has_time_dimension) {
685  const std::vector<size_t> start{0, 0, 0};
686  const std::vector<size_t> count{
687  1, static_cast<size_t>(ny), static_cast<size_t>(nx)};
688  var.get(m_zterrain.data(), start, count);
689  } else {
690  var.get(m_zterrain.data());
691  }
692  }
693  if (!std::all_of(m_zterrain.begin(), m_zterrain.end(),
694  [] (amrex::Real value) { return std::isfinite(value); })) {
695  amrex::Abort(terrain_description + " contains nonfinite height values");
696  }
697  ncf.close();
698 
699  amrex::Print() << " Grid size: " << nx << " x " << ny << "\n"
700  << " X range: [" << m_xterrain[0] << ", " << m_xterrain[nx-1] << "]\n"
701  << " Y range: [" << m_yterrain[0] << ", " << m_yterrain[ny-1] << "]\n"
702  << " Height range: ["
703  << *std::min_element(m_zterrain.begin(), m_zterrain.end()) << ", "
704  << *std::max_element(m_zterrain.begin(), m_zterrain.end()) << "]\n";
705  }
706 
707  // Broadcast to all MPI ranks
708  amrex::ParallelDescriptor::Bcast(&nx, 1, amrex::ParallelDescriptor::IOProcessorNumber());
709  amrex::ParallelDescriptor::Bcast(&ny, 1, amrex::ParallelDescriptor::IOProcessorNumber());
710  amrex::ParallelDescriptor::Bcast(&mass_point_terrain, 1,
711  amrex::ParallelDescriptor::IOProcessorNumber());
712 
713  if (!amrex::ParallelDescriptor::IOProcessor()) {
714  m_xterrain.resize(nx);
715  m_yterrain.resize(ny);
716  m_zterrain.resize(nx * ny);
717  }
718 
719  amrex::ParallelDescriptor::Bcast(m_xterrain.data(), nx, amrex::ParallelDescriptor::IOProcessorNumber());
720  amrex::ParallelDescriptor::Bcast(m_yterrain.data(), ny, amrex::ParallelDescriptor::IOProcessorNumber());
721  amrex::ParallelDescriptor::Bcast(m_zterrain.data(), nx * ny, amrex::ParallelDescriptor::IOProcessorNumber());
722 
723  // Copy to GPU
724  amrex::Gpu::DeviceVector<amrex::Real> d_xterrain(nx), d_yterrain(ny), d_zterrain(nx * ny);
725  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_xterrain.begin(), m_xterrain.end(), d_xterrain.begin());
726  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_yterrain.begin(), m_yterrain.end(), d_yterrain.begin());
727  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_zterrain.begin(), m_zterrain.end(), d_zterrain.begin());
728 
729  amrex::Real* d_xt = d_xterrain.data();
730  amrex::Real* d_yt = d_yterrain.data();
731  amrex::Real* d_zt = d_zterrain.data();
732 
733  auto dx_arr = geom.CellSizeArray();
734  auto prob_lo = geom.ProbLoArray();
735 
736  int ilo = geom.Domain().smallEnd(0);
737  int jlo = geom.Domain().smallEnd(1);
738  int klo = geom.Domain().smallEnd(2);
739  int ihi = geom.Domain().bigEnd(0) + 1;
740  int jhi = geom.Domain().bigEnd(1) + 1;
741 
742  amrex::Box zbx = terrain_fab.box();
743  amrex::Array4<amrex::Real> const& z_arr = terrain_fab.array();
744  const amrex::Real terrain_dx = m_xterrain[1] - m_xterrain[0];
745  const amrex::Real terrain_dy = m_yterrain[1] - m_yterrain[0];
746 
747  if (!mass_point_terrain && !zbx.isEmpty()) {
748  amrex::Box target_box = zbx & amrex::convert(geom.Domain(), zbx.ixType());
749  if (!target_box.isEmpty()) {
750  target_box.setSmall(2, zbx.smallEnd(2));
751  target_box.setBig(2, zbx.smallEnd(2));
752  amrex::ReduceOps<amrex::ReduceOpSum, amrex::ReduceOpSum> reduce_op;
753  amrex::ReduceData<amrex::Long, amrex::Long> reduce_data(reduce_op);
754  reduce_op.eval(target_box, reduce_data,
755  [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/) -> amrex::GpuTuple<amrex::Long, amrex::Long> {
756  const amrex::Real x = prob_lo[0] + static_cast<amrex::Real>(i) * dx_arr[0];
757  const amrex::Real y = prob_lo[1] + static_cast<amrex::Real>(j) * dx_arr[1];
758  const auto x_stencil = erf_grid_utils::uniform_interpolation_stencil(
759  x, d_xt[0], terrain_dx, nx);
760  const auto y_stencil = erf_grid_utils::uniform_interpolation_stencil(
761  y, d_yt[0], terrain_dy, ny);
762  const amrex::Long outside =
763  (x_stencil.inside && y_stencil.inside) ? amrex::Long(0) : amrex::Long(1);
764  return {amrex::Long(1), outside};
765  });
766  // No parallel reduction here: init_terrain_surface is called
767  // on every rank with its own private full-domain FArrayBox,
768  // not a distributed MultiFab, so every rank has already
769  // counted the whole domain. Summing across ranks would
770  // simply multiply both counts by the rank count.
771  const auto local = reduce_data.value();
772  const amrex::Long total_targets = amrex::get<0>(local);
773  const amrex::Long outside_targets = amrex::get<1>(local);
774  if (amrex::ParallelDescriptor::IOProcessor() && outside_targets > 0) {
775  const amrex::Real source_xhi = m_xterrain[nx-1];
776  const amrex::Real source_yhi = m_yterrain[ny-1];
777  const amrex::Real target_xlo = geom.ProbLo(0);
778  const amrex::Real target_ylo = geom.ProbLo(1);
779  const amrex::Real target_xhi = geom.ProbHi(0);
780  const amrex::Real target_yhi = geom.ProbHi(1);
781  const amrex::Real percentage = total_targets > 0
782  ? amrex::Real(100.0) * static_cast<amrex::Real>(outside_targets) /
783  static_cast<amrex::Real>(total_targets) : amrex::Real(0.0);
784  amrex::Print() << "WARNING: Terrain source grid does not cover ERF terrain nodes: outside "
785  << outside_targets << " of " << total_targets << " ("
786  << percentage << "%). Source extent x=[" << m_xterrain[0]
787  << ", " << source_xhi << "] y=[" << m_yterrain[0] << ", "
788  << source_yhi << "]; target extent x=[" << target_xlo << ", "
789  << target_xhi << "] y=[" << target_ylo << ", " << target_yhi
790  << "]. Outside nodes are set to zero.\n";
791  }
792  }
793  }
794 
795  amrex::ParallelFor(zbx, [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/) noexcept
796  {
797  int ii = amrex::min(amrex::max(i, ilo), ihi);
798  int jj = amrex::min(amrex::max(j, jlo), jhi);
799 
800  amrex::Real x = prob_lo[0] + static_cast<amrex::Real>(ii) * dx_arr[0];
801  amrex::Real y = prob_lo[1] + static_cast<amrex::Real>(jj) * dx_arr[1];
802 
803  const amrex::Real dx_t = d_xt[1] - d_xt[0];
804  const amrex::Real dy_t = d_yt[1] - d_yt[0];
805  if (mass_point_terrain) {
806  // A WPS mass grid does not contain the ERF terrain nodes at
807  // the four outer edges. Hold the nearest mass value there;
808  // this is intentional, finite one-sided staggering rather
809  // than accidental extrapolation.
810  x = amrex::min(amrex::max(x, d_xt[0]), d_xt[nx-1]);
811  y = amrex::min(amrex::max(y, d_yt[0]), d_yt[ny-1]);
812  }
813  const auto x_stencil = erf_grid_utils::uniform_interpolation_stencil(
814  x, d_xt[0], dx_t, nx);
815  const auto y_stencil = erf_grid_utils::uniform_interpolation_stencil(
816  y, d_yt[0], dy_t, ny);
817 
818  if (x_stencil.inside && y_stencil.inside) {
819  const int i_t = x_stencil.lower;
820  const int j_t = y_stencil.lower;
821  const amrex::Real wx = x_stencil.weight;
822  const amrex::Real wy = y_stencil.weight;
823 
824  // Data is stored [y, x] in NetCDF
825  amrex::Real z00 = d_zt[ j_t * nx + i_t ];
826  amrex::Real z10 = d_zt[ j_t * nx + (i_t + 1)];
827  amrex::Real z01 = d_zt[(j_t + 1) * nx + i_t ];
828  amrex::Real z11 = d_zt[(j_t + 1) * nx + (i_t + 1)];
829 
830  z_arr(i, j, klo) = (amrex::Real(1.0) - wx) * (amrex::Real(1.0) - wy) * z00 +
831  wx * (amrex::Real(1.0) - wy) * z10 +
832  (amrex::Real(1.0) - wx) * wy * z01 +
833  wx * wy * z11;
834  } else {
835  z_arr(i, j, klo) = amrex::Real(0.0);
836  }
837  });
838 
839  // The interpolation kernel dereferences the device vectors above;
840  // synchronize before their scope ends and their storage is released.
841  amrex::Gpu::synchronize();
842  }
843 #endif
844 
845  void
846  read_custom_terrain(const std::string& fname,
847  const bool is_usgs,
848  const amrex::Geometry& geom,
849  amrex::FArrayBox& terrain_fab,
850  const double& /*time*/)
851  {
852  amrex::Vector<amrex::Real> m_xterrain,m_yterrain,m_zterrain;
853 
854  int nx = 0; int ny = 0;
855 
856  if (amrex::ParallelDescriptor::IOProcessor()) {
857  // Read terrain file
858  amrex::Print()<<"Reading terrain file: "<< fname<< std::endl;
859  std::ifstream file(fname);
860 
861  if (!file.is_open()) {
862  amrex::Abort("Error: Could not open the file " + fname+ "\n");
863  }
864 
865  // Check if file is empty
866  if (file.peek() == std::ifstream::traits_type::eof()) {
867  amrex::Abort("Error: The file " + fname+ " is empty.\n");
868  }
869 
870  amrex::Real value1,value2,value3;
871 
872  if (is_usgs) {
873  amrex::Real lat_min, lon_min;
874 
875  file >> lon_min >> lat_min;
876  if(std::fabs(lon_min) > amrex::Real(180.0)) {
877  amrex::Error("The value of longitude for entry in the first line in " + fname
878  + " should not exceed amrex::Real(180.) It is " + std::to_string(lon_min));
879  }
880  if(std::fabs(lat_min) > amrex::Real(90.0)) {
881  amrex::Error("The value of latitude for entry in the first line in " + fname
882  + " should not exceed amrex::Real(90.) It is " + std::to_string(lat_min));
883  }
884 
885  file >> nx >> ny;
886 
887  int counter = 0;
888  while (file >> value1 >> value2 >> value3) {
889  m_xterrain.push_back(value1);
890  if(counter%nx==0) {
891  m_yterrain.push_back(value2);
892  }
893  m_zterrain.push_back(value3);
894  counter += 1;
895  }
896  AMREX_ASSERT(m_xterrain.size() == static_cast<long int>(nx*ny));
897  AMREX_ASSERT(m_yterrain.size() == static_cast<long int>(ny));
898  AMREX_ASSERT(m_zterrain.size() == static_cast<long int>(nx*ny));
899 
900  } else {
901  int cnt = 1;
902  nx = erf_get_single_value<int>(file,cnt); cnt++;
903  ny = erf_get_single_value<int>(file,cnt); cnt++;
904  amrex::Print()<<"Expecting " << nx << " values of x, " <<
905  ny << " values of y, and " <<
906  nx*ny << " values of z" << std::endl;
907  AMREX_ALWAYS_ASSERT(nx > 0);
908  AMREX_ALWAYS_ASSERT(ny > 0);
909  m_xterrain.resize(nx);
910  m_yterrain.resize(ny);
911  m_zterrain.resize(nx * ny);
912  for (int n = 0; n < nx; n++) {
913  m_xterrain[n] = erf_get_single_value<amrex::Real>(file,cnt);
914  cnt++;
915  }
916  for (int n = 0; n < ny; n++) {
917  m_yterrain[n] = erf_get_single_value<amrex::Real>(file,cnt);
918  cnt++;
919  }
920  for (int n = 0; n < nx * ny; n++) {
921  m_zterrain[n] = erf_get_single_value<amrex::Real>(file,cnt);
922  cnt++;
923  }
924  }
925 
926  // Close the file after reading
927  file.close();
928  }
929 
930  amrex::ParallelDescriptor::Bcast(&nx,1,amrex::ParallelDescriptor::IOProcessorNumber());
931  amrex::ParallelDescriptor::Bcast(&ny,1,amrex::ParallelDescriptor::IOProcessorNumber());
932 
933  AMREX_ALWAYS_ASSERT(nx > 0 && ny > 0);
934  if (is_usgs) {
935  // The usgs branch below always uses a full 2x2 stencil
937  "USGS terrain file must have at least two points in each direction");
938  }
939 
940  int nz = nx * ny;
941  int nx_vals = is_usgs ? (nx * ny) : nx;
942 
943  m_xterrain.resize(nx_vals);
944  m_yterrain.resize(ny);
945  m_zterrain.resize(nz);
946 
947  amrex::ParallelDescriptor::Bcast(m_xterrain.data(),nx_vals,amrex::ParallelDescriptor::IOProcessorNumber());
948  amrex::ParallelDescriptor::Bcast(m_yterrain.data(),ny,amrex::ParallelDescriptor::IOProcessorNumber());
949  amrex::ParallelDescriptor::Bcast(m_zterrain.data(),nz,amrex::ParallelDescriptor::IOProcessorNumber());
950 
951  // Copy data to the GPU
952  amrex::Gpu::DeviceVector<amrex::Real> d_xterrain(nx_vals),d_yterrain(ny),d_zterrain(nz);
953  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_xterrain.begin(), m_xterrain.end(), d_xterrain.begin());
954  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_yterrain.begin(), m_yterrain.end(), d_yterrain.begin());
955  amrex::Gpu::copy(amrex::Gpu::hostToDevice, m_zterrain.begin(), m_zterrain.end(), d_zterrain.begin());
956 
957  amrex::Real* d_xt = d_xterrain.data();
958  amrex::Real* d_yt = d_yterrain.data();
959  amrex::Real* d_zt = d_zterrain.data();
960 
961  auto dx = geom.CellSizeArray();
962  auto ProbLoArr = geom.ProbLoArray();
963 
964  int ilo = geom.Domain().smallEnd(0);
965  int jlo = geom.Domain().smallEnd(1);
966  int klo = geom.Domain().smallEnd(2);
967  int ihi = geom.Domain().bigEnd(0) + 1;
968  int jhi = geom.Domain().bigEnd(1) + 1;
969 
970  amrex::Box zbx = terrain_fab.box();
971  amrex::Array4<amrex::Real> const& z_arr = terrain_fab.array();
972 
973  amrex::ParallelFor(zbx, [=] AMREX_GPU_DEVICE (int i, int j, int /*k*/)
974  {
975  // Clip indices for ghost cells
976  int ii = amrex::min(amrex::max(i,ilo),ihi);
977  int jj = amrex::min(amrex::max(j,jlo),jhi);
978 
979  // Location of nodes
980  amrex::Real x = ProbLoArr[0] + ii * dx[0] + amrex::Real(1e-3);
981  amrex::Real y = ProbLoArr[1] + jj * dx[1] + amrex::Real(1e-3);
982 
983  int ind11, ind12, ind21, ind22;
984  amrex::Real x1, x2, y1, y2;
985 
986  int iindex_terrain=-1;
987  int jindex_terrain=-1;
988  // *******************************************************************
989  // NOTE: usgs-format is contiguous in x
990  // *******************************************************************
991  if (is_usgs) {
992 
993  // NOTE: the searches below must distinguish "the node is below the first
994  // table value" (bracket index -1) from "no table value exceeds the
995  // node" (search never triggered), so we can not use the initial
996  // value of -1 as the not-found flag
997  bool jfound = false;
998  for (int it = 0; it < ny && !jfound; it++) {
999  if (d_yt[it] > y) {
1000  jindex_terrain = it-1; jfound = true;
1001  }
1002  }
1003  if (!jfound) {
1004  jindex_terrain = ny-1;
1005  }
1006  // Keep the 2x2 stencil inside the table
1007  jindex_terrain = amrex::min(amrex::max(jindex_terrain,0), ny-2);
1008 
1009  int gstart = (jindex_terrain )*nx;
1010  int gend = (jindex_terrain+1)*nx-1;
1011  bool ifound = false;
1012  for (int it = gstart; it <= gend && !ifound; it++) {
1013  if (d_xt[it] > x) {
1014  iindex_terrain = it-gstart-1; ifound = true;
1015  }
1016  }
1017  if (!ifound) {
1018  iindex_terrain = nx-1;
1019  }
1020  // Keep the 2x2 stencil inside the table
1021  iindex_terrain = amrex::min(amrex::max(iindex_terrain,0), nx-2);
1022 
1023  // Define the four values to interpolate between
1024  ind11 = jindex_terrain*nx + iindex_terrain; // (x1,y1)
1025  ind12 = ind11+nx; // (x1,y2)
1026  ind21 = ind11+1; // (x2,y1)
1027  ind22 = ind12+1; // (x2,y2)
1028 
1029  x1 = d_xt[ind11];
1030  x2 = d_xt[ind21];
1031  y1 = d_yt[jindex_terrain];
1032  y2 = d_yt[jindex_terrain+1];
1033 
1034  amrex::Real denom = (x2-x1)*(y2-y1);
1035 
1036  if (denom == amrex::Real(0.0)) {
1037  // Degenerate cell (repeated x or y in the table) -- use the corner value
1038  z_arr(i,j,klo) = d_zt[ind11];
1039  } else {
1040  amrex::Real w_11 = (x2-x)*(y2-y)/denom; // (x1,y1)
1041  amrex::Real w_12 = (x2-x)*(y-y1)/denom; // (x1,y2)
1042  amrex::Real w_21 = (x-x1)*(y2-y)/denom; // (x2,y1)
1043  amrex::Real w_22 = (x-x1)*(y-y1)/denom; // (x2,y2)
1044 
1045  // Do bilinear interpolation
1046  z_arr(i,j,klo) = w_11*d_zt[ind11] + w_12*d_zt[ind12] + w_21*d_zt[ind21] + w_22*d_zt[ind22];
1047  }
1048 
1049  } else {
1050 
1051  bool jfound = false;
1052  for (int it = 0; it < ny && !jfound; it++) {
1053  if (d_yt[it] > y) {
1054  jindex_terrain = it-1; jfound = true;
1055  }
1056  }
1057  if (!jfound) {
1058  // No table value exceeds y -- fall back to the last row
1059  jindex_terrain = ny-1;
1060  }
1061  jindex_terrain = amrex::max(jindex_terrain,0);
1062 
1063  bool ifound = false;
1064  for (int it = 0; it < nx && !ifound; it++) {
1065  if (d_xt[it] > x) {
1066  iindex_terrain = it-1; ifound = true;
1067  }
1068  }
1069  if (!ifound) {
1070  // No table value exceeds x -- fall back to the last column
1071  iindex_terrain = nx-1;
1072  }
1073  iindex_terrain = amrex::max(iindex_terrain,0);
1074 
1075  // NOTE: these must be clamped since the fallbacks above can leave
1076  // iindex_terrain = nx-1 (jindex_terrain = ny-1)
1077  int ip1 = amrex::min(iindex_terrain+1,nx-1);
1078  int jp1 = amrex::min(jindex_terrain+1,ny-1);
1079 
1080  // Define the four values to interpolate between
1081  x1 = d_xt[iindex_terrain];
1082  x2 = d_xt[ip1];
1083  y1 = d_yt[jindex_terrain];
1084  y2 = d_yt[jp1];
1085 
1086 #if 1
1087  // *******************************************************************
1088  // NOTE: this format is contiguous in y to match the AMR-Wind read
1089  // *******************************************************************
1090  ind11 = iindex_terrain * ny + jindex_terrain; // (x1,y1)
1091  ind21 = ip1 * ny + jindex_terrain; // (x2,y1)
1092 
1093  ind12 = iindex_terrain * ny + jp1; // (x1,y2)
1094  ind22 = ip1 * ny + jp1; // (x2,y2)
1095 #else
1096  // *******************************************************************
1097  // NOTE: this format is contiguous in x as an alternative
1098  // *******************************************************************
1099 
1100  ind11 = jindex_terrain * nx + iindex_terrain; // (x1,y1)
1101  ind12 = jp1 * nx + iindex_terrain; // (x1,y2)
1102 
1103  ind21 = jindex_terrain * nx + ip1; // (x2,y1)
1104  ind22 = jp1 * nx + ip1; // (x2,y2)
1105 #endif
1106 
1107  // Only interpolate in a direction if we have a non-degenerate interval there
1108  bool interp_x = (ip1 != iindex_terrain) && (x2 != x1);
1109  bool interp_y = (jp1 != jindex_terrain) && (y2 != y1);
1110 
1111  if (!interp_x && !interp_y)
1112  {
1113  z_arr(i,j,klo) = d_zt[ind11];
1114  }
1115  else if (interp_x && !interp_y)
1116  {
1117  amrex::Real w_11 = (x2-x); // (x1,y1)
1118  amrex::Real w_21 = (x-x1); // (x2,y1)
1119  amrex::Real denom = (x2-x1);
1120  z_arr(i,j,klo) = (w_11*d_zt[ind11] + w_21*d_zt[ind21])/denom;
1121  }
1122  else if (!interp_x && interp_y)
1123  {
1124  amrex::Real w_11 = (y2-y); // (x1,y1)
1125  amrex::Real w_12 = (y-y1); // (x1,y2)
1126  amrex::Real denom = (y2-y1);
1127  z_arr(i,j,klo) = (w_11*d_zt[ind11] + w_12*d_zt[ind12])/denom;
1128  }
1129  else
1130  {
1131  amrex::Real w_11 = (x2-x)*(y2-y); // (x1,y1)
1132  amrex::Real w_21 = (x-x1)*(y2-y); // (x2,y1)
1133  amrex::Real w_12 = (x2-x)*(y-y1); // (x1,y2)
1134  amrex::Real w_22 = (x-x1)*(y-y1); // (x2,y2)
1135  amrex::Real denom = (x2-x1)*(y2-y1);
1136  z_arr(i,j,klo) = (w_11*d_zt[ind11] + w_12*d_zt[ind12] + w_21*d_zt[ind21] + w_22*d_zt[ind22]) / denom;
1137  }
1138  } // usgs?
1139  });
1140  }
1141 
1142  /**
1143  * Function to perform custom initialization of terrain
1144  *
1145  * Note: Terrain functionality can also be used to provide grid stretching.
1146  *
1147  * @param[in] geom container for geometric information
1148  * @param[out] terrain_mf height coordinate at nodes
1149  * @param[in] time current time
1150  */
1151  virtual void
1152  init_custom_terrain (const amrex::Geometry& geom,
1153  amrex::FArrayBox& terrain_fab,
1154  const double& time)
1155  {
1156  std::string custom_terrain_type = "None";
1157  amrex::ParmParse pp_prob("prob"); pp_prob.queryAdd("custom_terrain_type",custom_terrain_type);
1158 
1159  if (custom_terrain_type != "None")
1160  {
1161  amrex::Print() << "Calling custom terrain initialization" << std::endl;
1162  init_my_custom_terrain(geom,terrain_fab,time);
1163 
1164  } else {
1165  amrex::Print() << "Initializing flat terrain" << std::endl;
1166  terrain_fab.template setVal<amrex::RunOn::Device>(0);
1167 
1168  if (SolverChoice::mesh_type == MeshType::VariableDz) {
1169  SolverChoice::set_mesh_type(MeshType::StretchedDz);
1170  amrex::Print() << "Resetting mesh type to StretchedDz" << std::endl;
1171  }
1172  }
1173  }
1174 
1175 #ifdef ERF_USE_TERRAIN_VELOCITY
1176  virtual amrex::Real compute_terrain_velocity(const double /*time*/)
1177  {
1178  amrex::Error("Should never call compute_terrain_velocity for "+name()+" problem");
1179  }
1180 #endif
1181 
1182  /**
1183  * Function to define the quantities needed to impose Rayleigh damping
1184  *
1185  * @param[out] rayleigh_ptrs = {strength of Rayleigh damping, reference values for xvel/yvel/zvel/theta used to define Rayleigh damping}
1186  * @param[in] geom container for geometric information
1187  * @param[in] z_phys_cc height coordinate at cell centers
1188  */
1189  virtual void
1190  erf_init_rayleigh (amrex::Vector<amrex::Vector<amrex::Real> >& /*rayleigh_ptrs*/,
1191  amrex::Geometry const& /*geom*/,
1192  std::unique_ptr<amrex::MultiFab>& /*z_phys_nd*/,
1193  amrex::Real /*zdamp*/)
1194  {
1195  // Default which does no harm
1196  }
1197 
1198 protected:
1199  // Struct to store problem parameters
1201 
1202  /**
1203  * Function to update default base parameters, currently only used for
1204  * init_type == InitType::Uniform
1205  */
1208  base_parms.T_0 = T_0;
1209  }
1210 
1211  std::string name() {
1212  std::string prob_name;
1213  amrex::ParmParse pp("erf");
1214  pp.get("prob_name",prob_name); return prob_name;
1215  }
1216 };
1217 
1218 
1219 /**
1220  * Function to init the physical bounds of the domain
1221  * and instantiate a Problem derived from ProblemBase
1222 */
1223 extern std::unique_ptr<ProblemBase> amrex_probinit (const amrex_real* problo,
1224  const amrex_real* probhi) AMREX_ATTRIBUTE_WEAK;
1225 #endif
@ wbar
Definition: ERF_DataStruct.H:179
auto probhi
Definition: ERF_InitCustomPertVels_ABL.H:37
auto problo
Definition: ERF_InitCustomPertVels_ABL.H:36
const int nx
Definition: ERF_InitCustomPertVels_CloudChamber.H:14
const int ny
Definition: ERF_InitCustomPertVels_CloudChamber.H:15
const int klo
Definition: ERF_InitCustomPert_ABL.H:75
Real rho_0
Definition: ERF_InitCustomPert_ABL.H:18
ParmParse pp_prob("prob")
Real T_0
Definition: ERF_InitCustomPert_ABL.H:19
const Real dx
Definition: ERF_InitCustomPert_ABL.H:44
ParmParse pp("prob")
const int khi
Definition: ERF_InitCustomPert_Bubble.H:21
AMREX_ALWAYS_ASSERT(bx.length()[2]==khi+1)
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(m_cloud_chamber_config.active, "Cloud Chamber: initializer reached without a parsed configuration")
const GpuArray< Real, AMREX_SPACEDIM > prob_lo
Definition: ERF_InitCustomPert_CloudChamber.H:33
ParallelFor(fab_box, [=] AMREX_GPU_DEVICE(int i, int j, int k) { qrcuten_arr(i, j, k)=Real(0);qscuten_arr(i, j, k)=Real(0);qicuten_arr(i, j, k)=Real(0);})
Dimensionless numeric literals and pure mathematical constants.
constexpr amrex::Real one
Definition: ERF_NumericalConstants.H:30
constexpr amrex::Real zero
Definition: ERF_NumericalConstants.H:29
void init_my_custom_terrain(const amrex::Geometry &geom, amrex::FArrayBox &terrain_fab, const double &time)
T erf_get_single_value(std::istream &is, int n)
Definition: ERF_ProbCommon.H:31
std::unique_ptr< ProblemBase > amrex_probinit(const amrex_real *problo, const amrex_real *probhi) AMREX_ATTRIBUTE_WEAK
amrex::Real Real
Definition: ERF_ShocInterface.H:19
Definition: ERF_ProbCommon.H:60
virtual void update_w_subsidence(const double &, amrex::Vector< amrex::Real > &wbar, amrex::Gpu::DeviceVector< amrex::Real > &d_wbar, const amrex::MultiFab &, const amrex::Geometry &geom, std::unique_ptr< amrex::MultiFab > &)
Definition: ERF_ProbCommon.H:262
void init_terrain_surface(const amrex::Geometry &geom, amrex::FArrayBox &terrain_fab, const double &time)
Definition: ERF_ProbCommon.H:358
virtual void update_geostrophic_profile(const double &, amrex::Vector< amrex::Real > &u_geos, amrex::Gpu::DeviceVector< amrex::Real > &d_u_geos, amrex::Vector< amrex::Real > &v_geos, amrex::Gpu::DeviceVector< amrex::Real > &d_v_geos, const amrex::Geometry &geom, std::unique_ptr< amrex::MultiFab > &)
Definition: ERF_ProbCommon.H:297
virtual void update_rhotheta_sources(const double &, amrex::MultiFab *src, const amrex::Geometry &, std::unique_ptr< amrex::MultiFab > &)
Definition: ERF_ProbCommon.H:195
virtual void erf_init_const_dens_and_linear_th_hse(amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::Real, std::unique_ptr< amrex::MultiFab > &)
Definition: ERF_ProbCommon.H:106
virtual void init_custom_pert_vels(const amrex::Box &, const amrex::Box &, const amrex::Box &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real const > const &, amrex::GeometryData const &, amrex::Array4< amrex::Real const > const &, amrex::Array4< amrex::Real const > const &, const SolverChoice &, const int)
Definition: ERF_ProbCommon.H:170
virtual bool terrain_is_specified()
Definition: ERF_ProbCommon.H:399
virtual void erf_init_const_dens_hse(amrex::MultiFab &)
Definition: ERF_ProbCommon.H:92
virtual void init_custom_terrain(const amrex::Geometry &geom, amrex::FArrayBox &terrain_fab, const double &time)
Definition: ERF_ProbCommon.H:1152
virtual void erf_init_dens_hse_dry(amrex::MultiFab &, std::unique_ptr< amrex::MultiFab > &, std::unique_ptr< amrex::MultiFab > &, amrex::Geometry const &, const amrex::Vector< amrex::Real > &, bool, bool)
Definition: ERF_ProbCommon.H:77
virtual void update_rhoqt_sources(const double &, amrex::MultiFab *qsrc, const amrex::Geometry &, std::unique_ptr< amrex::MultiFab > &)
Definition: ERF_ProbCommon.H:227
void init_buildings_surface(const amrex::Geometry &geom, amrex::FArrayBox &buildings_fab, const double &time)
Definition: ERF_ProbCommon.H:333
void read_custom_terrain(const std::string &fname, const bool is_usgs, const amrex::Geometry &geom, amrex::FArrayBox &terrain_fab, const double &)
Definition: ERF_ProbCommon.H:846
virtual void erf_init_rayleigh(amrex::Vector< amrex::Vector< amrex::Real > > &, amrex::Geometry const &, std::unique_ptr< amrex::MultiFab > &, amrex::Real)
Definition: ERF_ProbCommon.H:1190
void init_base_parms(amrex::Real rho_0, amrex::Real T_0)
Definition: ERF_ProbCommon.H:1206
virtual ~ProblemBase()=default
virtual void erf_init_dens_hse_moist(amrex::MultiFab &, std::unique_ptr< amrex::MultiFab > &, amrex::Geometry const &)
Definition: ERF_ProbCommon.H:115
virtual void init_custom_pert(const amrex::Box &, amrex::Array4< amrex::Real const > const &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real > const &, amrex::Array4< amrex::Real const > const &, amrex::Array4< amrex::Real const > const &, amrex::GeometryData const &, amrex::Array4< amrex::Real const > const &, const SolverChoice &, const int)
Definition: ERF_ProbCommon.H:138
std::string name()
Definition: ERF_ProbCommon.H:1211
virtual void erf_init_const_dens_and_th_hse(amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::MultiFab &, amrex::Real)
Definition: ERF_ProbCommon.H:98
ProbParmDefaults base_parms
Definition: ERF_ProbCommon.H:1200
@ T
Definition: ERF_IndexDefines.H:128
std::string validate_uniform_axis(const amrex::Vector< amrex::Real > &coordinates, int expected_size, const std::string &axis_name, const std::string &field_description, amrex::Real &origin, amrex::Real &spacing)
Definition: ERF_GridUtils.H:56
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE InterpolationStencil uniform_interpolation_stencil(amrex::Real coordinate, amrex::Real origin, amrex::Real spacing, int point_count) noexcept
Definition: ERF_GridUtils.H:173
Definition: ERF_ProbCommon.H:25
amrex::Real T_0
Definition: ERF_ProbCommon.H:27
amrex::Real rho_0
Definition: ERF_ProbCommon.H:26
Definition: ERF_DataStruct.H:662
static MeshType mesh_type
Vertical mesh representation.
Definition: ERF_DataStruct.H:1958
static void set_mesh_type(MeshType new_mesh_type)
Override the globally selected mesh type.
Definition: ERF_DataStruct.H:1965