ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
WRFSurfaceFields Class Reference

#include <ERF_WRFSurfaceFields.H>

Collaboration diagram for WRFSurfaceFields:

Classes

struct  Descriptor
 
struct  HeaderLevel
 
struct  Pending
 

Public Types

enum class  Field : int {
  LAI = 0 , VEGFRA , TMN , ZNT ,
  ALBEDO , ALBBCK , SEAICE , SNOW ,
  SNOWH , TSLB , SMOIS , ZS ,
  DZS , NumFields
}
 
enum class  Kind : int { Surface , SoilField , LayerColumn }
 

Public Member Functions

void resize (int nlevs)
 
int num_levels () const
 
bool holds_any (int lev) const
 
void clear (int lev)
 
const amrex::MultiFab * get (int lev, Field id) const
 
bool has (int lev, Field id) const
 
const amrex::Vector< amrex::Real > & soil_depth (int lev) const
 
const amrex::Vector< amrex::Real > & soil_thickness (int lev) const
 
void set_soil_layers (int lev, Field id, const amrex::FArrayBox &src)
 
void fill (int lev, Field id, const amrex::BoxArray &ba2d, const amrex::DistributionMapping &dm, const amrex::IntVect &ng, int nlayers, const amrex::FArrayBox &src, const amrex::Box &file_box)
 
void finish_level (int lev, const amrex::Periodicity &period)
 
void remake (int lev, const amrex::BoxArray &new_ba2d, const amrex::DistributionMapping &new_dm, const amrex::Periodicity &period, const amrex::IntVect &ratio, bool take_coarser_fields, int verbose=0)
 
void write_checkpoint (const std::string &checkpoint_dir, int nlevels) const
 
bool read_checkpoint (const std::string &checkpoint_dir, int nlevels, const amrex::Vector< amrex::BoxArray > &ba2d, const amrex::Vector< amrex::DistributionMapping > &dm, const amrex::IntVect &ng, const amrex::Vector< amrex::Periodicity > &period, const amrex::Vector< amrex::IntVect > &ratio)
 
void write_header (std::ostream &os, int nlevels) const
 

Static Public Member Functions

static const std::array< Descriptor, num_fields > & catalog ()
 
static const Descriptor * find (const std::string &nc_name)
 
static bool has_soil_layers (const std::string &nc_name)
 
static bool parse_header (std::istream &is, amrex::Vector< HeaderLevel > &out)
 
static void fill_ghost_cells (amrex::MultiFab &mf, const amrex::Periodicity &period)
 

Static Public Attributes

static constexpr int num_fields = static_cast<int>(Field::NumFields)
 
static constexpr const char * checkpoint_header_name = "WRFSurfaceFieldsHeader"
 

Private Member Functions

void drop (int lev, Field id)
 
std::unique_ptr< amrex::MultiFab > on_grids (int lev, Field id, const amrex::MultiFab *src, const amrex::BoxArray &ba2d, const amrex::DistributionMapping &dm, const amrex::IntVect &ng, const amrex::Periodicity &period, const amrex::IntVect &ratio) const
 

Private Attributes

amrex::Vector< std::array< std::unique_ptr< amrex::MultiFab >, num_fields > > m_fields
 
amrex::Vector< std::array< Pending, num_fields > > m_pending
 
amrex::Vector< amrex::Vector< amrex::Real > > m_soil_depth
 
amrex::Vector< amrex::Vector< amrex::Real > > m_soil_thickness
 

Member Enumeration Documentation

◆ Field

enum WRFSurfaceFields::Field : int
strong

The variables, in the order they are requested from the file.

Enumerator
LAI 

leaf area index [m2/m2]

VEGFRA 

vegetation fraction [percent]

TMN 

soil temperature at the lower boundary [K]

ZNT 

roughness length [m]; in wrfout files, not in a real.exe wrfinput

ALBEDO 

surface albedo [1]; in wrfout files, not in a real.exe wrfinput

ALBBCK 

background (snow-free) albedo [1]; what a real.exe wrfinput holds

SEAICE 

sea ice flag [1]

SNOW 

snow water equivalent [kg/m2]

SNOWH 

snow depth [m]

TSLB 

soil temperature, one component per soil layer, top layer first [K]

SMOIS 

soil moisture, one component per soil layer, top layer first [m3/m3]

ZS 

depth of the center of each soil layer, one column for the level [m]

DZS 

thickness of each soil layer, one column for the level [m]

NumFields 
50  : int {
51  LAI = 0, ///< leaf area index [m2/m2]
52  VEGFRA, ///< vegetation fraction [percent]
53  TMN, ///< soil temperature at the lower boundary [K]
54  ZNT, ///< roughness length [m]; in wrfout files, not in a real.exe wrfinput
55  ALBEDO, ///< surface albedo [1]; in wrfout files, not in a real.exe wrfinput
56  ALBBCK, ///< background (snow-free) albedo [1]; what a real.exe wrfinput holds
57  SEAICE, ///< sea ice flag [1]
58  SNOW, ///< snow water equivalent [kg/m2]
59  SNOWH, ///< snow depth [m]
60  TSLB, ///< soil temperature, one component per soil layer, top layer first [K]
61  SMOIS, ///< soil moisture, one component per soil layer, top layer first [m3/m3]
62  ZS, ///< depth of the center of each soil layer, one column for the level [m]
63  DZS, ///< thickness of each soil layer, one column for the level [m]
64  NumFields
65  };

◆ Kind

enum WRFSurfaceFields::Kind : int
strong

How a variable is laid out in the file.

Enumerator
Surface 

one value per column

SoilField 

one value per column and soil layer

LayerColumn 

one value per soil layer, the same for every column (ZS, DZS)

70  : int {
71  Surface, ///< one value per column
72  SoilField, ///< one value per column and soil layer
73  LayerColumn ///< one value per soil layer, the same for every column (ZS, DZS)
74  };

Member Function Documentation

◆ catalog()

const std::array< WRFSurfaceFields::Descriptor, WRFSurfaceFields::num_fields > & WRFSurfaceFields::catalog ( )
static

The one list of the variables. The reader asks the file for every name in it, and takes the layout of a name from its kind.

The bounds leave out only values that cannot be the named quantity (a negative temperature, a fraction above one). A field that a hand-built file declares and leaves at zero passes; whether zero is usable is for the code that takes the field. The upper bounds of LAI, TMN, ZNT, SNOW, SNOWH, TSLB, ZS and DZS are not physical limits: they are set far above any value of the quantity so that a NetCDF fill value (9.97e36), which is finite, is left out.

58 {
59  // Not named zero and one: those are constants of ERF_NumericalConstants.H
60  constexpr Real lo0 = Real(0.0);
61  constexpr Real hi1 = Real(1.0);
62  static const std::array<Descriptor, num_fields> table{{
63  {Field::LAI, "LAI", Kind::Surface, "m2/m2", lo0, Real(100.0)},
64  {Field::VEGFRA, "VEGFRA", Kind::Surface, "%", lo0, Real(100.0)},
65  {Field::TMN, "TMN", Kind::Surface, "K", lo0, Real(1000.0)},
66  {Field::ZNT, "ZNT", Kind::Surface, "m", lo0, Real(100.0)},
67  {Field::ALBEDO, "ALBEDO", Kind::Surface, "1", lo0, hi1},
68  {Field::ALBBCK, "ALBBCK", Kind::Surface, "1", lo0, hi1},
69  {Field::SEAICE, "SEAICE", Kind::Surface, "1", lo0, hi1},
70  {Field::SNOW, "SNOW", Kind::Surface, "kg/m2", lo0, Real(1.0e6)},
71  {Field::SNOWH, "SNOWH", Kind::Surface, "m", lo0, Real(1.0e4)},
72  {Field::TSLB, "TSLB", Kind::SoilField, "K", lo0, Real(1000.0)},
73  {Field::SMOIS, "SMOIS", Kind::SoilField, "m3/m3", lo0, hi1},
74  {Field::ZS, "ZS", Kind::LayerColumn, "m", lo0, Real(1.0e4)},
75  {Field::DZS, "DZS", Kind::LayerColumn, "m", lo0, Real(1.0e4)},
76  }};
77  return table;
78 }
@ LayerColumn
one value per soil layer, the same for every column (ZS, DZS)
@ Surface
one value per column
@ SoilField
one value per column and soil layer
@ TSLB
soil temperature, one component per soil layer, top layer first [K]
@ ALBBCK
background (snow-free) albedo [1]; what a real.exe wrfinput holds
@ SMOIS
soil moisture, one component per soil layer, top layer first [m3/m3]
@ SNOWH
snow depth [m]
@ SNOW
snow water equivalent [kg/m2]
@ ALBEDO
surface albedo [1]; in wrfout files, not in a real.exe wrfinput
@ ZS
depth of the center of each soil layer, one column for the level [m]
@ VEGFRA
vegetation fraction [percent]
@ LAI
leaf area index [m2/m2]
@ TMN
soil temperature at the lower boundary [K]
@ SEAICE
sea ice flag [1]
@ ZNT
roughness length [m]; in wrfout files, not in a real.exe wrfinput
@ DZS
thickness of each soil layer, one column for the level [m]

◆ clear()

void WRFSurfaceFields::clear ( int  lev)

Drop everything held at this level. Prints one line when something was held.

110 {
111  if (lev < 0 || lev >= num_levels()) { return; }
112  if (holds_any(lev)) {
113  Print() << " wrfinput land and soil fields at level " << lev << " are dropped\n";
114  }
115  for (auto& f : m_fields[lev]) { f.reset(); }
116  m_pending[lev] = {};
117  m_soil_depth[lev].clear();
118  m_soil_thickness[lev].clear();
119 }
bool holds_any(int lev) const
Definition: ERF_WRFSurfaceFields.cpp:99
int num_levels() const
Definition: ERF_WRFSurfaceFields.H:111
amrex::Vector< amrex::Vector< amrex::Real > > m_soil_thickness
Definition: ERF_WRFSurfaceFields.H:312
amrex::Vector< amrex::Vector< amrex::Real > > m_soil_depth
Definition: ERF_WRFSurfaceFields.H:311
amrex::Vector< std::array< Pending, num_fields > > m_pending
Definition: ERF_WRFSurfaceFields.H:309
amrex::Vector< std::array< std::unique_ptr< amrex::MultiFab >, num_fields > > m_fields
Definition: ERF_WRFSurfaceFields.H:308

◆ drop()

void WRFSurfaceFields::drop ( int  lev,
Field  id 
)
private
123 {
124  if (id == Field::ZS) {
125  m_soil_depth[lev].clear();
126  } else if (id == Field::DZS) {
127  m_soil_thickness[lev].clear();
128  } else {
129  m_fields[lev][static_cast<int>(id)].reset();
130  }
131 }
DiagnosticID id
Definition: ERF_Plotfile2DWaterPath.cpp:28

◆ fill()

void WRFSurfaceFields::fill ( int  lev,
Field  id,
const amrex::BoxArray &  ba2d,
const amrex::DistributionMapping &  dm,
const amrex::IntVect &  ng,
int  nlayers,
const amrex::FArrayBox &  src,
const amrex::Box &  file_box 
)

Copy the part of one field that one file covers. Every rank calls it, once per file of the level; no MPI call is made here.

The valid cells of the level inside file_box take the file's values. A soil field gets one component per layer, in the file's order. The values are counted against the catalog range here; the report, the decision and the ghost cells are left to finish_level().

Parameters
levlevel
idfield (not ZS or DZS)
ba2dthe level's grids, one cell thick in z
dmthe level's distribution
ngghost cells of the stored field (none in z)
nlayersnumber of soil layers of the variable in the file (1 for a surface field); the same on every rank
srcthis rank's part of the field as read; memory a device kernel can read (the reader's fab); its low z index is the first layer
file_boxthe columns this file covers at this level (z is ignored)
212 {
213  AMREX_ALWAYS_ASSERT(lev >= 0 && lev < num_levels());
214  const int idx = static_cast<int>(id);
215  const Descriptor& d = catalog()[idx];
217  Pending& p = m_pending[lev][idx];
218  if (p.conflict) { return; }
219 
220  const int ncomp = (d.kind == Kind::SoilField) ? nlayers : 1;
221  AMREX_ALWAYS_ASSERT(ncomp >= 1);
222  auto& mf = m_fields[lev][idx];
223  if (!p.read) {
224  // The first file of the level that holds the variable
225  mf = std::make_unique<MultiFab>(ba2d, dm, ncomp, ng);
226  // Defined everywhere, also where no file covers the level (reported later)
227  mf->setVal(Real(0.0));
228  p.read = true;
229  } else if (mf->nComp() != ncomp) {
230  // The layer count is the file's metadata: every rank sees the same disagreement
231  p.conflict = true;
232  return;
233  }
234 
235  const Box& sbx = src.box();
236  const int klo = sbx.ok() ? sbx.smallEnd(2) : 0;
237  const Real lo = d.lo;
238  const Real hi = d.hi;
239  constexpr Real big = std::numeric_limits<Real>::max();
240 
241  ReduceOps<ReduceOpSum, ReduceOpSum, ReduceOpSum, ReduceOpMin, ReduceOpMax> reduce_op;
242  ReduceData<Long, Long, Long, Real, Real> reduce_data(reduce_op);
243  using ReduceTuple = typename decltype(reduce_data)::Type;
244 
245  for (MFIter mfi(*mf, TilingIfNotGPU()); mfi.isValid(); ++mfi) {
246  // The valid columns of this box that the file covers
247  Box bx = mfi.tilebox();
248  for (int dir = 0; dir < 2; ++dir) {
249  bx.setSmall(dir, amrex::max(bx.smallEnd(dir), file_box.smallEnd(dir)));
250  bx.setBig (dir, amrex::min(bx.bigEnd(dir), file_box.bigEnd(dir)));
251  }
252  if (!bx.ok()) { continue; }
253 
254  // The source is tested on the host and not read where it does not reach. (Its
255  // index type in z differs from the field's for a soil variable, so the test is
256  // made index by index.)
257  const bool covered = sbx.ok() &&
258  sbx.smallEnd(0) <= bx.smallEnd(0) && sbx.bigEnd(0) >= bx.bigEnd(0) &&
259  sbx.smallEnd(1) <= bx.smallEnd(1) && sbx.bigEnd(1) >= bx.bigEnd(1) &&
260  sbx.length(2) >= ncomp;
261  if (!covered) {
262  ++p.n_uncovered;
263  continue;
264  }
265 
266  const Array4<const Real> s = src.const_array();
267  const Array4<Real> a = mf->array(mfi);
268  reduce_op.eval(bx, ncomp, reduce_data,
269  [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept -> ReduceTuple
270  {
271  const Real v = s(i, j, klo + n);
272  a(i, j, k, n) = v;
273  // isfinite first: a comparison with a NaN raises the invalid-operation
274  // exception, which a run may trap
275  if (!amrex::Math::isfinite(v)) {
276  return {Long(1), Long(0), Long(1), big, -big};
277  }
278  const Long outside = (v < lo || v > hi) ? Long(1) : Long(0);
279  return {Long(1), outside, Long(0), v, v};
280  });
281  }
282 
283  const ReduceTuple r = reduce_data.value(reduce_op);
284  p.n_filled += amrex::get<0>(r);
285  p.n_outside += amrex::get<1>(r);
286  p.n_not_finite += amrex::get<2>(r);
287  p.vmin = amrex::min(p.vmin, amrex::get<3>(r));
288  p.vmax = amrex::max(p.vmax, amrex::get<4>(r));
289 }
AMREX_ALWAYS_ASSERT(bx.length()[2]==khi+1)
const int klo
Definition: ERF_InitCustomPert_KE.H:9
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE int idx(int i, int j, int k, int nx, int ny)
Definition: ERF_InitForEnsemble.cpp:404
static const std::array< Descriptor, num_fields > & catalog()
Definition: ERF_WRFSurfaceFields.cpp:57
@ ng
Definition: ERF_Morrison.H:51
@ p
Definition: ERF_WSM6.H:303
Here is the call graph for this function:

◆ fill_ghost_cells()

void WRFSurfaceFields::fill_ghost_cells ( amrex::MultiFab &  mf,
const amrex::Periodicity &  period 
)
static

Fill the ghost cells of a field from its valid cells: a ghost cell that the level's grids cover (also through a periodic boundary) takes the value there; one beyond the bounding box of the level's grids takes the nearest column inside it, as the reader's other surface fields do beyond the file; any other takes the nearest column of its own box. Public for the unit tests.

384 {
385  if (mf.nGrowVect() == IntVect(0)) { return; }
386  const int ncomp = mf.nComp();
387  // Not tiled: each box reads its own valid cells and writes its own ghost cells
388  for (MFIter mfi(mf, false); mfi.isValid(); ++mfi) {
389  const Dim3 lo = amrex::lbound(mfi.validbox());
390  const Dim3 hi = amrex::ubound(mfi.validbox());
391  const Array4<Real> a = mf.array(mfi);
392  ParallelFor(mfi.fabbox(), ncomp,
393  [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept
394  {
395  const int ci = amrex::min(amrex::max(i, lo.x), hi.x);
396  const int cj = amrex::min(amrex::max(j, lo.y), hi.y);
397  if (ci != i || cj != j) { a(i, j, k, n) = a(ci, cj, k, n); }
398  });
399  }
400  // The ghost cells another box (or a periodic image) covers take the value there
401  mf.FillBoundary(period);
402 
403  // A ghost cell beyond the level's bounding box in a direction that is not periodic
404  // takes the nearest column inside the bounding box. That column is a valid cell of
405  // this box or one of the ghost cells set above; the cells read lie inside the
406  // bounding box and the cells written outside it.
407  const Box bound = mf.boxArray().minimalBox();
408  const Dim3 blo = amrex::lbound(bound);
409  const Dim3 bhi = amrex::ubound(bound);
410  const bool px = period.isPeriodic(0);
411  const bool py = period.isPeriodic(1);
412  for (MFIter mfi(mf, false); mfi.isValid(); ++mfi) {
413  const Array4<Real> a = mf.array(mfi);
414  ParallelFor(mfi.fabbox(), ncomp,
415  [=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept
416  {
417  const int ci = px ? i : amrex::min(amrex::max(i, blo.x), bhi.x);
418  const int cj = py ? j : amrex::min(amrex::max(j, blo.y), bhi.y);
419  if (ci != i || cj != j) { a(i, j, k, n) = a(ci, cj, k, n); }
420  });
421  }
422 }
GpuArray< Real, AMREX_SPACEDIM > period
Definition: ERF_ActuatorSpreading.cpp:131
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);})
real(c_double), private ci
Definition: ERF_module_mp_morr_two_moment.F90:203
Here is the call graph for this function:

◆ find()

const WRFSurfaceFields::Descriptor * WRFSurfaceFields::find ( const std::string &  nc_name)
static

The descriptor of the variable with this name in the file, or null when it is not one of these.

82 {
83  for (const auto& d : catalog()) {
84  if (nc_name == d.nc_name) { return &d; }
85  }
86  return nullptr;
87 }

Referenced by has_soil_layers().

Here is the caller graph for this function:

◆ finish_level()

void WRFSurfaceFields::finish_level ( int  lev,
const amrex::Periodicity &  period 
)

Close the read of a level, after the last file. Collective: every rank calls it.

Reduces the counts and ranges of fill() over the ranks (two reductions for the level, whatever the number of fields), then for every field read: reports it and fills its ghost cells; or, when a valid cell was not covered by a file, a value lies outside the catalog range, a value is not finite, or two files disagree on the number of layers, reports that with the counts and drops the field. Then drops TSLB, SMOIS, ZS and DZS together when they disagree on the number of soil layers.

Parameters
levlevel
periodthe level's periodicity
293 {
294  AMREX_ALWAYS_ASSERT(lev >= 0 && lev < num_levels());
295  auto& pend = m_pending[lev];
296 
297  // Two reductions for the level: the counts of every field, then the ranges
298  constexpr int ncount = 4;
299  std::array<Long, ncount*num_fields> counts{};
300  std::array<Real, 2*num_fields> range{};
301  for (int f = 0; f < num_fields; ++f) {
302  counts[ncount*f ] = pend[f].n_filled;
303  counts[ncount*f+1] = pend[f].n_outside;
304  counts[ncount*f+2] = pend[f].n_not_finite;
305  counts[ncount*f+3] = pend[f].n_uncovered;
306  range[2*f ] = -pend[f].vmin;
307  range[2*f+1] = pend[f].vmax;
308  }
309  ParallelDescriptor::ReduceLongSum(counts.data(), static_cast<int>(counts.size()));
310  ParallelDescriptor::ReduceRealMax(range.data(), static_cast<int>(range.size()));
311 
312  for (const auto& d : catalog()) {
313  const int f = static_cast<int>(d.id);
314  if (d.kind == Kind::LayerColumn || !pend[f].read) { continue; }
315  auto& mf = m_fields[lev][f];
316  AMREX_ALWAYS_ASSERT(mf != nullptr);
317  const int ncomp = mf->nComp();
318  const Long n_expect = mf->boxArray().numPts() * ncomp;
319  const Long n_filled = counts[ncount*f];
320  const Long n_outside = counts[ncount*f+1];
321  const Long n_nonfin = counts[ncount*f+2];
322  const Long n_uncov = counts[ncount*f+3];
323  const Real vmin = -range[2*f];
324  const Real vmax = range[2*f+1];
325 
326  // n_filled is a sum over the files. The files of a level do not overlap (the
327  // reader takes them as the level's boxes). If two ever did, the columns they
328  // share would be counted twice, n_filled would exceed n_expect, and the field
329  // would be left out with a count above the level's.
330  std::ostringstream why;
331  if (pend[f].conflict) {
332  why << "the files of the level disagree on its number of soil layers";
333  } else if (n_uncov > 0 || n_filled != n_expect) {
334  why << "the files give " << n_filled << " of the level's " << n_expect << " value(s)";
335  } else if (n_outside > 0 || n_nonfin > 0) {
336  why << n_outside << " value(s) outside " << d.lo << " to " << d.hi
337  << " [" << d.units << "], " << n_nonfin << " not finite";
338  if (vmin <= vmax) {
339  why << "; the finite values span " << vmin << " to " << vmax;
340  }
341  }
342  if (!why.str().empty()) {
343  Print() << "Warning: wrfinput " << d.nc_name << " at level " << lev
344  << " is not held: " << why.str() << "\n";
345  drop(lev, d.id);
346  continue;
347  }
348  Print() << " wrfinput surface field " << d.nc_name << " at level " << lev << ": "
349  << ncomp << (ncomp == 1 ? " component" : " components")
350  << ", min " << vmin << ", max " << vmax << " [" << d.units << "]\n";
351  fill_ghost_cells(*mf, period);
352  }
353 
354  // TSLB, SMOIS, ZS and DZS, whichever are held, must agree on the number of layers.
355  // Every rank holds the same counts.
356  {
357  int nlay = 0;
358  bool agree = true;
359  const auto take = [&nlay, &agree] (int n) {
360  if (n == 0) { return; } // not held
361  if (nlay == 0) { nlay = n; }
362  agree = agree && (n == nlay);
363  };
364  take(static_cast<int>(m_soil_depth[lev].size()));
365  take(static_cast<int>(m_soil_thickness[lev].size()));
366  for (const Field id : {Field::TSLB, Field::SMOIS}) {
367  const MultiFab* mf = get(lev, id);
368  take(mf ? mf->nComp() : 0);
369  }
370  if (!agree) {
371  Print() << "Warning: wrfinput TSLB, SMOIS, ZS and DZS at level " << lev
372  << " are not held: they do not have the same number of soil layers\n";
373  for (const Field id : {Field::TSLB, Field::SMOIS, Field::ZS, Field::DZS}) {
374  drop(lev, id);
375  }
376  }
377  }
378 
379  pend = {};
380 }
Field
Definition: ERF_WRFSurfaceFields.H:50
static void fill_ghost_cells(amrex::MultiFab &mf, const amrex::Periodicity &period)
Definition: ERF_WRFSurfaceFields.cpp:383
const amrex::MultiFab * get(int lev, Field id) const
Definition: ERF_WRFSurfaceFields.H:120
static constexpr int num_fields
Definition: ERF_WRFSurfaceFields.H:67
void drop(int lev, Field id)
Definition: ERF_WRFSurfaceFields.cpp:122
Here is the call graph for this function:

◆ get()

const amrex::MultiFab* WRFSurfaceFields::get ( int  lev,
Field  id 
) const
inline

The field at this level, or null when it is not held. Always null for ZS and DZS.

121  {
122  if (lev < 0 || lev >= num_levels()) { return nullptr; }
123  return m_fields[lev][static_cast<int>(id)].get();
124  }

Referenced by has().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ has()

bool WRFSurfaceFields::has ( int  lev,
Field  id 
) const
inline
126 { return get(lev, id) != nullptr; }
Here is the call graph for this function:

◆ has_soil_layers()

static bool WRFSurfaceFields::has_soil_layers ( const std::string &  nc_name)
inlinestatic

True when the third index of this variable in the file is the soil layer.

104  {
105  const Descriptor* d = find(nc_name);
106  return d != nullptr && d->kind != Kind::Surface;
107  }
static const Descriptor * find(const std::string &nc_name)
Definition: ERF_WRFSurfaceFields.cpp:81
Here is the call graph for this function:

◆ holds_any()

bool WRFSurfaceFields::holds_any ( int  lev) const

True when the level holds a field or a soil layer column.

100 {
101  if (lev < 0 || lev >= num_levels()) { return false; }
102  for (const auto& f : m_fields[lev]) {
103  if (f) { return true; }
104  }
105  return !m_soil_depth[lev].empty() || !m_soil_thickness[lev].empty();
106 }

◆ num_levels()

int WRFSurfaceFields::num_levels ( ) const
inline
111 { return static_cast<int>(m_fields.size()); }

Referenced by get(), soil_depth(), and soil_thickness().

Here is the caller graph for this function:

◆ on_grids()

std::unique_ptr< MultiFab > WRFSurfaceFields::on_grids ( int  lev,
Field  id,
const amrex::MultiFab *  src,
const amrex::BoxArray &  ba2d,
const amrex::DistributionMapping &  dm,
const amrex::IntVect &  ng,
const amrex::Periodicity &  period,
const amrex::IntVect &  ratio 
) const
private
429 {
430  const MultiFab* crse = (lev > 0) ? get(lev-1, id) : nullptr;
431  if (src == nullptr && crse == nullptr) { return nullptr; }
432  const int ncomp = src ? src->nComp() : crse->nComp();
433 
434  const bool src_covers = src && src->boxArray().contains(ba2d);
435  bool use_crse = false;
436  if (!src_covers) {
437  // The coarser level must hold the field with the same soil layers, on every
438  // column under the new grids (proper nesting gives the last)
439  if (crse == nullptr || crse->nComp() != ncomp) { return nullptr; }
440  BoxArray cba = ba2d;
441  cba.coarsen(IntVect(ratio[0], ratio[1], 1));
442  if (!crse->boxArray().contains(cba)) { return nullptr; }
443  use_crse = true;
444  }
445 
446  auto fresh = std::make_unique<MultiFab>(ba2d, dm, ncomp, ng);
447  if (use_crse) { fill_from_coarser(*fresh, *crse, ratio); }
448  // The level's own values go on top, wherever they reach
449  if (src) { fresh->ParallelCopy(*src, 0, 0, ncomp, IntVect(0), IntVect(0)); }
450  fill_ghost_cells(*fresh, period);
451  return fresh;
452 }
void fill_from_coarser(MultiFab &fine, const MultiFab &crse, const IntVect &ratio)
Definition: ERF_WRFSurfaceFields.cpp:33
Here is the call graph for this function:

◆ parse_header()

bool WRFSurfaceFields::parse_header ( std::istream &  is,
amrex::Vector< HeaderLevel > &  out 
)
static

Returns false, leaving out empty, when the text is not a header of this class.

546 {
547  out.clear();
548  std::string magic;
549  int version = 0;
550  int nlevels = 0;
551  if (!(is >> magic >> version >> nlevels) || magic != chk_magic ||
552  version != chk_version || nlevels < 0) {
553  return false;
554  }
555  Vector<HeaderLevel> levels(nlevels);
556  for (int lev = 0; lev < nlevels; ++lev) {
557  std::string word;
558  int ilev = -1;
559  int n = -1;
560  if (!(is >> word >> ilev >> n) || word != "Level" || ilev != lev || n < 0) { return false; }
561  for (int e = 0; e < n; ++e) {
562  std::string name;
563  int count = 0;
564  if (!(is >> name >> count) || count < 1) { return false; }
565  const Descriptor* d = find(name);
566  if (d == nullptr) { return false; }
567  if (d->kind == Kind::LayerColumn) {
568  Vector<Real> v(count);
569  for (auto& x : v) {
570  if (!(is >> x)) { return false; }
571  }
572  ((d->id == Field::DZS) ? levels[lev].soil_thickness : levels[lev].soil_depth) = v;
573  }
574  levels[lev].ncomp[static_cast<int>(d->id)] = count;
575  }
576  }
577  out = std::move(levels);
578  return true;
579 }
int count
Definition: ERF_ActuatorSpreading.cpp:264
std::string name
Definition: ERF_Plotfile2DCatalog.cpp:139
const amrex::Vector< amrex::Real > & soil_thickness(int lev) const
Definition: ERF_WRFSurfaceFields.H:136
const amrex::Vector< amrex::Real > & soil_depth(int lev) const
Definition: ERF_WRFSurfaceFields.H:129
constexpr int chk_version
Definition: ERF_WRFSurfaceFields.cpp:28
const char *const chk_magic
Definition: ERF_WRFSurfaceFields.cpp:27

◆ read_checkpoint()

bool WRFSurfaceFields::read_checkpoint ( const std::string &  checkpoint_dir,
int  nlevels,
const amrex::Vector< amrex::BoxArray > &  ba2d,
const amrex::Vector< amrex::DistributionMapping > &  dm,
const amrex::IntVect &  ng,
const amrex::Vector< amrex::Periodicity > &  period,
const amrex::Vector< amrex::IntVect > &  ratio 
)

Read what write_checkpoint() wrote, onto the grids of this run (they need not be those of the checkpoint). A checkpoint without the text file (written before this class) leaves the holder empty, prints one line and returns false.

Where this run's grids reach beyond those of the checkpoint, the rule of remake() applies: the columns the checkpoint does not give come from level lev-1, or the field is not restored and one line says so. No cell is left without a value.

Parameters
ba2d,dmthe grids and distribution of each level of this run
ngghost cells of the stored fields
periodper level
ratiorefinement ratio between level lev and lev+1, per level (z is ignored)
607 {
608  const std::string name = checkpoint_dir + "/" + checkpoint_header_name;
609  if (!amrex::FileExists(name)) {
610  Print() << " " << name << " is not in the checkpoint (written before the wrfinput "
611  << "land and soil fields were stored): none is restored\n";
612  return false;
613  }
614 
615  Vector<char> chars;
616  ParallelDescriptor::ReadAndBcastFile(name, chars);
617  std::istringstream is(std::string(chars.dataPtr()));
618  Vector<HeaderLevel> levels;
619  if (!parse_header(is, levels)) {
620  Print() << "Warning: " << name << " could not be read: the wrfinput land and soil "
621  << "fields are not restored\n";
622  return false;
623  }
624 
625  const int nlev = amrex::min(nlevels, num_levels(), static_cast<int>(levels.size()));
626  for (int lev = 0; lev < nlev; ++lev) {
627  for (auto& f : m_fields[lev]) { f.reset(); }
628  m_pending[lev] = {};
629  m_soil_depth[lev] = levels[lev].soil_depth;
630  m_soil_thickness[lev] = levels[lev].soil_thickness;
631  for (const Field id : {Field::ZS, Field::DZS}) {
632  const auto& v = (id == Field::DZS) ? m_soil_thickness[lev] : m_soil_depth[lev];
633  if (v.empty()) { continue; }
634  Print() << " wrfinput soil layer "
635  << ((id == Field::DZS) ? "thicknesses DZS" : "depths ZS")
636  << " at level " << lev << " restored from the checkpoint:";
637  for (const Real x : v) { Print() << " " << x; }
638  Print() << " [m]\n";
639  }
640  for (const auto& d : catalog()) {
641  const int ncomp = levels[lev].ncomp[static_cast<int>(d.id)];
642  if (d.kind == Kind::LayerColumn || ncomp < 1) { continue; }
643  const std::string prefix = MultiFabFileFullPrefix(lev, checkpoint_dir, "Level_",
644  std::string(chk_mf_prefix) + d.nc_name);
645  if (!amrex::FileExists(prefix + "_H")) {
646  Print() << "Warning: " << prefix << " is not in the checkpoint: wrfinput "
647  << d.nc_name << " at level " << lev << " is not restored\n";
648  continue;
649  }
650  // Defined by VisMF::Read on the grids the checkpoint was written with
651  MultiFab src;
652  VisMF::Read(src, prefix);
653  if (src.nComp() != ncomp) {
654  Print() << "Warning: " << prefix << " holds " << src.nComp() << " component(s) and "
655  << name << " lists " << ncomp << ": wrfinput " << d.nc_name
656  << " at level " << lev << " is not restored\n";
657  continue;
658  }
659  // As on a regrid: the checkpoint's values where its grids reach, the coarser
660  // level (restored just before) elsewhere, and no field when neither covers
661  // this run's grids. No cell is left without a value.
662  auto& mf = m_fields[lev][static_cast<int>(d.id)];
663  mf = on_grids(lev, d.id, &src, ba2d[lev], dm[lev], ng, period[lev],
664  (lev > 0) ? ratio[lev-1] : IntVect(1));
665  if (!mf) {
666  Print() << "Warning: wrfinput " << d.nc_name << " at level " << lev
667  << " is not restored: this run's grids reach beyond the grids of "
668  << "the checkpoint";
669  if (lev > 0) {
670  Print() << ", and level " << lev-1
671  << " does not hold it with the same number of components";
672  }
673  Print() << "\n";
674  continue;
675  }
676  // The range is reported so that a restart can be compared with the first run
677  Real vmin = std::numeric_limits<Real>::max();
678  Real vmax = -std::numeric_limits<Real>::max();
679  for (int n = 0; n < ncomp; ++n) {
680  vmin = amrex::min(vmin, mf->min(n));
681  vmax = amrex::max(vmax, mf->max(n));
682  }
683  Print() << " wrfinput surface field " << d.nc_name << " at level " << lev
684  << " restored from the checkpoint: " << ncomp
685  << (ncomp == 1 ? " component" : " components")
686  << ", min " << vmin << ", max " << vmax << " [" << d.units << "]\n";
687  }
688  }
689  return true;
690 }
std::unique_ptr< amrex::MultiFab > on_grids(int lev, Field id, const amrex::MultiFab *src, const amrex::BoxArray &ba2d, const amrex::DistributionMapping &dm, const amrex::IntVect &ng, const amrex::Periodicity &period, const amrex::IntVect &ratio) const
Definition: ERF_WRFSurfaceFields.cpp:425
static bool parse_header(std::istream &is, amrex::Vector< HeaderLevel > &out)
Definition: ERF_WRFSurfaceFields.cpp:545
static constexpr const char * checkpoint_header_name
Definition: ERF_WRFSurfaceFields.H:234
const char *const chk_mf_prefix
Definition: ERF_WRFSurfaceFields.cpp:24

◆ remake()

void WRFSurfaceFields::remake ( int  lev,
const amrex::BoxArray &  new_ba2d,
const amrex::DistributionMapping &  new_dm,
const amrex::Periodicity &  period,
const amrex::IntVect &  ratio,
bool  take_coarser_fields,
int  verbose = 0 
)

Put the level's fields on new grids (a new level, a regrid or a rebalance). Collective: every rank calls it. Level lev-1 must already be on its new grids.

A field the level holds keeps its values on the columns its old grids covered. The other columns take the values of the column of level lev-1 they lie in. When level lev-1 does not hold the field with the same number of components and the new grids reach beyond the old ones, that field is dropped and one line says so.

With take_coarser_fields, a field the level does not hold and level lev-1 does is taken from level lev-1 on every column, and so are the soil layer columns when the level has none. This is for a level without a file of its own.

The soil layer columns do not depend on the grids and are kept.

Parameters
levlevel
new_ba2d,new_dmthe new grids, one cell thick in z, and their distribution
periodthe level's periodicity
ratiorefinement ratio between level lev-1 and this level (z is ignored; not used at level 0)
take_coarser_fieldstake the fields the level lacks from level lev-1
verboseabove zero: one line per field put on new grids, with the number of columns taken from level lev-1 and the range
462 {
463  if (lev < 0 || lev >= num_levels()) { return; }
464  const Long ncol = new_ba2d.numPts();
465 
466  for (const auto& d : catalog()) {
467  if (d.kind == Kind::LayerColumn) { continue; }
468  auto& f = m_fields[lev][static_cast<int>(d.id)];
469  const MultiFab* crse = (lev > 0) ? get(lev-1, d.id) : nullptr;
470  const bool held = (f != nullptr);
471  if (!held && !(take_coarser_fields && crse)) { continue; }
472  if (held && f->boxArray() == new_ba2d && f->DistributionMap() == new_dm) { continue; }
473 
474  const IntVect ng = held ? f->nGrowVect() : crse->nGrowVect();
475  // Columns the level's own grids give; the others come from the coarser level
476  const Long n_own = (held && verbose > 0) ? amrex::intersect(new_ba2d, f->boxArray()).numPts() : 0;
477  auto fresh = on_grids(lev, d.id, f.get(), new_ba2d, new_dm, ng, period, ratio);
478  if (!fresh) {
479  if (held) {
480  Print() << "Warning: wrfinput " << d.nc_name << " at level " << lev
481  << " is dropped: the new grids reach beyond the grids that held it";
482  if (lev > 0) {
483  Print() << ", and level " << lev-1
484  << " does not hold it with the same number of components";
485  }
486  Print() << "\n";
487  f.reset();
488  }
489  continue;
490  }
491  f = std::move(fresh);
492  if (verbose > 0) {
493  Real vmin = std::numeric_limits<Real>::max();
494  Real vmax = -std::numeric_limits<Real>::max();
495  for (int n = 0; n < f->nComp(); ++n) {
496  vmin = amrex::min(vmin, f->min(n));
497  vmax = amrex::max(vmax, f->max(n));
498  }
499  Print() << " wrfinput surface field " << d.nc_name << " at level " << lev
500  << " on the new grids: " << f->nComp()
501  << (f->nComp() == 1 ? " component" : " components") << ", "
502  << ncol - n_own << " of " << ncol << " columns from level "
503  << amrex::max(lev-1, 0) << ", min " << vmin << ", max " << vmax
504  << " [" << d.units << "]\n";
505  }
506  }
507 
508  // The soil layer columns do not depend on the grids: they are kept. A level that
509  // takes the fields of the coarser level takes its columns too, when it has none.
510  if (take_coarser_fields && lev > 0) {
511  if (m_soil_depth[lev].empty()) { m_soil_depth[lev] = m_soil_depth[lev-1]; }
512  if (m_soil_thickness[lev].empty()) { m_soil_thickness[lev] = m_soil_thickness[lev-1]; }
513  }
514 }
Here is the call graph for this function:

◆ resize()

void WRFSurfaceFields::resize ( int  nlevs)
91 {
92  m_fields.resize(nlevs);
93  m_pending.resize(nlevs);
94  m_soil_depth.resize(nlevs);
95  m_soil_thickness.resize(nlevs);
96 }

Referenced by ERF::ERF_shared().

Here is the caller graph for this function:

◆ set_soil_layers()

void WRFSurfaceFields::set_soil_layers ( int  lev,
Field  id,
const amrex::FArrayBox &  src 
)

Take the soil layer depths (ZS) or thicknesses (DZS) from the column a rank has read. Local: every rank reads the same column.

A column that is zero in every layer is taken as not given. Otherwise the depths must be zero or more and increase with the layer (a land model may put its first level at the surface), and the thicknesses must be positive. A column that breaks these rules, or holds a value that is not finite or above the catalog bound, is reported and not held.

Parameters
levlevel
idField::ZS or Field::DZS
srcthe column as read; host-readable memory; its z range is the soil layers
135 {
136  AMREX_ALWAYS_ASSERT(lev >= 0 && lev < num_levels());
137  AMREX_ALWAYS_ASSERT(id == Field::ZS || id == Field::DZS);
138  const Descriptor& d = catalog()[static_cast<int>(id)];
139  Pending& p = m_pending[lev][static_cast<int>(id)];
140  auto& dst = (id == Field::DZS) ? m_soil_thickness[lev] : m_soil_depth[lev];
141  const Box& sbx = src.box();
143  "WRFSurfaceFields::set_soil_layers: this rank holds no part of the soil layer column");
144  if (p.conflict) { return; }
145 
146  const auto arr = src.const_array();
147  const int ilo = sbx.smallEnd(0);
148  const int jlo = sbx.smallEnd(1);
149  const int nlay = sbx.length(2);
150  Vector<Real> vals(nlay);
151  std::string reason;
152  bool all_zero = true;
153  for (int n = 0; n < nlay; ++n) {
154  vals[n] = arr(ilo, jlo, sbx.smallEnd(2) + n);
155  // isfinite first: a comparison with a NaN raises the invalid-operation exception
156  if (!std::isfinite(vals[n])) {
157  reason = "a value is not finite";
158  break;
159  }
160  all_zero = all_zero && (vals[n] == Real(0.0));
161  }
162  if (reason.empty() && all_zero) {
163  // A file written without a land model (ideal.exe, or a hand-built file) declares
164  // the layers and leaves them at zero: that is a file without them.
165  Print() << " wrfinput " << d.nc_name << " at level " << lev
166  << " is zero in every soil layer: taken as not given\n";
167  return;
168  }
169  for (int n = 0; reason.empty() && n < nlay; ++n) {
170  if (vals[n] > d.hi) {
171  reason = "a value is above the catalog bound";
172  } else if (id == Field::DZS && vals[n] <= Real(0.0)) {
173  reason = "every soil layer thickness must be positive";
174  } else if (id == Field::ZS && vals[n] < Real(0.0)) {
175  reason = "a soil layer depth is negative";
176  } else if (id == Field::ZS && n > 0 && vals[n] <= vals[n-1]) {
177  // The top layer is first: the depths grow with the layer index. The first
178  // one may be zero (a land model with its first level at the surface).
179  reason = "the soil layer depths must increase, top layer first";
180  }
181  }
182  if (reason.empty() && p.read && !dst.empty() && dst != vals) {
183  reason = "two files of the level give different values";
184  }
185  if (!reason.empty()) {
186  Print() << "Warning: wrfinput " << d.nc_name << " at level " << lev
187  << " is not held: " << reason << "\n";
188  dst.clear();
189  p.conflict = true;
190  return;
191  }
192  const bool first = dst.empty();
193  dst = vals;
194  p.read = true;
195  if (first) {
196  Print() << " wrfinput soil layer "
197  << ((id == Field::DZS) ? "thicknesses DZS" : "depths ZS")
198  << " at level " << lev << ":";
199  for (const Real v : dst) { Print() << " " << v; }
200  Print() << " [m]\n";
201  }
202 }
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(axis >=0 &&axis< AMREX_SPACEDIM, "prob.axis must be 0, 1 or 2")
Here is the call graph for this function:

◆ soil_depth()

const amrex::Vector<amrex::Real>& WRFSurfaceFields::soil_depth ( int  lev) const
inline

Depth of the center of each soil layer [m], top layer first (ZS); empty when not held.

130  {
131  AMREX_ALWAYS_ASSERT(lev >= 0 && lev < num_levels());
132  return m_soil_depth[lev];
133  }
Here is the call graph for this function:

◆ soil_thickness()

const amrex::Vector<amrex::Real>& WRFSurfaceFields::soil_thickness ( int  lev) const
inline

Thickness of each soil layer [m], top layer first (DZS); empty when not held.

137  {
138  AMREX_ALWAYS_ASSERT(lev >= 0 && lev < num_levels());
139  return m_soil_thickness[lev];
140  }
Here is the call graph for this function:

◆ write_checkpoint()

void WRFSurfaceFields::write_checkpoint ( const std::string &  checkpoint_dir,
int  nlevels 
) const

Write the held fields into a checkpoint directory: one MultiFab file per field under the level's directory, and one text file that lists what each level holds. The text file is written by the I/O rank, also when nothing is held.

583 {
584  if (ParallelDescriptor::IOProcessor()) {
585  const std::string name = checkpoint_dir + "/" + checkpoint_header_name;
586  std::ofstream os(name, std::ofstream::out | std::ofstream::trunc);
587  write_header(os, nlevels);
588  if (!os.good()) { amrex::FileOpenFailed(name); }
589  }
590  for (int lev = 0; lev < nlevels && lev < num_levels(); ++lev) {
591  for (const auto& d : catalog()) {
592  if (const MultiFab* mf = get(lev, d.id)) {
593  VisMF::Write(*mf, MultiFabFileFullPrefix(lev, checkpoint_dir, "Level_",
594  std::string(chk_mf_prefix) + d.nc_name));
595  }
596  }
597  }
598 }
void write_header(std::ostream &os, int nlevels) const
Definition: ERF_WRFSurfaceFields.cpp:517
Here is the call graph for this function:

◆ write_header()

void WRFSurfaceFields::write_header ( std::ostream &  os,
int  nlevels 
) const

Write and parse the text file; public for the unit tests.

518 {
519  os << chk_magic << " " << chk_version << "\n" << nlevels << "\n";
520  os << std::setprecision(17);
521  for (int lev = 0; lev < nlevels; ++lev) {
522  std::ostringstream entries;
523  entries << std::setprecision(17);
524  int n = 0;
525  if (lev < num_levels()) {
526  for (const auto& d : catalog()) {
527  if (d.kind == Kind::LayerColumn) {
528  const auto& v = (d.id == Field::DZS) ? m_soil_thickness[lev] : m_soil_depth[lev];
529  if (v.empty()) { continue; }
530  entries << d.nc_name << " " << v.size();
531  for (const Real x : v) { entries << " " << x; }
532  entries << "\n";
533  ++n;
534  } else if (const MultiFab* mf = get(lev, d.id)) {
535  entries << d.nc_name << " " << mf->nComp() << "\n";
536  ++n;
537  }
538  }
539  }
540  os << "Level " << lev << " " << n << "\n" << entries.str();
541  }
542 }
Here is the call graph for this function:

Member Data Documentation

◆ checkpoint_header_name

constexpr const char* WRFSurfaceFields::checkpoint_header_name = "WRFSurfaceFieldsHeader"
staticconstexpr

Name of the checkpoint's text file that lists what each level holds.

◆ m_fields

amrex::Vector<std::array<std::unique_ptr<amrex::MultiFab>, num_fields> > WRFSurfaceFields::m_fields
private

Referenced by get(), and num_levels().

◆ m_pending

amrex::Vector<std::array<Pending, num_fields> > WRFSurfaceFields::m_pending
private

◆ m_soil_depth

amrex::Vector<amrex::Vector<amrex::Real> > WRFSurfaceFields::m_soil_depth
private

Referenced by soil_depth().

◆ m_soil_thickness

amrex::Vector<amrex::Vector<amrex::Real> > WRFSurfaceFields::m_soil_thickness
private

Referenced by soil_thickness().

◆ num_fields

constexpr int WRFSurfaceFields::num_fields = static_cast<int>(Field::NumFields)
staticconstexpr

The documentation for this class was generated from the following files: