ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_CheckpointSurfaceTemperature.H
Go to the documentation of this file.
1 #ifndef ERF_CHECKPOINT_SURFACE_TEMPERATURE_H_
2 #define ERF_CHECKPOINT_SURFACE_TEMPERATURE_H_
3 
4 #include <cctype>
5 #include <iomanip>
6 #include <istream>
7 #include <ostream>
8 #include <sstream>
9 #include <string>
10 #include <vector>
11 
12 #include <AMReX_Box.H>
13 #include <AMReX_Geometry.H>
14 #include <AMReX_Gpu.H>
15 #include <AMReX_iMultiFab.H>
16 #include <AMReX_MultiFab.H>
17 #include <AMReX_ParallelDescriptor.H>
18 #include <AMReX_ParmParse.H>
19 #include <AMReX_Periodicity.H>
20 #include <AMReX_PlotFileUtil.H>
21 #include <AMReX_Print.H>
22 #include <AMReX_Utility.H>
23 
24 #include "ERF_EOS.H"
25 #include "ERF_SurfaceTemperature.H"
26 
28 
29 /**
30  * Version of the surface_temperature_contract marker written with a checkpoint, which says
31  * what its SST_0 and TSK_0 arrays hold:
32  *
33  * 1: potential temperature, referenced to the surface pressure of the input they were
34  * read from
35  * 2: absolute temperature [K], which the surface layer converts at the current surface
36  * pressure
37  */
38 constexpr int contract_version = 2;
39 
40 /** Name of the marker file in the checkpoint directory */
41 constexpr const char* contract_file_name = "surface_temperature_contract";
42 
43 /** Parameter (in the erf namespace) asserting the init type that wrote a checkpoint */
44 constexpr const char* legacy_init_type_key = "legacy_surface_temperature_init_type";
45 
46 inline void
47 write_contract_version (std::ostream& output)
48 {
49  output << contract_version << "\n";
50 }
51 
52 /**
53  * Return the first AMR level containing a legacy SST or TSK surface array.
54  *
55  * The arrays are identified by their AMReX header files. A return value of
56  * -1 means that neither legacy array is present on any level.
57  */
58 inline int
59 first_legacy_surface_temperature_level (const std::string& checkpointname,
60  const int finest_level)
61 {
62  for (int lev = 0; lev <= finest_level; ++lev) {
63  const bool has_sst = amrex::FileExists(
64  amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "SST_0_H"));
65  const bool has_tsk = amrex::FileExists(
66  amrex::MultiFabFileFullPrefix(lev, checkpointname, "Level_", "TSK_0_H"));
67  if (has_sst || has_tsk) {
68  return lev;
69  }
70  }
71  return -1;
72 }
73 
74 enum class ContractReadStatus {
75  Valid,
76  Malformed,
78 };
79 
80 enum class LegacyInitType {
81  WRFInput,
82  Metgrid,
83  Unknown
84 };
85 
86 /**
87  * What the SST_0 and TSK_0 arrays of a checkpoint hold
88  */
90  Absolute, ///< absolute temperature [K], restored as it is
91  Potential, ///< potential temperature, converted to absolute temperature on restart
92  UnknownProvenance ///< no marker, and the init type that wrote them is not known
93 };
94 
95 inline LegacyInitType
96 parse_legacy_init_type_value (std::string value)
97 {
98  for (char& character : value) {
99  character = static_cast<char>(std::tolower(static_cast<unsigned char>(character)));
100  }
101  if (value == "wrfinput") {
103  }
104  if (value == "metgrid") {
106  }
108 }
109 
110 inline const char*
112 {
113  switch (type) {
115  return "WRFInput";
117  return "Metgrid";
118  default:
119  return "unknown";
120  }
121 }
122 
123 /**
124  * Parse the integer surface-temperature contract marker from a checkpoint. Every version
125  * up to contract_version is understood.
126  */
127 inline ContractReadStatus
128 read_contract_version (std::istream& input, int& version)
129 {
130  if (!(input >> version)) {
132  }
133 
134  std::string extra;
135  if (input >> extra) {
137  }
138 
139  return (version >= 1 && version <= contract_version) ? ContractReadStatus::Valid
141 }
142 
143 /**
144  * Read the init type that wrote a checkpoint, from the last erf.init_type assignment in its
145  * job_info. Before the marker, WRFInput stored SST and TSK as potential temperature and
146  * Metgrid as absolute temperature, so for a checkpoint without one this tells which of the
147  * two it holds. For one with a version 1 marker, which holds potential temperature, it
148  * tells which surface pressure they were converted with.
149  */
150 inline LegacyInitType
152 {
153  constexpr const char* key = "erf.init_type";
154  constexpr std::size_t key_length = 13;
156  std::string line;
157 
158  while (std::getline(input, line)) {
159  std::size_t pos = 0;
160  while (pos < line.size() &&
161  std::isspace(static_cast<unsigned char>(line[pos]))) {
162  ++pos;
163  }
164  if (line.compare(pos, key_length, key) != 0) {
165  continue;
166  }
167  pos += key_length;
168  if (pos < line.size() && !std::isspace(static_cast<unsigned char>(line[pos])) &&
169  line[pos] != '=') {
170  continue;
171  }
172  while (pos < line.size() &&
173  std::isspace(static_cast<unsigned char>(line[pos]))) {
174  ++pos;
175  }
176  if (pos == line.size() || line[pos] != '=') {
177  result = LegacyInitType::Unknown;
178  continue;
179  }
180  ++pos;
181  while (pos < line.size() &&
182  std::isspace(static_cast<unsigned char>(line[pos]))) {
183  ++pos;
184  }
185 
186  std::string value;
187  bool malformed = (pos == line.size());
188  if (!malformed && line[pos] == '"') {
189  ++pos;
190  const std::size_t end_quote = line.find('"', pos);
191  if (end_quote == std::string::npos) {
192  malformed = true;
193  } else {
194  value = line.substr(pos, end_quote - pos);
195  pos = end_quote + 1;
196  }
197  } else if (!malformed) {
198  const std::size_t value_begin = pos;
199  while (pos < line.size() &&
200  !std::isspace(static_cast<unsigned char>(line[pos]))) {
201  ++pos;
202  }
203  value = line.substr(value_begin, pos - value_begin);
204  }
205 
206  while (pos < line.size() &&
207  std::isspace(static_cast<unsigned char>(line[pos]))) {
208  ++pos;
209  }
210  if (malformed || pos != line.size()) {
211  result = LegacyInitType::Unknown;
212  continue;
213  }
214 
215  result = parse_legacy_init_type_value(value);
216  }
217 
218  return result;
219 }
220 
221 /**
222  * Classify the SST_0 and TSK_0 arrays of a checkpoint. marker_version is the version of its
223  * contract marker, or 0 if it has none; a checkpoint without one is classified by the init
224  * type that wrote it (see parse_legacy_init_type_from_job_info).
225  */
227 classify_stored_surface_temperature (const int marker_version,
228  const bool has_surface_arrays,
229  const LegacyInitType legacy_init_type)
230 {
231  if (!has_surface_arrays || marker_version >= 2) {
233  }
234  if (marker_version == 1 || legacy_init_type == LegacyInitType::WRFInput) {
236  }
237  if (legacy_init_type == LegacyInitType::Metgrid) {
239  }
241 }
242 
243 /**
244  * Where the init type that wrote the SST_0 and TSK_0 of a checkpoint was learned from
245  */
246 enum class ProvenanceOrigin {
247  JobInfo, ///< the erf.init_type recorded in the job_info of the checkpoint
248  Assertion, ///< erf.legacy_surface_temperature_init_type, in the inputs of the restart
249  None ///< not known
250 };
251 
252 /**
253  * What the SST_0 and TSK_0 arrays of a checkpoint hold, and which init type wrote them
254  */
256  int marker_version = 0; ///< version of the contract marker, 0 if there is none
257  int first_level = -1; ///< first AMR level holding SST_0 or TSK_0, -1 if none does
258  LegacyInitType source = LegacyInitType::Unknown; ///< init type that wrote them
259  ProvenanceOrigin origin = ProvenanceOrigin::None; ///< where source was learned from
260  LegacyInitType asserted = LegacyInitType::Unknown; ///< init type the restart inputs assert
262 };
263 
264 /**
265  * Establish what the SST_0 and TSK_0 of a checkpoint hold, and which init type wrote them.
266  *
267  * The erf.init_type recorded in the job_info of the checkpoint is its provenance. The
268  * erf.legacy_surface_temperature_init_type assertion stands in for it only where the
269  * checkpoint records none. The init type of the restart plays no part: a run can be
270  * restarted with inputs other than those that wrote the checkpoint.
271  *
272  * @param marker_version version of the contract marker, 0 if there is none
273  * @param first_level first AMR level holding SST_0 or TSK_0, -1 if none does
274  * @param job_info_source init type recorded in the job_info of the checkpoint
275  * @param asserted_source init type asserted by erf.legacy_surface_temperature_init_type
276  */
278 resolve_surface_temperature_provenance (const int marker_version,
279  const int first_level,
280  const LegacyInitType job_info_source,
281  const LegacyInitType asserted_source)
282 {
284  result.marker_version = marker_version;
285  result.first_level = first_level;
286  result.asserted = asserted_source;
287  if (job_info_source != LegacyInitType::Unknown) {
288  result.source = job_info_source;
290  } else if (asserted_source != LegacyInitType::Unknown) {
291  result.source = asserted_source;
293  }
294  result.stored = classify_stored_surface_temperature(marker_version, first_level >= 0,
295  result.source);
296  return result;
297 }
298 
299 /**
300  * How the SST_0 and TSK_0 of a checkpoint are brought to the absolute temperature they are
301  * now kept as
302  */
304  None, ///< they hold absolute temperature: restored as they are
305  InputPressure, ///< best available WRFInput pressure; refined regrids can make it approximate
306  RestartPressure, ///< approximate: converted with the surface pressure of the restarted state
307  Reject ///< they cannot be migrated: the restart aborts, giving the reason
308 };
309 
312  SurfaceTemperatureProvenance provenance; ///< what the decision was made from
313  std::string reason; ///< for Reject: what is missing, and how to supply it
314 };
315 
316 /**
317  * Decide how to bring the SST_0 and TSK_0 of a checkpoint to absolute temperature.
318  *
319  * Arrays that hold potential temperature were converted with the surface pressure of the
320  * input they were read from, which only the init type that wrote them identifies. A WRFInput
321  * restart reads the first init file's PSFC at level 0 and, at finer levels, uses the level's
322  * own PSFC where covered and the recovered parent pressure elsewhere. The checkpoint does
323  * not record whether RemakeLevel replaced fine values with parent-interpolated potential
324  * temperature, so fine-level migration is approximate wherever that may have happened:
325  * pressure-dependent conversion and spatial interpolation do not commute. A Metgrid run
326  * converted them with its met_em surface pressure, which a restart does not read. Metgrid
327  * migration therefore uses restarted ground pressure on boxes that reach the ground and
328  * parent ground pressure for aloft-only boxes. Both old formats lack enough metadata to
329  * recover the original absolute temperatures exactly.
330  *
331  * @param provenance what the checkpoint holds and which init type wrote it
332  * @param restart_reads_wrfinput whether the restart is a WRFInput run, in a build with NetCDF
333  * @param checkpointname name of the checkpoint, for the reason of a rejection
334  */
337  const bool restart_reads_wrfinput,
338  const std::string& checkpointname)
339 {
341  plan.provenance = provenance;
342  if (provenance.stored == StoredSurfaceTemperature::Absolute) {
343  return plan;
344  }
345 
346  const std::string holds = "Restart checkpoint '" + checkpointname + "' holds SST_0/TSK_0 " +
347  "(from AMR level " + std::to_string(provenance.first_level) + ")";
348  const std::string set_assertion = "Set erf." + std::string(legacy_init_type_key) +
349  " to the erf.init_type of the run that wrote it: ";
352  plan.reason = holds + " without a surface-temperature contract marker, and its job_info "
353  "does not record the erf.init_type that wrote them. " + set_assertion +
354  "WRFInput, which stored them as potential temperature, or Metgrid, which "
355  "stored them as absolute temperature.";
356  return plan;
357  }
358 
359  switch (provenance.source) {
361  if (restart_reads_wrfinput) {
363  } else {
364  plan.reason = holds + " as potential temperature, which a WRFInput run converted with "
365  "the surface pressure (PSFC) of its wrfinput files. Recovering them "
366  "needs that PSFC: restart with erf.init_type = WRFInput, in a build "
367  "with NetCDF, and the erf.nc_init_file_<lev> of the original run.";
368  }
369  break;
372  break;
374  plan.reason = holds + " as potential temperature (surface-temperature contract version " +
375  std::to_string(provenance.marker_version) + "), but its job_info does not "
376  "record the erf.init_type that converted them, so the surface pressure "
377  "they were converted with is not known. " + set_assertion +
378  "WRFInput, to use available wrfinput PSFC (fine-level regrids may be "
379  "approximate), or Metgrid, to migrate them approximately with restarted "
380  "ground pressure and parent ground pressure for aloft-only levels.";
381  break;
382  }
383  return plan;
384 }
385 
386 /**
387  * Where the wrfinput surface pressure that a level's SST and TSK were converted with is
388  * recovered from
389  */
391  OwnInitFile, ///< the PSFC of the level's own (first) init file
392  CoarserLevel, ///< the coarser level's, interpolated: the level took its SST and TSK from it
393  Unavailable ///< it cannot be recovered
394 };
395 
396 /**
397  * Of the init files of a finer level, the first after its first that had started by the time
398  * of a checkpoint, or -1 if none had. The run reads a later init file only once its start
399  * time comes, when the coarser level's start time and elapsed time reach it (ERF::ErrorEst,
400  * with the same comparison), and only then tags the level for it. Until then the level is
401  * made and kept as if it listed its first file alone.
402  *
403  * @param start_times the start time of each init file of the level, in their order
404  * @param coarser_start the start time of the first init file of the coarser level
405  * @param checkpoint_time the elapsed time of the coarser level at the checkpoint
406  */
407 inline int
408 first_started_later_init_file (const std::vector<double>& start_times,
409  const double coarser_start,
410  const double checkpoint_time)
411 {
412  for (int i = 1; i < static_cast<int>(start_times.size()); ++i) {
413  if (start_times[i] <= coarser_start + checkpoint_time) { return i; }
414  }
415  return -1;
416 }
417 
418 /**
419  * Where the wrfinput surface pressure of a level is recovered from, on restart from a WRFInput
420  * checkpoint that holds the SST and TSK as potential temperature. It is read from where the
421  * level read its SST and TSK, and converted them with:
422  *
423  * - level 0 read them from its first init file, the only one init_from_wrfinput reads there,
424  * however many erf.nc_init_file_0 lists;
425  * - a finer level read them from its own init file, unless it has none, or level 0 reads a
426  * wrflowinp file and the level has none of its own (see init_fine_low_slices): it then
427  * took them from the coarser level, interpolated, with the coarser level's PSFC;
428  * - a finer level with several init files read them from its first alone if none of the
429  * others had started by the time of the checkpoint (see first_started_later_init_file).
430  * Once one has, the level may have read it as well, over its own footprint, or have been
431  * regridded for it, which gives it the coarser level's, and the checkpoint does not record
432  * which, so it is not recovered.
433  *
434  * @param lev AMR level
435  * @param num_own_init_files number of init files of the level (erf.nc_init_file_<lev>)
436  * @param later_init_file_started whether an init file of the level after the first may have
437  * started by the time of the checkpoint
438  * @param level0_reads_low_file whether level 0 reads a wrflowinp file (erf.nc_low_file)
439  * @param has_own_low_file whether the level has a wrflowinp file of its own
440  * @param coarser_level_recovered whether the surface pressure of the coarser level was recovered
441  */
444  const int num_own_init_files,
445  const bool later_init_file_started,
446  const bool level0_reads_low_file,
447  const bool has_own_low_file,
448  const bool coarser_level_recovered)
449 {
450  if (lev == 0) {
451  return (num_own_init_files > 0) ? LegacySurfacePressureSource::OwnInitFile
453  }
454  const bool from_coarser_level = (num_own_init_files == 0) ||
455  (level0_reads_low_file && !has_own_low_file);
456  if (from_coarser_level) {
457  return coarser_level_recovered ? LegacySurfacePressureSource::CoarserLevel
459  }
460  return (num_own_init_files == 1 || !later_init_file_started)
463 }
464 
465 /**
466  * What decides, at each cell of a level, whether its surface layer takes the SST, the TSK
467  * or the prescribed land temperature there (erf_surface_temperature::surface_temperature_source).
468  * It takes neither field at a level without an SST.
469  */
471  const amrex::iMultiFab* lmask = nullptr; ///< land mask; without one, every cell is land
472  bool have_sst = false; ///< whether the level has an SST
473  bool have_tsk = false; ///< whether the level has TSK
474  bool ignore_sst = false; ///< whether its surface layer ignores the SST
475 };
476 
477 /**
478  * What decides it at a level on restart: the land mask restored from the checkpoint, and
479  * whether the level has an SST and TSK. The surface layer fills the surface temperature
480  * from them only at a level with an SST (SurfaceLayer::update_fluxes), so a level with TSK
481  * and no SST takes neither. It ignores the SST of a level with TSK whatever
482  * most.ignore_sst says, and that parameter selects nothing at a level without TSK, so it
483  * does not matter here.
484  *
485  * @param lmask the restored land mask of the level, or nullptr
486  * @param have_sst whether the level has an SST once restarted
487  * @param have_tsk whether the level has TSK
488  */
490 restart_surface_temperature_use (const amrex::iMultiFab* lmask, const bool have_sst,
491  const bool have_tsk)
492 {
493  return SurfaceTemperatureUse{lmask, have_sst, have_tsk,
494  erf_surface_temperature::sst_ignored(false, have_tsk)};
495 }
496 
497 /**
498  * Select pressure for migrating one level's legacy surface fields. `ground_pressure` is
499  * diagnosed only where that level's grid actually reaches the domain ground. Elsewhere the
500  * cell is a refined patch aloft and must use the coarser level's ground pressure, never the
501  * lowest elevated cell as a stand-in.
502  */
503 AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE
504 amrex::Real
505 restart_surface_pressure (const bool has_ground_coverage,
506  const amrex::Real ground_pressure,
507  const amrex::Real parent_ground_pressure)
508 {
509  return has_ground_coverage ? ground_pressure : parent_ground_pressure;
510 }
511 
512 /** The name of a surface field: "SST" or "TSK" */
513 inline const char*
515 {
516  return (source == erf_surface_temperature::SurfaceTemperatureSource::tsk) ? "TSK" : "SST";
517 }
518 
519 /**
520  * The valid cells of a surface field that were not converted on this rank: those that could
521  * not be, how many and the first one recorded, and the placeholders left as they are
522  */
524  int count = 0; ///< cells that could not be converted or reconstructed
525  int ghost_count = 0; ///< ghost cells among count
526  int preserved = 0; ///< valid cells left as they are: placeholders where the field is not used
527  int claimed = 0; ///< whether the first cell that could not be converted is described below
528  int i = 0;
529  int j = 0;
530  int land = 0; ///< its land mask
531  int used = 0; ///< whether the surface layer takes the field there
532  int ghost = 0; ///< whether the first failure is a ghost cell
533  amrex::Real theta = amrex::Real(0.0);
534  amrex::Real pressure = amrex::Real(0.0);
535 };
536 
537 /**
538  * Convert a surface field (SST or TSK) from potential to absolute temperature with the
539  * surface pressure it was converted with, T = theta (p/p0)^(R_d/c_p). A ghost cell takes the
540  * pressure of the nearest valid cell of its box. If the ghost cannot be converted, a usable
541  * nearest valid temperature is converted to kelvin and copied into it before FillBoundary.
542  *
543  * Every cell that holds a finite, positive potential temperature is converted, whether or not
544  * the surface layer takes the field there, so that no value the run may come to use (after a
545  * regrid or an interpolation, say) is left as a potential temperature; that takes a finite,
546  * positive surface pressure. A cell that holds none is left as it is. Of the valid cells
547  * left unconverted:
548  *
549  * - one where the surface layer takes the field (see SurfaceTemperatureUse), or that holds a
550  * potential temperature it has no pressure to convert with, is counted, and the first one
551  * described, for abort_on_legacy_conversion_failure;
552  * - one where the surface layer does not take the field, and that holds no temperature, is
553  * a placeholder, such as a zero SST over land, or a zero TSK at a level without an SST:
554  * it is only counted as preserved. It is not made to look like a temperature, so should
555  * the field ever be taken there, the surface layer rejects it then.
556  *
557  * An invalid unused ghost placeholder is left as it is. A required ghost that cannot be
558  * reconstructed is counted and aborts the migration, just like an unconvertible valid cell.
559  *
560  * @param[in,out] field potential temperature in, absolute temperature [K] out
561  * @param[in] source which field it is: SurfaceTemperatureSource::sst or ::tsk
562  * @param[in] use where the surface layer takes it; the land mask, if any, on the
563  * layout of field
564  * @param[in] pressure surface pressure [Pa] on the valid cells of the layout of field
565  * @param[in] rdOcp R_d/c_p
566  * @param[in] period periodicity of the level
567  * @return the cells of this rank that were not converted or reconstructed
568  */
570 potential_to_absolute_temperature (amrex::MultiFab& field,
572  const SurfaceTemperatureUse& use,
573  const amrex::MultiFab& pressure,
574  const amrex::Real rdOcp,
575  const amrex::Periodicity& period)
576 {
578  AMREX_ALWAYS_ASSERT(!use.lmask || (use.lmask->boxArray() == field.boxArray() &&
579  use.lmask->DistributionMap() == field.DistributionMap()));
580  amrex::Gpu::DeviceScalar<LegacyConversionFailure> d_fail(LegacyConversionFailure{});
581  LegacyConversionFailure* fail = d_fail.dataPtr();
582  const bool have_sst = use.have_sst;
583  const bool have_tsk = use.have_tsk;
584  const bool ignore_sst = use.ignore_sst;
585  amrex::iMultiFab converted(field.boxArray(), field.DistributionMap(), 1,
586  field.nGrowVect());
587  converted.setVal(0);
588 
589  // Convert valid cells first. A later ghost pass can then safely copy a converted
590  // neighbor, without racing a valid-cell thread that is still changing theta to kelvin.
591  for (amrex::MFIter mfi(field); mfi.isValid(); ++mfi) {
592  const amrex::Box& vbx = mfi.validbox();
593  const amrex::Array4<amrex::Real> f = field.array(mfi);
594  const amrex::Array4<const amrex::Real> p = pressure.const_array(mfi);
595  const amrex::Array4<const int> mask = (use.lmask) ? use.lmask->const_array(mfi)
596  : amrex::Array4<const int>{};
597  const amrex::Array4<int> was_converted = converted.array(mfi);
598  amrex::ParallelFor(vbx, [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
599  {
600  const amrex::Real theta = f(i,j,k);
601  const amrex::Real p_s = p(i,j,k);
602  amrex::Real temperature = theta;
604  f(i,j,k) = temperature;
605  was_converted(i,j,k) = 1;
606  return;
607  }
608  const int land = (mask) ? mask(i,j,k) : 1;
609  const bool used = have_sst &&
611  land != 0, have_tsk, ignore_sst) == source;
613  amrex::Gpu::Atomic::Add(&fail->preserved, 1);
614  return;
615  }
616  amrex::Gpu::Atomic::Add(&fail->count, 1);
617  if (amrex::Gpu::Atomic::CAS(&fail->claimed, 0, 1) == 0) {
618  fail->i = i;
619  fail->j = j;
620  fail->land = land;
621  fail->used = used ? 1 : 0;
622  fail->ghost = 0;
623  fail->theta = theta;
624  fail->pressure = p_s;
625  }
626  });
627  }
628 
629  for (amrex::MFIter mfi(field); mfi.isValid(); ++mfi) {
630  const amrex::Box& vbx = mfi.validbox();
631  const amrex::IntVect lo = vbx.smallEnd();
632  const amrex::IntVect hi = vbx.bigEnd();
633  const amrex::Array4<amrex::Real> f = field.array(mfi);
634  const amrex::Array4<const amrex::Real> p = pressure.const_array(mfi);
635  const amrex::Array4<const int> mask = (use.lmask) ? use.lmask->const_array(mfi)
636  : amrex::Array4<const int>{};
637  const amrex::Array4<int> was_converted = converted.array(mfi);
638  amrex::ParallelFor(mfi.fabbox(), [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
639  {
640  if (i >= lo[0] && i <= hi[0] && j >= lo[1] && j <= hi[1] &&
641  k >= lo[2] && k <= hi[2]) {
642  return;
643  }
644  const int li = amrex::min(amrex::max(i, lo[0]), hi[0]);
645  const int lj = amrex::min(amrex::max(j, lo[1]), hi[1]);
646  const int lk = amrex::min(amrex::max(k, lo[2]), hi[2]);
647  const amrex::Real theta = f(i,j,k);
648  const amrex::Real p_s = p(li,lj,lk);
649  amrex::Real temperature = theta;
651  f(i,j,k) = temperature;
652  was_converted(i,j,k) = 1;
653  return;
654  }
655 
656  // An invalid temperature is not a positive potential temperature. If an
657  // authoritative neighbor was converted, copy its kelvin value into this
658  // physical-boundary/nest-edge ghost; otherwise preserve the invalid sentinel.
659  // Active invalid valid cells are reported by the valid-cell pass below/above.
661  if (was_converted(li,lj,lk) != 0) {
662  f(i,j,k) = f(li,lj,lk);
663  was_converted(i,j,k) = 1;
664  }
665  return;
666  }
667 
668  const int land = (mask) ? mask(li,lj,lk) : 1;
669  const bool used = have_sst &&
671  land != 0, have_tsk, ignore_sst) == source;
672  if (was_converted(li,lj,lk) != 0) {
673  f(i,j,k) = f(li,lj,lk);
674  was_converted(i,j,k) = 1;
675  return;
676  }
677 
678  // A ghost that merely repeats a positive potential temperature from an
679  // unconvertible valid cell is covered by that valid-cell failure. Counting
680  // each duplicate physical-boundary ghost separately obscures the actionable
681  // owner location and cannot let a mixed-unit field proceed past the abort.
682  const amrex::Real owner_theta = f(li,lj,lk);
684  theta == owner_theta) {
685  return;
686  }
687 
688  amrex::Gpu::Atomic::Add(&fail->count, 1);
689  amrex::Gpu::Atomic::Add(&fail->ghost_count, 1);
690  if (amrex::Gpu::Atomic::CAS(&fail->claimed, 0, 1) == 0) {
691  fail->i = i;
692  fail->j = j;
693  fail->land = land;
694  fail->used = used ? 1 : 0;
695  fail->ghost = 1;
696  fail->theta = theta;
697  fail->pressure = p_s;
698  }
699  });
700  }
701  amrex::Gpu::streamSynchronize();
702  field.FillBoundary(period);
703  return d_fail.dataValue();
704 }
705 
706 /**
707  * Say how many placeholders of a converted surface field were left as they are, and abort the
708  * restart if any rank could not convert a valid cell, after each rank that could not
709  * describes its first such cell. Collective: every rank must call this.
710  *
711  * @param[in] fail this rank's record, from potential_to_absolute_temperature
712  * @param[in] source which field was converted: SurfaceTemperatureSource::sst or ::tsk
713  * @param[in] what what was being converted, to open the messages with
714  */
715 inline void
718  const std::string& what)
719 {
720  const std::string name = surface_field_name(source);
721  int counts[3] = {fail.count, fail.preserved, fail.ghost_count};
722  amrex::ParallelDescriptor::ReduceIntSum(counts, 3);
723  const int count = counts[0];
724  const int preserved = counts[1];
725  const int ghosts = counts[2];
726  if (preserved > 0) {
727  amrex::Print() << what << ": kept " << preserved << " cells where the surface layer "
728  << "does not take the " << name << " as they are, placeholders without "
729  << "a finite, positive temperature\n";
730  }
731  if (count == 0) {
732  return;
733  }
734  if (fail.count > 0) {
735  // Assemble the whole report before writing it, so that the ranks do not interleave
736  std::ostringstream msg;
737  msg << std::setprecision(10) << what << " [rank " << amrex::ParallelDescriptor::MyProc()
738  << "]: " << fail.count << " cells cannot be converted; the first, (" << fail.i
739  << "," << fail.j << "), a " << ((fail.ghost != 0) ? "ghost " : "")
740  << ((fail.land != 0) ? "land" : "water") << " cell "
741  << "where the surface layer " << ((fail.used != 0) ? "takes" : "does not take")
742  << " the " << name << ", has theta = " << fail.theta << ", surface pressure = "
743  << fail.pressure << " Pa\n";
744  amrex::AllPrint() << msg.str() << std::flush;
745  }
746  amrex::ParallelDescriptor::Barrier();
747  amrex::Abort(what + ": " + std::to_string(count) + " cells (" +
748  std::to_string(ghosts) + " ghosts) could not be converted to "
749  "absolute temperature (see above). A cell where the surface layer takes the " +
750  name + " needs a finite, positive potential temperature, and any cell that "
751  "holds one a finite, positive surface pressure to convert it with");
752 }
753 
754 /**
755  * Give each cell of a planar field that lies outside the domain, in a direction that is not
756  * periodic, the value of the nearest cell of the domain, so that a finer level can interpolate
757  * the field up to the domain boundary. The cells of the domain must be filled.
758  *
759  * @param[in,out] mf planar field, cell-centered
760  * @param[in] geom geometry of its level
761  */
762 inline void
763 fill_outside_domain_from_nearest (amrex::MultiFab& mf, const amrex::Geometry& geom)
764 {
765  const amrex::Box& domain = geom.Domain();
766  const amrex::IntVect dlo = domain.smallEnd();
767  const amrex::IntVect dhi = domain.bigEnd();
768  const bool periodic_x = geom.isPeriodic(0);
769  const bool periodic_y = geom.isPeriodic(1);
770  const int ncomp = mf.nComp();
771  for (amrex::MFIter mfi(mf); mfi.isValid(); ++mfi) {
772  const amrex::Array4<amrex::Real> a = mf.array(mfi);
773  amrex::ParallelFor(mfi.fabbox(), [=] AMREX_GPU_DEVICE (int i, int j, int k) noexcept
774  {
775  const int ni = periodic_x ? i : amrex::min(amrex::max(i, dlo[0]), dhi[0]);
776  const int nj = periodic_y ? j : amrex::min(amrex::max(j, dlo[1]), dhi[1]);
777  if (ni != i || nj != j) {
778  for (int n = 0; n < ncomp; ++n) {
779  a(i,j,k,n) = a(ni,nj,k,n);
780  }
781  }
782  });
783  }
784 }
785 
786 /**
787  * Read what the SST_0 and TSK_0 arrays of a checkpoint hold, and which init type wrote them.
788  *
789  * The contract marker says what they hold. Where it does not settle that they hold absolute
790  * temperature (no marker, or version 1), the init type that wrote them is read from the
791  * erf.init_type in the job_info of the checkpoint or, where that records none, from the
792  * erf.legacy_surface_temperature_init_type assertion. Aborts on a malformed or unknown marker
793  * or an invalid assertion.
794  *
795  * @param checkpointname name of the checkpoint directory
796  * @param finest_level finest AMR level of the checkpoint
797  */
798 inline SurfaceTemperatureProvenance
799 read_surface_temperature_provenance (const std::string& checkpointname,
800  const int finest_level)
801 {
802  int marker_version = 0;
803  const std::string marker_name = checkpointname + "/" + contract_file_name;
804  if (amrex::FileExists(marker_name)) {
805  amrex::Vector<char> marker_chars;
806  amrex::ParallelDescriptor::ReadAndBcastFile(marker_name, marker_chars);
807  std::istringstream marker_stream(std::string(marker_chars.dataPtr()),
808  std::istringstream::in);
809  const auto status = read_contract_version(marker_stream, marker_version);
810  if (status == ContractReadStatus::Malformed) {
811  amrex::Abort("Malformed surface-temperature contract marker in '" + marker_name + "'");
812  }
813  if (status == ContractReadStatus::UnknownVersion) {
814  amrex::Abort("Unsupported surface-temperature contract version " +
815  std::to_string(marker_version) + " in '" + marker_name + "'");
816  }
817  }
818  const int first_level = first_legacy_surface_temperature_level(checkpointname, finest_level);
819 
820  // Which init type wrote the arrays matters only where they may hold potential temperature
821  LegacyInitType job_info_source = LegacyInitType::Unknown;
822  LegacyInitType asserted_source = LegacyInitType::Unknown;
823  if (classify_stored_surface_temperature(marker_version, first_level >= 0,
826  {
827  const std::string job_info_name = checkpointname + "/job_info";
828  if (amrex::FileExists(job_info_name)) {
829  amrex::Vector<char> job_info_chars;
830  amrex::ParallelDescriptor::ReadAndBcastFile(job_info_name, job_info_chars);
831  std::istringstream job_info_stream(std::string(job_info_chars.dataPtr()),
832  std::istringstream::in);
833  job_info_source = parse_legacy_init_type_from_job_info(job_info_stream);
834  }
835 
836  amrex::ParmParse pp_erf("erf");
837  if (pp_erf.countval(legacy_init_type_key) > 0) {
838  std::string value;
839  pp_erf.get(legacy_init_type_key, value);
840  asserted_source = parse_legacy_init_type_value(value);
841  if (asserted_source == LegacyInitType::Unknown) {
842  amrex::Abort("Invalid erf." + std::string(legacy_init_type_key) + " value '" +
843  value + "'; accepted values are WRFInput and Metgrid "
844  "(case-insensitive).");
845  }
846  }
847  }
848 
849  const auto provenance = resolve_surface_temperature_provenance(
850  marker_version, first_level, job_info_source, asserted_source);
851  if (provenance.origin == ProvenanceOrigin::Assertion) {
852  amrex::Print() << "WARNING: checkpoint '" << checkpointname << "' does not record the "
853  << "erf.init_type that wrote its SST_0/TSK_0; trusting the explicit erf."
854  << legacy_init_type_key << " = " << legacy_init_type_name(asserted_source)
855  << " assertion.\n";
856  } else if (asserted_source != LegacyInitType::Unknown && asserted_source != job_info_source) {
857  amrex::Print() << "WARNING: ignoring erf." << legacy_init_type_key << " = "
858  << legacy_init_type_name(asserted_source) << ": checkpoint '"
859  << checkpointname << "' records erf.init_type = "
860  << legacy_init_type_name(job_info_source) << " in its job_info.\n";
861  }
862  return provenance;
863 }
864 
865 } // namespace erf_checkpoint_surface_temperature
866 
867 #endif
GpuArray< Real, AMREX_SPACEDIM > period
Definition: ERF_ActuatorSpreading.cpp:131
GpuArray< int, AMREX_SPACEDIM > dhi
Definition: ERF_ActuatorSpreading.cpp:132
GpuArray< int, AMREX_SPACEDIM > dlo
Definition: ERF_ActuatorSpreading.cpp:132
std::vector< std::array< Real, 3 > > pos
Definition: ERF_ActuatorSpreading.cpp:220
int count
Definition: ERF_ActuatorSpreading.cpp:264
const Real rdOcp
Definition: ERF_InitCustomPert_ABL.H:128
AMREX_ALWAYS_ASSERT(bx.length()[2]==khi+1)
std::string input
Definition: ERF_InputPreflight.cpp:29
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);})
std::string name
Definition: ERF_Plotfile2DCatalog.cpp:139
@ theta
Definition: ERF_Kessler.H:26
@ ni
Definition: ERF_Morrison.H:49
@ p
Definition: ERF_WSM6.H:303
ContractReadStatus read_contract_version(std::istream &input, int &version)
Definition: ERF_CheckpointSurfaceTemperature.H:128
LegacySurfacePressureSource
Definition: ERF_CheckpointSurfaceTemperature.H:390
@ CoarserLevel
the coarser level's, interpolated: the level took its SST and TSK from it
@ OwnInitFile
the PSFC of the level's own (first) init file
LegacyInitType parse_legacy_init_type_value(std::string value)
Definition: ERF_CheckpointSurfaceTemperature.H:96
SurfaceTemperatureUse restart_surface_temperature_use(const amrex::iMultiFab *lmask, const bool have_sst, const bool have_tsk)
Definition: ERF_CheckpointSurfaceTemperature.H:490
constexpr int contract_version
Definition: ERF_CheckpointSurfaceTemperature.H:38
StoredSurfaceTemperature classify_stored_surface_temperature(const int marker_version, const bool has_surface_arrays, const LegacyInitType legacy_init_type)
Definition: ERF_CheckpointSurfaceTemperature.H:227
SurfaceTemperatureMigrationPlan plan_surface_temperature_migration(const SurfaceTemperatureProvenance &provenance, const bool restart_reads_wrfinput, const std::string &checkpointname)
Definition: ERF_CheckpointSurfaceTemperature.H:336
LegacyConversionFailure potential_to_absolute_temperature(amrex::MultiFab &field, const erf_surface_temperature::SurfaceTemperatureSource source, const SurfaceTemperatureUse &use, const amrex::MultiFab &pressure, const amrex::Real rdOcp, const amrex::Periodicity &period)
Definition: ERF_CheckpointSurfaceTemperature.H:570
const char * legacy_init_type_name(const LegacyInitType type)
Definition: ERF_CheckpointSurfaceTemperature.H:111
constexpr const char * contract_file_name
Definition: ERF_CheckpointSurfaceTemperature.H:41
int first_legacy_surface_temperature_level(const std::string &checkpointname, const int finest_level)
Definition: ERF_CheckpointSurfaceTemperature.H:59
LegacyInitType
Definition: ERF_CheckpointSurfaceTemperature.H:80
constexpr const char * legacy_init_type_key
Definition: ERF_CheckpointSurfaceTemperature.H:44
SurfaceTemperatureMigration
Definition: ERF_CheckpointSurfaceTemperature.H:303
@ InputPressure
best available WRFInput pressure; refined regrids can make it approximate
@ None
they hold absolute temperature: restored as they are
@ RestartPressure
approximate: converted with the surface pressure of the restarted state
@ Reject
they cannot be migrated: the restart aborts, giving the reason
ContractReadStatus
Definition: ERF_CheckpointSurfaceTemperature.H:74
int first_started_later_init_file(const std::vector< double > &start_times, const double coarser_start, const double checkpoint_time)
Definition: ERF_CheckpointSurfaceTemperature.H:408
const char * surface_field_name(const erf_surface_temperature::SurfaceTemperatureSource source)
Definition: ERF_CheckpointSurfaceTemperature.H:514
ProvenanceOrigin
Definition: ERF_CheckpointSurfaceTemperature.H:246
@ Assertion
erf.legacy_surface_temperature_init_type, in the inputs of the restart
@ JobInfo
the erf.init_type recorded in the job_info of the checkpoint
void fill_outside_domain_from_nearest(amrex::MultiFab &mf, const amrex::Geometry &geom)
Definition: ERF_CheckpointSurfaceTemperature.H:763
StoredSurfaceTemperature
Definition: ERF_CheckpointSurfaceTemperature.H:89
@ Potential
potential temperature, converted to absolute temperature on restart
@ Absolute
absolute temperature [K], restored as it is
@ UnknownProvenance
no marker, and the init type that wrote them is not known
LegacyInitType parse_legacy_init_type_from_job_info(std::istream &input)
Definition: ERF_CheckpointSurfaceTemperature.H:151
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real restart_surface_pressure(const bool has_ground_coverage, const amrex::Real ground_pressure, const amrex::Real parent_ground_pressure)
Definition: ERF_CheckpointSurfaceTemperature.H:505
LegacySurfacePressureSource legacy_wrfinput_pressure_source(const int lev, const int num_own_init_files, const bool later_init_file_started, const bool level0_reads_low_file, const bool has_own_low_file, const bool coarser_level_recovered)
Definition: ERF_CheckpointSurfaceTemperature.H:443
void abort_on_legacy_conversion_failure(const LegacyConversionFailure &fail, const erf_surface_temperature::SurfaceTemperatureSource source, const std::string &what)
Definition: ERF_CheckpointSurfaceTemperature.H:716
void write_contract_version(std::ostream &output)
Definition: ERF_CheckpointSurfaceTemperature.H:47
SurfaceTemperatureProvenance read_surface_temperature_provenance(const std::string &checkpointname, const int finest_level)
Definition: ERF_CheckpointSurfaceTemperature.H:799
SurfaceTemperatureProvenance resolve_surface_temperature_provenance(const int marker_version, const int first_level, const LegacyInitType job_info_source, const LegacyInitType asserted_source)
Definition: ERF_CheckpointSurfaceTemperature.H:278
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE bool sst_ignored(const bool ignore_sst_requested, const bool have_tsk)
Definition: ERF_SurfaceTemperature.H:189
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE SurfaceTemperatureSource surface_temperature_source(const bool is_land, const bool have_tsk, const bool ignore_sst)
Definition: ERF_SurfaceTemperature.H:205
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE bool theta_to_temperature(const amrex::Real theta, const amrex::Real pressure, const amrex::Real rdOcp, amrex::Real &temperature)
Definition: ERF_SurfaceTemperature.H:136
SurfaceTemperatureSource
Definition: ERF_SurfaceTemperature.H:176
@ prescribed
the prescribed land surface potential temperature (most.pot_surf_temp)
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE bool valid_temperature(const amrex::Real temperature)
Definition: ERF_SurfaceTemperature.H:129
Definition: ERF_CheckpointSurfaceTemperature.H:523
amrex::Real theta
Definition: ERF_CheckpointSurfaceTemperature.H:533
int used
whether the surface layer takes the field there
Definition: ERF_CheckpointSurfaceTemperature.H:531
int preserved
valid cells left as they are: placeholders where the field is not used
Definition: ERF_CheckpointSurfaceTemperature.H:526
int ghost_count
ghost cells among count
Definition: ERF_CheckpointSurfaceTemperature.H:525
int land
its land mask
Definition: ERF_CheckpointSurfaceTemperature.H:530
int count
cells that could not be converted or reconstructed
Definition: ERF_CheckpointSurfaceTemperature.H:524
int i
Definition: ERF_CheckpointSurfaceTemperature.H:528
amrex::Real pressure
Definition: ERF_CheckpointSurfaceTemperature.H:534
int j
Definition: ERF_CheckpointSurfaceTemperature.H:529
int ghost
whether the first failure is a ghost cell
Definition: ERF_CheckpointSurfaceTemperature.H:532
int claimed
whether the first cell that could not be converted is described below
Definition: ERF_CheckpointSurfaceTemperature.H:527
Definition: ERF_CheckpointSurfaceTemperature.H:310
std::string reason
for Reject: what is missing, and how to supply it
Definition: ERF_CheckpointSurfaceTemperature.H:313
SurfaceTemperatureMigration method
Definition: ERF_CheckpointSurfaceTemperature.H:311
SurfaceTemperatureProvenance provenance
what the decision was made from
Definition: ERF_CheckpointSurfaceTemperature.H:312
Definition: ERF_CheckpointSurfaceTemperature.H:255
LegacyInitType source
init type that wrote them
Definition: ERF_CheckpointSurfaceTemperature.H:258
LegacyInitType asserted
init type the restart inputs assert
Definition: ERF_CheckpointSurfaceTemperature.H:260
ProvenanceOrigin origin
where source was learned from
Definition: ERF_CheckpointSurfaceTemperature.H:259
StoredSurfaceTemperature stored
Definition: ERF_CheckpointSurfaceTemperature.H:261
int marker_version
version of the contract marker, 0 if there is none
Definition: ERF_CheckpointSurfaceTemperature.H:256
int first_level
first AMR level holding SST_0 or TSK_0, -1 if none does
Definition: ERF_CheckpointSurfaceTemperature.H:257
Definition: ERF_CheckpointSurfaceTemperature.H:470
bool ignore_sst
whether its surface layer ignores the SST
Definition: ERF_CheckpointSurfaceTemperature.H:474
const amrex::iMultiFab * lmask
land mask; without one, every cell is land
Definition: ERF_CheckpointSurfaceTemperature.H:471
bool have_sst
whether the level has an SST
Definition: ERF_CheckpointSurfaceTemperature.H:472
bool have_tsk
whether the level has TSK
Definition: ERF_CheckpointSurfaceTemperature.H:473