ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_ComputeDiffusivityYSU.cpp File Reference
#include <algorithm>
#include <AMReX_Math.H>
#include "ERF_SurfaceLayer.H"
#include "ERF_DirectionSelector.H"
#include "ERF_Diffusion.H"
#include "ERF_Constants.H"
#include "ERF_TurbStruct.H"
#include "ERF_PBLModels.H"
#include "ERF_PBLRibCrossing.H"
#include "ERF_TileNoZ.H"
#include "ERF_MoistUtils.H"
#include <cmath>
Include dependency graph for ERF_ComputeDiffusivityYSU.cpp:

Functions

void ComputeDiffusivityYSU (const MultiFab &xvel, const MultiFab &yvel, const MultiFab &cons_in, MultiFab &eddyViscosity, const Geometry &geom, const TurbChoice &turbChoice, std::unique_ptr< SurfaceLayer > &SurfLayer, bool use_terrain_fitted_coords, bool use_moisture, int level, const BCRec *bc_ptr, bool, const std::unique_ptr< MultiFab > &z_phys_nd, const std::unique_ptr< MultiFab > &z_sfc_nd, const std::unique_ptr< MultiFab > &z_phys_cc, const MoistureComponentIndices &moisture_indices, const MultiFab *qheating_rates, const MultiFab *terrain_blank)
 

Function Documentation

◆ ComputeDiffusivityYSU()

void ComputeDiffusivityYSU ( const MultiFab &  xvel,
const MultiFab &  yvel,
const MultiFab &  cons_in,
MultiFab &  eddyViscosity,
const Geometry &  geom,
const TurbChoice &  turbChoice,
std::unique_ptr< SurfaceLayer > &  SurfLayer,
bool  use_terrain_fitted_coords,
bool  use_moisture,
int  level,
const BCRec *  bc_ptr,
bool  ,
const std::unique_ptr< MultiFab > &  z_phys_nd,
const std::unique_ptr< MultiFab > &  z_sfc_nd,
const std::unique_ptr< MultiFab > &  z_phys_cc,
const MoistureComponentIndices &  moisture_indices,
const MultiFab *  qheating_rates,
const MultiFab *  terrain_blank 
)

Compute vertical eddy viscosity coefficients using the Yonsei University (YSU) boundary layer scheme.

Parameters
[in]xvelX-velocity field.
[in]yvelY-velocity field.
[in]cons_inInput conservative variables.
[out]eddyViscosityMultiFab to store computed eddy viscosity and countergradient terms.
[in]geomGeometry used for grid spacings and domain extent.
[in]turbChoiceTurbulence model configuration and parameters.
[in]SurfLayerPointer to surface layer data.
[in]use_terrain_fitted_coordsUse terrain-fitted coordinates if true.
[in]use_moistureInclude moisture in the diffusivity calculation.
[in]levelCurrent AMR level.
[in]bc_ptrBoundary condition records.
[in]vert_onlyReserved flag for vertical-only computation.
[in]z_phys_ndNodal physical height field.
[in]z_sfc_ndNodal heights of the bottom of the domain
[in]z_phys_ccCell-centered physical height field.
[in]moisture_indicesIndices for moisture variables in the state vector.
[in]qheating_ratesOptional heating rates for cloud-top mixing.
63 {
64  const StratType pbl_strat = turbChoice.pbl_strat_type;
65  /*
66  ============================================================================
67  Yonsei University (YSU) Boundary Layer Parameterization Scheme
68  ============================================================================
69 
70  Implementation of the YSU boundary layer scheme based on:
71  - Hong, S.-Y., Y. Noh, and J. Dudhia, 2006: A new vertical diffusion
72  package with an explicit treatment of entrainment processes.
73  Monthly Weather Review, 134, 2318-2341. [HND06]
74  https://doi.org/10.1175/MWR3199.1
75  - Hong, S.-Y., 2010: A new stable boundary-layer mixing scheme and
76  its impact on the simulated East Asian summer monsoon.
77  Quarterly Journal of the Royal Meteorological Society, 136, 1481-1496. [H10]
78  https://doi.org/10.1002/qj.665
79  - WRF Reference Implementation: module_bl_ysu.F
80  https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F
81 
82  CORE ALGORITHM (HND06):
83  -----------------------
84  1. Three-Pass Bulk Richardson Number (Rib) PBL Height Diagnosis
85  Pass 1: Ribcr=f(surface type), base surface θ_v (predictor)
86  Pass 2: Same Ribcr, enhanced surface θ_v + VPERT (corrector)
87  Pass 3: Ribcr=0 diagnostic, gives mixed-layer depth h_ze
88 
89  2. Nonlocal Countergradient Flux Corrections
90  HGAMT = -const_b * u_* * θ_* / wscale (capped at GAMCRT=3K)
91  HGAMQ = -const_b * u_* * q_* / wscale (capped at GAMCRQ=2e-3)
92  VPERT = max(HGAMT + 0.61*θ*HGAMQ, 0)
93 
94  3. K-Profile Below PBL (HND06 Eq. A1):
95  K_m = ρ * wscale * κ * z * (1 - z/h)^pfac
96  K_t = K_m / Pr_t
97  wscale = (u_*³ + phifac * κ * wstar_conv³ * (1-zfac))^(1/3)
98 
99  4. Explicit Entrainment at PBL Top (WRF bl_ysu.F90 lines 831-925):
100  K_entr = ρ * |we| * dz at k = kpbl (applied only when we < 0)
101  wm3 = wstar³ + 5*u_*³
102  bfxpbl = -0.15 * θv(klo)/g * wm3 / pblh
103  dthvx = max(θv(kpbl+1) - θv(kpbl), 1e-2)
104  we = max(bfxpbl/dthvx, -sqrt(wm3^(2/3)))
105 
106  5. Free Atmosphere / Stable PBL (H10, YSU Appendix A):
107  Ri_g-dependent mixing with grid-adaptive length scale
108  λ = min(max(0.1*dz, 30m), 300m)
109  l = λ * κz / (λ + κz)
110  Optional QNSE stability functions (Sukoriansky et al. 2005):
111  - If enable_qnse_stable_functions=true, replace linear stable stability
112  functions with bounded rational QNSE functions:
113  phi_m = (1 + qnse_am * zeta) / (1 + qnse_bm * zeta)
114  phi_h = (1 + qnse_ah * zeta) / (1 + qnse_bh * zeta)
115  where zeta = sf * h/L, avoiding unbounded growth at large stability
116 
117  PARAMETER DEFAULTS (Matching WRF-YSU):
118  ----------------------------------------
119  const_b = 7.8 (CFAC: countergradient coefficient)
120  sf = 0.1 (SFCFRAC: surface layer depth fraction)
121  phifac = 8.0 (PHIFAC: convective wscale weight)
122  pfac = 2.0 (profile shape exponent)
123  GAMCRT = 3.0 K (max heat countergradient)
124  GAMCRQ = 2e-3 (max moisture countergradient)
125  Ribcr land= 0.25 (critical bulk Richardson number over land)
126  QNSE default coefficients: qnse_am/qnse_bm/qnse_ah/qnse_bh = 2.5/0.2/2.5/0.2
127  */
128 
129  // Domain extent in z-dir
130  int klo = geom.Domain().smallEnd(2);
131  int khi = geom.Domain().bigEnd(2);
132  const int izmin = klo;
133  const int izmax = khi;
134 
135  const Real dz = geom.CellSize(2);
136  const Real dz_inv = geom.InvCellSize(2);
137  const auto& dxInv = geom.InvCellSizeArray();
138 
139  // Collect the YSU-computed PBLH for writing back to SurfaceLayer.
140  // NOTE: OpenMP is not used here; if re-enabled, this MultiFab must remain
141  // outside any omp parallel structured block to avoid undefined behavior.
142  MultiFab pblh_mf(eddyViscosity.boxArray(), eddyViscosity.DistributionMap(), 1, 0);
143  pblh_mf.setVal(0.0);
144 
145  // PBLH smoothing reads one column per pass outside the cells it writes, so the
146  // work arrays have to carry that many columns of halo and the PBLH passes have
147  // to fill them: otherwise the stencil reads off the end of the tile and the
148  // answer depends on the decomposition. With smoothing off this is the single
149  // column of halo the diffusivity kernels already use, so nothing changes.
150  const int ng_pblh = (turbChoice.enable_pblh_smoothing)
151  ? std::max(1, turbChoice.pblh_smoothing_passes) : 1;
152 
153  // The surface-layer fields carry one column of halo on the bottom surface, and the
154  // radiative heating rates one; with more smoothing passes than that, the PBLH passes
155  // read them from copies widened to ng_pblh (see WidenForPBLH). Otherwise the fields
156  // are read directly.
157  const auto needs_widening = [&] (const MultiFab* mf) {
158  return mf != nullptr && std::min(mf->nGrowVect()[0], mf->nGrowVect()[1]) < ng_pblh;
159  };
160  const auto widen_sfc = [&] (const MultiFab* mf) -> std::unique_ptr<MultiFab> {
161  if (!needs_widening(mf)) { return nullptr; }
162  return WidenForPBLH(*mf, ng_pblh,
163  [&] (MultiFab& wide) { SurfLayer->fill_planar_boundary(level, wide); });
164  };
165  const std::unique_ptr<MultiFab> u_star_wide = widen_sfc(SurfLayer->get_u_star(level));
166  const std::unique_ptr<MultiFab> t_star_wide = widen_sfc(SurfLayer->get_t_star(level));
167  const std::unique_ptr<MultiFab> q_star_wide = widen_sfc(SurfLayer->get_q_star(level));
168  const std::unique_ptr<MultiFab> olen_wide = widen_sfc(SurfLayer->get_olen(level));
169  const std::unique_ptr<MultiFab> z0_wide = widen_sfc(SurfLayer->get_z0(level));
170  const std::unique_ptr<MultiFab> qheat_wide = (needs_widening(qheating_rates))
171  ? WidenForPBLH(*qheating_rates, ng_pblh,
172  [&] (MultiFab& wide) { wide.FillBoundary(geom.periodicity()); })
173  : nullptr;
174  const MultiFab* u_star_src = (u_star_wide) ? u_star_wide.get() : SurfLayer->get_u_star(level);
175  const similarity_funs l_sfuns = SurfLayer->similarity_functions();
176  const MultiFab* t_star_src = (t_star_wide) ? t_star_wide.get() : SurfLayer->get_t_star(level);
177  const MultiFab* q_star_src = (q_star_wide) ? q_star_wide.get() : SurfLayer->get_q_star(level);
178  const MultiFab* olen_src = (olen_wide) ? olen_wide.get() : SurfLayer->get_olen(level);
179  const MultiFab* z0_src = (z0_wide) ? z0_wide.get() : SurfLayer->get_z0(level);
180  const MultiFab* qheat_src = (qheat_wide) ? qheat_wide.get() : qheating_rates;
181 
182  if (ng_pblh > 1) {
183  int ng_avail = std::min({cons_in.nGrowVect()[0], cons_in.nGrowVect()[1],
184  xvel.nGrowVect()[0], xvel.nGrowVect()[1],
185  yvel.nGrowVect()[0], yvel.nGrowVect()[1],
186  u_star_src->nGrowVect()[0], u_star_src->nGrowVect()[1],
187  olen_src->nGrowVect()[0], olen_src->nGrowVect()[1],
188  (terrain_blank) ? terrain_blank->nGrowVect()[0] : 1000,
189  (terrain_blank) ? terrain_blank->nGrowVect()[1] : 1000});
190  // The PBLH passes also read these fields over the same widened region;
191  // a field that is not allocated (nullptr) is not read.
192  auto limit_by = [&ng_avail] (const auto* mf) {
193  if (mf) { ng_avail = std::min({ng_avail, mf->nGrowVect()[0], mf->nGrowVect()[1]}); }
194  };
195  limit_by(t_star_src);
196  limit_by(q_star_src);
197  limit_by(SurfLayer->get_mac_avg(level, 3));
198  limit_by(SurfLayer->get_mac_avg(level, 4));
199  limit_by(SurfLayer->get_mac_avg(level, 6));
200  limit_by(z0_src);
201  limit_by(SurfLayer->get_lmask(level));
202  limit_by(z_phys_nd.get());
203  limit_by(z_sfc_nd.get());
204  limit_by(qheat_src);
205  if (ng_pblh > ng_avail) {
206  amrex::Abort("erf.pblh_smoothing_passes = " + std::to_string(turbChoice.pblh_smoothing_passes)
207  + " needs " + std::to_string(ng_pblh) + " halo columns, but the fields the "
208  "PBLH passes read carry only " + std::to_string(ng_avail)
209  + "; reduce erf.pblh_smoothing_passes to at most " + std::to_string(ng_avail));
210  }
211  }
212 
213 #ifdef _OPENMP
214 #pragma omp parallel if (Gpu::notInLaunchRegion())
215 #endif
216 
217  for (MFIter mfi(eddyViscosity, TileNoZ()); mfi.isValid(); ++mfi) {
218 
219  // Box operated on must span fill domain in z-dir
220  const Box& gbx = mfi.growntilebox(IntVect(1,1,0));
221  AMREX_ALWAYS_ASSERT( gbx.smallEnd(2) == klo &&
222  gbx.bigEnd(2) == khi );
223 
224  //
225  // PREDICTOR: Compute the height of the PBL without thermal excess
226  // From Hong et al. 2006, Eqns. 1 & 2:
227  //
228  // h = Rib_cf * theta_va * | U(h) |^2 / (g * (theta_v(h) - theta_s))
229  //
230  // where the surface virtual potential temperature is
231  //
232  // theta_s = theta_va + theta_T
233  //
234  // and here the thermal excess theta_T = zero
235  //
236  // WRF reference (module_bl_ysu.F lines 100-130):
237  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F#L100-L130
238 
239  // create flattened boxes to store PBL height and related quantities
240  const Box xybx = PerpendicularBox<ZDir>(gbx, IntVect{0, 0, 0});
241 
242  // The PBLH passes run on the region the smoothing stencil will consume
243  // (see ng_pblh above). growntilebox() is no use here: it does not grow at
244  // an interior tile edge, so a tile in the middle of a box gets no halo at
245  // all -- which is exactly how the stencil came to read off the end of the
246  // array. Grow the tile box explicitly instead, which costs a little
247  // duplicated work in the overlaps. With smoothing off these are gbx and
248  // xybx and nothing is duplicated.
249  const Box gbx_work = (turbChoice.enable_pblh_smoothing)
250  ? amrex::grow(mfi.tilebox(), IntVect(ng_pblh,ng_pblh,0)) : gbx;
251  const Box xybx_work = PerpendicularBox<ZDir>(gbx_work, IntVect{0, 0, 0});
252  const Box xybx_tile = PerpendicularBox<ZDir>(mfi.tilebox(), IntVect{0, 0, 0});
253  FArrayBox pbl_height_corrector(xybx_work, 1, The_Async_Arena());
254  IArrayBox pbl_index(xybx_work, 1, The_Async_Arena());
255  IArrayBox pbl_index_zero_ri(xybx_work, 1, The_Async_Arena()); // Index for zero-Ri diagnostic pass
256  FArrayBox hgamt_fab(xybx_work, 1, The_Async_Arena()); // Store HGAMT/h (normalized countergradient)
257  FArrayBox hgamq_fab(xybx_work, 1, The_Async_Arena()); // Store HGAMQ/h (normalized countergradient)
258  FArrayBox hgamu_fab(xybx_work, 1, The_Async_Arena()); // Store HGAMU (YSU u countergradient)
259  FArrayBox hgamv_fab(xybx_work, 1, The_Async_Arena()); // Store HGAMV (YSU v countergradient)
260  FArrayBox wstar_fab(xybx_work, 1, The_Async_Arena()); // Convective velocity scale computed with pblh_corr
261  FArrayBox vpert_fab(xybx_work, 1, The_Async_Arena()); // Virtual temperature perturbation VPERT for Pass 3
262  FArrayBox entr_fab(xybx_work, 1, The_Async_Arena()); // Per-column entrainment diffusivity
263  IArrayBox cloud_top_fab(xybx_work, 1, The_Async_Arena()); // Cloud-top cell index for top-down mixing
264  FArrayBox wstar3_down_fab(xybx_work, 1, The_Async_Arena()); // Top-down convective velocity scale cubed
265  FArrayBox sflux_fab(xybx_work, 1, The_Async_Arena()); // Virtual kinematic heat flux (sensible + latent)
266  FArrayBox wstar3_fab(xybx_work, 1, The_Async_Arena()); // Convective velocity scale cubed per column
267  FArrayBox zol1_fab(xybx_work, 1, The_Async_Arena()); // Monin-Obukhov stability parameter at first level
268  FArrayBox sfcflg_fab(xybx_work, 1, The_Async_Arena()); // Surface stability flag: 1=unstable/neutral, 0=stable
269  // REQUIRED: zero-initialize all FArrayBoxes before GPU kernels read them.
270  // The_Async_Arena() does not zero memory; reading uninitialized data
271  // corrupts rib_enhan_arr (via vpert_arr) and SFCFLG (via sflux_arr).
272  vpert_fab.setVal<RunOn::Device>(zero);
273  sflux_fab.setVal<RunOn::Device>(zero);
274  wstar3_fab.setVal<RunOn::Device>(zero);
275  wstar3_down_fab.setVal<RunOn::Device>(zero);
276  sfcflg_fab.setVal<RunOn::Device>(zero);
277  hgamt_fab.setVal<RunOn::Device>(zero);
278  hgamq_fab.setVal<RunOn::Device>(zero);
279  hgamu_fab.setVal<RunOn::Device>(zero);
280  hgamv_fab.setVal<RunOn::Device>(zero);
281  wstar_fab.setVal<RunOn::Device>(zero);
282  entr_fab.setVal<RunOn::Device>(zero);
283  pbl_height_corrector.setVal<RunOn::Device>(zero);
284  const auto& pblh_corr_arr = pbl_height_corrector.array();
285  const auto& pbli_arr = pbl_index.array();
286  const auto& pbli_zero_arr = pbl_index_zero_ri.array(); // Zero-Ri diagnostic PBL index
287  const auto& hgamt_arr = hgamt_fab.array();
288  const auto& hgamq_arr = hgamq_fab.array();
289  const auto& hgamu_arr = hgamu_fab.array();
290  const auto& hgamv_arr = hgamv_fab.array();
291  const auto& wstar_arr = wstar_fab.array(); // Stored convective velocity for use in K-profile
292  const auto& vpert_arr = vpert_fab.array(); // Stored VPERT for Pass 3 diagnostic loop
293  const auto& entr_arr = entr_fab.array(); // Stored entrainment diffusivity
294  const auto& cloud_top_arr = cloud_top_fab.array(); // Cloud-top cell index for top-down mixing
295  const auto& wstar3_down_arr = wstar3_down_fab.array(); // Top-down wstar cubed
296  const auto& sflux_arr = sflux_fab.array(); // Virtual kinematic heat flux
297  const auto& wstar3_arr = wstar3_fab.array(); // Convective velocity scale cubed
298  const auto& zol1_arr = zol1_fab.array(); // Monin-Obukhov stability parameter
299  const auto& sfcflg_arr = sfcflg_fab.array(); // Surface stability flag (1=unstable/neutral, 0=stable)
300 
301  // Get some data in arrays
302  const auto& cell_data = cons_in.const_array(mfi);
303  const auto& uvel = xvel.const_array(mfi);
304  const auto& vvel = yvel.const_array(mfi);
305 
306  //const Real Ribcr = turbChoice.pbl_mrf_Ribcr; // Now surface-type-dependent in YSU
307  //const Real f0 = turbChoice.pbl_mrf_coriolis_freq;
308  const auto& u_star_arr = u_star_src->const_array(mfi);
309  const auto& t_star_arr = t_star_src->const_array(mfi);
310  const auto& q_star_arr = q_star_src->const_array(mfi);
311  const auto& l_obuk_arr = olen_src->const_array(mfi);
312  const auto& t10av_arr = SurfLayer->get_mac_avg(level, 3)->const_array(mfi);
313  const auto& q10av_arr = SurfLayer->get_mac_avg(level, 4)->const_array(mfi);
314  const auto& ws10av_arr = SurfLayer->get_mac_avg(level, 6)->const_array(mfi); // 10m wind speed for Rossby number
315  const auto& z0_arr = z0_src->const_array(mfi); // Roughness length for Rossby number
316  //const auto& t_surf_arr = SurfLayer->get_t_surf(level)->const_array(mfi);
317  // Get land/water mask for proper handling of moisture countergradient
318  const auto& lmask_arr = (SurfLayer->get_lmask(level)) ?
319  SurfLayer->get_lmask(level)->const_array(mfi) :
320  Array4<int>{};
321 
322  // --------------------------------------------------------------------
323  // Immersed-boundary awareness (turbChoice.pbl_ib_aware), as in the MRF
324  // scheme: per column the first fluid cell above the immersed solid
325  // (ksurf) and its height (zib); the surface height z_sfc of every
326  // kernel below becomes zib, indices at the surface become ksurf, the
327  // diffusivities vanish inside the solid, and the surface scales of a
328  // column with solid cells are a neutral log law at its top. With the
329  // option off, or without immersed cells, everything reduces to the
330  // original arithmetic.
331  // --------------------------------------------------------------------
332  const bool l_ib = turbChoice.pbl_ib_aware && (terrain_blank != nullptr);
333  AMREX_ALWAYS_ASSERT_WITH_MESSAGE(!(l_ib && use_terrain_fitted_coords),
334  "erf.pbl_ib_aware is not supported with terrain-fitted coordinates");
335  const Array4<Real const> blank_arr = l_ib ? terrain_blank->const_array(mfi) : Array4<Real const>{};
336  IArrayBox ksurf_fab(xybx_work, 1, The_Async_Arena());
337  FArrayBox zib_fab(xybx_work, 1, The_Async_Arena());
338  FArrayBox pblh_floor_fab(xybx_work, 1, The_Async_Arena()); // floor of the corrected height per column, reapplied after the smoothing
339  IArrayBox pbl_open_fab(xybx_work, 1, The_Async_Arena()); // 1 where the corrector found no Ribcr crossing up to khi
340  FArrayBox us_eff_fab(xybx_work, 1, The_Async_Arena()), ts_eff_fab(xybx_work, 1, The_Async_Arena());
341  FArrayBox qs_eff_fab(xybx_work, 1, The_Async_Arena()), ol_eff_fab(xybx_work, 1, The_Async_Arena());
342  FArrayBox t10_eff_fab(xybx_work, 1, The_Async_Arena()), q10_eff_fab(xybx_work, 1, The_Async_Arena());
343  FArrayBox ws10_eff_fab(xybx_work, 1, The_Async_Arena()), z0_eff_fab(xybx_work, 1, The_Async_Arena());
344  const auto& ksurf_arr = ksurf_fab.array();
345  const auto& zib_arr = zib_fab.array();
346  const auto& pblh_floor_arr = pblh_floor_fab.array();
347  const auto& pbl_open_arr = pbl_open_fab.array();
348  const auto& us_eff_arr = us_eff_fab.array(); const auto& ts_eff_arr = ts_eff_fab.array();
349  const auto& qs_eff_arr = qs_eff_fab.array(); const auto& ol_eff_arr = ol_eff_fab.array();
350  const auto& t10_eff_arr = t10_eff_fab.array(); const auto& q10_eff_arr = q10_eff_fab.array();
351  const auto& ws10_eff_arr = ws10_eff_fab.array(); const auto& z0_eff_arr = z0_eff_fab.array();
352  {
353  const Real dz_ib = geom.CellSize(2);
354  const Real z0_ib = turbChoice.pbl_ib_z0;
355  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
356  {
357  int ks = klo;
358  if (l_ib) {
359  for (int kk = klo; kk <= khi; ++kk) { if (blank_arr(i, j, kk) >= Real(0.5)) { ks = kk + 1; } }
360  if (ks > khi) { ks = khi; }
361  }
362  ksurf_arr(i, j, 0) = ks;
363  zib_arr(i, j, 0) = (ks - klo) * dz_ib;
364  if (ks > klo) {
365  const Real u_top = myhalf * (uvel(i, j, ks) + uvel(i + 1, j, ks));
366  const Real v_top = myhalf * (vvel(i, j, ks) + vvel(i, j + 1, ks));
367  const Real ws_top = std::sqrt(u_top * u_top + v_top * v_top);
368  us_eff_arr(i, j, 0) = amrex::max(KAPPA * ws_top / std::log(myhalf * dz_ib / z0_ib), Real(1.0e-3));
369  ts_eff_arr(i, j, 0) = Real(0);
370  qs_eff_arr(i, j, 0) = Real(0);
371  ol_eff_arr(i, j, 0) = immersed_neutral_obukhov_length;
372  t10_eff_arr(i, j, 0) = cell_data(i, j, ks, RhoTheta_comp) / cell_data(i, j, ks, Rho_comp);
373  q10_eff_arr(i, j, 0) = (use_moisture && moisture_indices.qv >= 0)
374  ? cell_data(i, j, ks, moisture_indices.qv) / cell_data(i, j, ks, Rho_comp) : Real(0);
375  ws10_eff_arr(i, j, 0) = ws_top;
376  z0_eff_arr(i, j, 0) = z0_ib;
377  } else {
378  us_eff_arr(i, j, 0) = u_star_arr(i, j, 0);
379  ts_eff_arr(i, j, 0) = t_star_arr(i, j, 0);
380  qs_eff_arr(i, j, 0) = q_star_arr(i, j, 0);
381  ol_eff_arr(i, j, 0) = l_obuk_arr(i, j, 0);
382  t10_eff_arr(i, j, 0) = t10av_arr(i, j, 0);
383  q10_eff_arr(i, j, 0) = q10av_arr(i, j, 0);
384  ws10_eff_arr(i, j, 0) = ws10av_arr(i, j, 0);
385  z0_eff_arr(i, j, 0) = z0_arr(i, j, 0);
386  }
387  });
388  }
389  const Array4<Real const> z_nd_arr = z_phys_nd->array(mfi);
390  const Array4<Real const> z_sfc_arr = z_sfc_nd->const_array(mfi);
391  const PBLDerivativeDzInv_T pbl_derivative_dz_inv{z_phys_cc->const_array(mfi)};
392  // Get qheating_rates if provided (for LW radiation coupling to top-down mixing)
393  const Array4<Real const> qheat_arr = (qheat_src != nullptr)
394  ? qheat_src->const_array(mfi)
395  : Array4<Real const>{};
396  const bool has_qheating_rates = (qheating_rates != nullptr);
397 
398 
399  // ========================================================================
400  // PRE-COMPUTE Rib ARRAYS FOR GPU PERFORMANCE
401  // ========================================================================
402  // Pre-compute both base (without VPERT) and enhanced (with VPERT) Richardson numbers
403  // in a single vectorized kernel to reduce divergent control flow in subsequent PBLH loops.
404  // This improves GPU performance by eliminating serial while-loops in favor of simple
405  // array lookups during the three PBLH pass loops.
406  //
407  FArrayBox rib_base_fab(gbx_work, 1, The_Async_Arena()); // Rib with base t_layer_v
408  FArrayBox rib_enhan_fab(gbx_work, 1, The_Async_Arena()); // Rib with enhanced t_layer_v+VPERT
409  const auto& rib_base_arr = rib_base_fab.array();
410  const auto& rib_enhan_arr = rib_enhan_fab.array();
411 
412  BL_PROFILE_VAR("YSU_Rib_Precompute", prof_rib_precomp);
413  ParallelFor(gbx_work, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
414  {
415  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
416  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
417  const amrex::Real t_layer = t10_eff_arr(i, j, 0);
418  const amrex::Real q_frac = use_moisture ? q10_eff_arr(i, j, 0) : zero;
419  const amrex::Real t_layer_v = t_layer * (one + epsv * q_frac);
420  // On first call, vpert_arr is initialized to zero
421  const amrex::Real t_enh = t_layer_v + vpert_arr(i,j,0);
422  // Rib uses the height above the ground (WRF za). zib is the column's immersed
423  // surface with erf.pbl_ib_aware and zero otherwise; that option is off on
424  // terrain-fitted meshes, where Compute_Zrel_AtCellCenter already measures from the ground
425  const amrex::Real z_sfc = zib;
426  const amrex::Real zval = (use_terrain_fitted_coords)
427  ? Compute_Zrel_AtCellCenter(i,j,k,z_sfc_arr,z_nd_arr)
428  : (k + myhalf) * dz;
429  const amrex::Real zrel = amrex::max(zval - z_sfc, amrex::Real(1.0e-4));
430  const amrex::Real theta_v = GetThetav(i,j,k,cell_data,moisture_indices);
431  const amrex::Real theta_v_klo = GetThetav(i,j,ksrf,cell_data,moisture_indices);
432  const amrex::Real ws2_raw = fourth * ((uvel(i,j,k)+uvel(i+1,j,k))*(uvel(i,j,k)+uvel(i+1,j,k))
433  + (vvel(i,j,k)+vvel(i,j+1,k))*(vvel(i,j,k)+vvel(i,j+1,k)));
434  // Vogelezang & Holtslag (1996): Add shear correction term to denominator instead of ad-hoc floor
435  // to better represent shear associated with surface-layer turbulence at low wind speeds.
436  // Reference: Vogelezang, D.H.P., and A.A.M. Holtslag, 1996: Evaluation and model impacts of
437  // alternative boundary-layer height formulations. Boundary-Layer Meteorology, 81, 245–269.
438  const amrex::Real ws2 = (turbChoice.enable_vh96_shear_correction)
439  ? (ws2_raw + turbChoice.vh96_shear_const_b * us_eff_arr(i,j,0) * us_eff_arr(i,j,0))
440  : amrex::max(ws2_raw, amrex::Real(1.0));
441  rib_base_arr(i,j,k) = CONST_GRAV * zrel * (theta_v - t_layer_v) / (ws2 * theta_v_klo);
442  rib_enhan_arr(i,j,k) = CONST_GRAV * zrel * (theta_v - t_enh) / (ws2 * theta_v_klo);
443  });
444  BL_PROFILE_VAR_STOP(prof_rib_precomp);
445 
446  // ========================================================================
447  // PRE-COMPUTE surface flux (sflux), stability flag (sfcflg), and convective
448  // velocity scale (wstar3) per column, following WRF-YSU formulation
449  // ========================================================================
450  // WRF Reference: module_bl_ysu.F lines 610-680
451  // These quantities are needed for:
452  // - Stability-dependent functions throughout the PBLH passes
453  // - Countergradient flux calculations (HGAMT, HGAMQ)
454  // - K-profile computations
455  // Computing them once per column improves GPU performance and ensures consistency.
456  //
457  BL_PROFILE_VAR("YSU_SurfFlux_Precompute", prof_sflux_precomp);
458  ParallelFor(xybx_work, [=, zero_d=zero] AMREX_GPU_DEVICE(int i, int j, int) noexcept
459  {
460  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
461  const Real rho_sfc = cell_data(i, j, ksrf, Rho_comp);
462  const Real t_layer = t10_eff_arr(i, j, 0); // Dry potential temperature at z1
463 
464  // WRF: rhox = psfc/(rd*tx(1)*tvcon), approximate with cell-bottom density
465  const Real rhox = rho_sfc;
466 
467  // Virtual temperature factor: ep1 = Rv/Rd - 1 = 0.608
468  constexpr Real ep1 = amrex::Real(0.608);
469  constexpr Real cp_air = amrex::Real(1004.0);
470 
471  // WRF bl_ysu.F90 line 613: sflux = hfx/(rho*cp) + qfx/rho*ep1*theta
472  // Approximate hfx and qfx from MOST quantities:
473  // hfx [W/m^2] = -rho * cp * u_star * t_star
474  // qfx [kg/m^2/s] = -rho * u_star * q_star
475  const Real ustar = us_eff_arr(i, j, 0);
476  const Real tstar = ts_eff_arr(i, j, 0);
477  const Real qstar = use_moisture ? qs_eff_arr(i, j, 0) : zero;
478  const Real hfx = -rhox * cp_air * ustar * tstar; // W/m^2
479  const Real qfx = -rhox * ustar * qstar; // kg/m^2/s
480  const Real sflux = hfx / (rhox * cp_air) + qfx / rhox * ep1 * t_layer;
481  sflux_arr(i, j, 0) = sflux;
482 
483  // WRF sfcflg: TRUE when unstable/neutral, FALSE when stable
484  // WRF bl_ysu.F90 line 615: if(br(i).gt.0.0) sfcflg(i) = .false.
485  // In ERF, br > 0 corresponds to sflux < 0 (stable), and a neutral
486  // surface (sflux = 0) is unstable/neutral, as in WRF. Over a neutral
487  // surface the flux is round-off: t_star comes from a plane-averaged
488  // theta that differs from the surface value in the last bits, and
489  // how depends on the box and tile decomposition. A flux within that
490  // round-off counts as neutral, so that it does not pick the branch.
491  const Real sflux_roundoff = Real(64.0) * real_eps * ustar * t_layer;
492  const bool sfcflg = (sflux >= -sflux_roundoff);
493  sfcflg_arr(i, j, 0) = sfcflg ? one : zero; // Store as scalar field for unified use
494 
495  // WRF: govrth = g/thx(1) — uses DRY theta at first level
496  const Real govrth = CONST_GRAV / t_layer;
497 
498  // WRF bl_ysu.F90 lines 664-668: wstar3 from sflux
499  // First-guess pblh needed for wstar3 — use nominal 500m for initial estimate
500  // wstar3 is refined in subsequent loop after corrector pblh is available
501  const Real pblh_guess = amrex::Real(500.0);
502  const Real bfx0 = amrex::max(sflux, zero_d);
503  const Real wstar3 = govrth * bfx0 * pblh_guess;
504  wstar3_arr(i, j, 0) = wstar3;
505 
506  // WRF bl_ysu.F90 line 676: wscale = (ust3 + phifac*karman*wstar3*0.5)^(1/3)
507  // The 0.5 factor is the column-average of (1-zfac) over the PBL depth
508  constexpr Real phifac = amrex::Real(8.0);
509  const Real ust3 = ustar * ustar * ustar;
510  Real wscale = std::cbrt(ust3 + phifac * KAPPA * wstar3 * amrex::Real(0.5));
511  // WRF bounds: min(wscale, ust*16), max(wscale, ust/5)
512  wscale = amrex::min(wscale, ustar * amrex::Real(16.0));
513  wscale = amrex::max(wscale, ustar / amrex::Real(5.0));
514  wstar_arr(i, j, 0) = wscale; // Store column-average wscale for HGAMT/HGAMQ
515 
516  // zol1: Monin-Obukhov stability parameter at first level
517  // WRF bl_ysu.F90 lines 651-662: zol1 = max(br*fm*fm/fh, rimin)
518  // Approximate: zol1 = z1 / L_obuk
519  Real obuk_val = ol_eff_arr(i, j, 0);
520  if (std::abs(obuk_val) < amrex::Real(1.0e-10)) {
521  obuk_val = (obuk_val >= zero) ? amrex::Real(1.0e-10) : amrex::Real(-1.0e-10);
522  }
523  const Real zl1 = (use_terrain_fitted_coords)
524  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
525  : (ksrf + myhalf) * dz;
526  Real zol1 = zl1 / obuk_val;
527  zol1 = amrex::max(zol1, amrex::Real(-100.0));
528  if (sfcflg) {
529  zol1 = amrex::min(zol1, amrex::Real(-1.0e-8));
530  } else {
531  zol1 = amrex::max(zol1, amrex::Real(1.0e-8));
532  }
533  zol1_arr(i, j, 0) = zol1;
534  });
535  BL_PROFILE_VAR_STOP(prof_sflux_precomp);
536 
537  // ========================================================================
538  // PASS 1 — PREDICTOR: Compute initial PBL index with surface-type-dependent
539  // critical Richardson number (Ribcr).
540  // ========================================================================
541  // WRF Reference: module_bl_ysu.F (Hong, Noh & Dudhia 2006, lines 1-100)
542  // Ribcr = 0.25 over land; Rossby-number-dependent over water (line 150-170).
543  // Rib = (g*z/θv0) * (θv(z) - θv_surf) / ws² (lines 180-200)
544  // References: Hong et al., Mon. Wea. Rev., 134, 2318-2341 (2006)
545  //
546 
547  BL_PROFILE_VAR("YSU_PBLH_Passes", prof_pblh);
548  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
549  {
550  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
551  // Determine surface-type-dependent critical Richardson number
552  // Over land: Ribcr = 0.25; over water: Ribcr depends on Rossby number
553  Real Ribcr;
554  {
555  bool over_land = (!lmask_arr) || (lmask_arr(i, j, 0) == 1);
556  if (over_land) {
557  Ribcr = turbChoice.pbl_ysu_land_Ribcr;
558  } else {
559  const Real z0 = z0_eff_arr(i, j, 0);
560  const Real ws_layer = ws10_eff_arr(i, j, 0);
561  const Real Rossby = ws_layer / (turbChoice.pbl_ysu_coriolis_freq * amrex::max(z0, Real(1.0e-4)));
562  Ribcr = amrex::min(Real(0.16) * std::pow(Real(1.0e-7) * Rossby, -Real(0.18)), Real(0.3));
563  }
564  }
565 
566  // Scan rib_base_arr(i,j,ksrf..khi) to find first crossing of Ribcr
567  // GAP 9: Seed from surface bulk Richardson number (WRF bl_ysu.F90 lines 620-621)
568  // WRF seeds the loop with br (surface bulk Ri) so ksrf is checked first.
569  int kpbl = ksrf;
570  Real Rib = rib_base_arr(i,j,ksrf); // Seed from surface level
571  bool above_critical = (Rib >= Ribcr); // Check if already above critical
572 
573  // Scan from ksrf+1 if not already above critical
574  for (int kk = ksrf+1; !above_critical && kk <= khi; ++kk) {
575  if (rib_base_arr(i,j,kk) >= Ribcr) {
576  kpbl = kk;
577  above_critical = true;
578  break;
579  }
580  kpbl = kk; // keep updating so kpbl = khi if never exceeded
581  }
582  pbli_arr(i, j, 0) = kpbl;
583  });
584  BL_PROFILE_VAR_STOP(prof_pblh);
585 
586  //
587  // FIRST ITERATION: Compute HGAMT/HGAMQ/VPERT using Pass 1 PBL height
588  // ========================================================================
589  // This produces initial estimates of countergradient corrections and VPERT,
590  // which will then be used to recompute rib_enhan_arr for a more accurate
591  // corrector pass.
592  //
593 
594  // (Reuse existing corrector loop code below, first pass...)
595 
596  //
597  // CORRECTOR: Apply YSU nonlocal countergradient correction (HGAMT/HGAMQ)
598  // following HND06 with countergradient modifications.
599  //
600  // This step raises the effective surface virtual potential temperature
601  // to account for convective contribution to buoyancy, leading to a
602  // higher diagnosed PBL height in unstable conditions.
603  //
604  // WRF reference:
605  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F
606  //
607  // WRF constants (module_bl_ysu.F lines 100-120):
608  // RLAM = 150. (mixing length scale in free atm., m)
609  // PRMIN = 0.5 (minimum Prandtl number)
610  // PRMAX = 4.0 (maximum Prandtl number)
611  // BRCR = 0.25 (bulk Richardson number critical value over land)
612  // CFAC = 7.8 (= const_b, surface layer factor in countergradient term)
613  // PHIFAC = 8.0 (phifac: convective wscale weight)
614  // SFCFRAC= 0.1 (surface layer depth fraction)
615  // GAMCRT = 3.0 (maximum heat countergradient, K)
616  // GAMCRQ = 2.e-3 (maximum moisture countergradient, kg/kg)
617  //
618  // WRF formulas (module_bl_ysu.F lines 220-260):
619  // GAMFAC = CFAC / (rho * wscale)
620  // HGAMT = min(GAMFAC * HFX / CPM, GAMCRT)
621  // HGAMQ = min(GAMFAC * QFX, GAMCRQ) [if over water, HGAMQ = 0]
622  // VPERT = HGAMT + EP1 * theta * HGAMQ
623  // THERMAL += max(VPERT, 0) [raises effective surface virtual pot. temp.]
624  //
625  // YSU K-profile below PBL (module_bl_ysu.F lines 190-220):
626  // K_mom = rho * wscale * kappa * z * (1 - z/h)^pfac
627  // K_theta = K_mom / Prt
628  // K_q = K_mom / Prq (Prq ~ Prt for moisture)
629  //
630  //
631  // PASS 2 — CORRECTOR: Apply surface-type-dependent Ribcr with VPERT enhancement
632  // following HND06 (Hong, Noh & Dudhia 2006), with countergradient corrections.
633  //
634  // This pass raises the effective surface virtual potential temperature
635  // to account for convective contribution to buoyancy, resulting in
636  // higher diagnosed PBL height in unstable conditions.
637  //
638  // WRF reference (module_bl_ysu.F lines 150-180):
639  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F
640  //
641  // WRF constants (module_bl_ysu.F lines 50-75):
642  // RLAM = 150. (mixing length scale in free atm., m)
643  // PRMIN = 0.5 (minimum Prandtl number)
644  // PRMAX = 4.0 (maximum Prandtl number)
645  // BRCR = 0.25 (over land, bulk Richardson number critical value)
646  // CFAC = 7.8 (= const_b, surface layer factor in countergradient term)
647  // PFAC = 2.0 (power law exponent for PBL height factor)
648  // SFCFRAC= 0.1 (surface layer depth fraction)
649  // GAMCRT = 3.0 (maximum heat countergradient, K)
650  // GAMCRQ = 2.e-3 (maximum moisture countergradient, kg/kg)
651  //
652  // WRF formulas (module_bl_ysu.F lines 200-250):
653  // GAMFAC = CFAC / (rho * wstar)
654  // HGAMT = min(GAMFAC * HFX / CPM, GAMCRT)
655  // HGAMQ = min(GAMFAC * QFX, GAMCRQ) [if over water, HGAMQ = 0]
656  // VPERT = HGAMT + EP1 * theta * HGAMQ
657  // THERMAL += max(VPERT, 0) [raises effective surface virtual pot. temp.]
658  //
659  // WRF diffusion coefficients below PBL (module_bl_ysu.F lines 300-350):
660  // K_mom = rho * wstar * kappa * z * (1 - z/h)^2
661  // K_theta = K_mom / Prt
662  // K_q = K_mom / Prq (Prq similar to Prt for moisture)
663  //
664  const Real const_b = turbChoice.pbl_mrf_const_b;
665  const Real sf = turbChoice.pbl_mrf_sf;
666  //constexpr Real prmin = Real(0.5);
667  //constexpr Real prmax = Real(4.0);
668  constexpr Real GAMCRT = Real(3.0); // WRF GAMCRT: max heat countergradient (K)
669  constexpr Real GAMCRQ = Real(2.e-3); // WRF GAMCRQ: max moisture countergradient (kg/kg)
670  const bool enable_ysu_countergradient = turbChoice.enable_ysu_countergradient;
671  const bool enable_ysu_unbounded_vpert = turbChoice.enable_mrf_unbounded_vpert;
672  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
673  {
674  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
675  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
676  // Determine surface-type-dependent critical Richardson number (same as Pass 1)
677  // Over land: Ribcr = 0.25; over water: Ribcr depends on Rossby number
678  Real Ribcr;
679  {
680  bool over_land = (!lmask_arr) || (lmask_arr(i, j, 0) == 1);
681  if (over_land) {
682  Ribcr = turbChoice.pbl_ysu_land_Ribcr;
683  } else {
684  const Real z0 = z0_eff_arr(i, j, 0);
685  const Real ws_layer = ws10_eff_arr(i, j, 0);
686  const Real Rossby = ws_layer / (turbChoice.pbl_ysu_coriolis_freq * amrex::max(z0, Real(1.0e-4)));
687  Ribcr = amrex::min(Real(0.16) * std::pow(Real(1.0e-7) * Rossby, -Real(0.18)), Real(0.3));
688  }
689  }
690 
691  /*
692  const Real t_layer = t10_eff_arr(i, j, 0);
693  const Real moisture_fraction = use_moisture ? q10_eff_arr(i, j, 0) : zero;
694  const Real t_layer_v = t_layer * (one + epsv * moisture_fraction);
695  */
696 
697  // Compute bounds for pblh clamping. The floor is the top face of the column's
698  // first fluid cell (see pblh_floor): zl1 is the height of that cell's center
699  // and dz1 its thickness, on every mesh type.
700  const Real zl1 = (use_terrain_fitted_coords)
701  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
702  : zib + myhalf * dz;
703  const Real dz1 = (use_terrain_fitted_coords)
704  ? Compute_h_zeta_AtCellCenter(i, j, ksrf, dxInv, z_nd_arr) / dz_inv
705  : dz;
706  const Real z_max = (use_terrain_fitted_coords)
707  ? Compute_Zrel_AtCellCenter(i, j, khi, z_sfc_arr, z_nd_arr)
708  : (khi + myhalf) * dz;
709  const Real pblh_max = Real(0.9) * z_max;
710  const Real pblh_min = pblh_floor(zl1, dz1);
711 
712  // Scan rib_enhan_arr from the surface cell up (GAP 9: WRF bl_ysu.F90 lines 620-621
713  // seed the scan with the surface bulk Ri, so ksrf is checked first) and interpolate
714  // between the levels that bracket Ribcr. The surface cell at or above Ribcr gives
715  // pblh_min; no crossing up to khi gives the top of the scan, capped by pblh_max.
716  auto rib_at = [=] (int kk) { return rib_enhan_arr(i,j,kk); };
717  auto z_at = [=] (int kk) {
718  return (use_terrain_fitted_coords) ? Compute_Zrel_AtCellCenter(i,j,kk,z_sfc_arr,z_nd_arr)
719  : (kk + myhalf) * dz;
720  };
721  const RibCrossing pbl = find_rib_crossing(ksrf, khi, Ribcr, rib_at, z_at, pblh_min, pblh_max);
722  pblh_corr_arr(i, j, 0) = pbl.pblh;
723  pbli_arr(i, j, 0) = pbl.kpbl;
724 
725  // Initialize countergradient fluxes for now
726  hgamt_arr(i, j, 0) = zero;
727  hgamq_arr(i, j, 0) = zero;
728  wstar_arr(i, j, 0) = zero;
729 
730  });
731  // Debug output (disabled):
732  /*
733  amrex::Print() << "PBL height computed for MRF scheme at level "
734  << pblh_corr_arr(2, 2, 0)
735  << std::endl;
736  amrex::Print() << "PBL Temp:" << t_surf_arr(2, 2, 0) << " "
737  << t10av_arr(2, 2, 0) << std::endl;
738  */
739 
740  //
741  // Recompute convective velocity scale (wstar) and countergradient fluxes
742  // (HGAMT/HGAMQ) using the corrector PBL height (pblh_corr_arr).
743  //
744  // Background: The corrector PBL height is now available. The Monin-Obukhov stability
745  // functions and countergradient fluxes depend strongly on the PBL height estimate,
746  // so these quantities must be recomputed after the corrector pass to ensure
747  // consistency between the PBL height diagnosis and the K-profile mixing lengths.
748  //
749  // Note: Previous versions computed both a predictor PBL height (without countergradient
750  // corrections) and a corrector PBL height (with countergradient effects). The inconsistency
751  // between these two estimates led to unrealistic mixing intensity since the stability
752  // parameter HOL = sf*h/L differs. The predictor pass has been removed; only the
753  // corrector PBL height (pblh_corr_arr) is now computed and used throughout.
754  //
755  // WRF implements WSCALE (convective velocity) and countergradient corrections
756  // only once before both the corrector loop and K-profile computations, ensuring
757  // consistency. ERF implements three passes: this loop performs the needed computation
758  // after the corrector pass is complete.
759  //
760  // YSU (HND06): WSCALE = u* / φ_m(h/L)
761  // Countergradient: HGAMT = min(CFAC * u* * θ*, GAMCRT), where CFAC=7.8, GAMCRT=3K
762  // WRF Reference: module_bl_ysu.F lines 220-250
763  const bool enable_ysu_sat_limiter = turbChoice.enable_ysu_sat_limiter;
764  const bool enable_ysu_rad_tend_limiter = turbChoice.enable_ysu_rad_tend_limiter;
765  const amrex::Real ysu_rad_tend_limiter_magnitude = turbChoice.ysu_rad_tend_limiter_magnitude;
766 
767  // ========================================================================
768  // Cloud-top detection for top-down mixing (H10 Section 3b)
769  // ========================================================================
770  const bool enable_ysu_topdown = turbChoice.enable_ysu_topdown;
771  const amrex::Real ysu_qcloud_threshold = turbChoice.ysu_qcloud_threshold;
772 
773  if (enable_ysu_topdown && use_moisture) {
774  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
775  {
776  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
777  cloud_top_arr(i, j, 0) = -1; // Initialize: no cloud found
778 
779  // Search from PBL top downward for cloud-top cell
780  int kpbl = pbli_arr(i, j, 0);
781  for (int kk = kpbl - 1; kk >= ksrf; --kk) {
782  amrex::Real qc_kk = zero, qi_kk = zero;
783  if (moisture_indices.qc >= 0)
784  qc_kk = cell_data(i, j, kk, moisture_indices.qc) / cell_data(i, j, kk, Rho_comp);
785  if (moisture_indices.qi >= 0)
786  qi_kk = cell_data(i, j, kk, moisture_indices.qi) / cell_data(i, j, kk, Rho_comp);
787 
788  if (qc_kk + qi_kk > ysu_qcloud_threshold) {
789  cloud_top_arr(i, j, 0) = kk;
790  break;
791  }
792  }
793  });
794  } else {
795  // Disable cloud-top detection
796  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
797  {
798  cloud_top_arr(i, j, 0) = -1;
799  });
800  }
801 
802  ParallelFor(xybx_work, [=, zero_d=zero, one_d=one, CONST_GRAV_d=CONST_GRAV] AMREX_GPU_DEVICE(int i, int j, int) noexcept
803  {
804  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
805  const Real t_layer = t10_eff_arr(i, j, 0);
806  Real obuk_val = ol_eff_arr(i, j, 0);
807  if (std::abs(obuk_val) < amrex::Real(1.0e-10)) {
808  obuk_val = (obuk_val >= zero) ? amrex::Real(1.0e-10) : amrex::Real(-1.0e-10);
809  }
810 
811  // Compute Monin-Obukhov stability parameter using corrector PBL height
812  // HOL = sf * h / L, where L is Monin-Obukhov length scale
813  // WRF Reference: module_bl_ysu.F lines 200-210
814  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F#L200-L210
815  const Real HOL = sf * pblh_corr_arr(i, j, 0) / obuk_val;
816  const Real HOL_bounded = amrex::max(amrex::min(HOL, Real(100.0)), Real(-100.0));
817  const Real one_quarter = Real(1.0) / Real(4.0);
818  const Real phiM = (obuk_val > 0)
819  ? (1 + 5 * HOL_bounded)
820  : std::pow(
821  amrex::max(1 - 16 * HOL_bounded, Real(0.01)),
822  -one_quarter);
823  const Real phiM_safe = amrex::max(phiM, Real(0.01));
824 
825  // Convective velocity scale (wscale = u*/phi_m), now computed with pblh_corr_arr
826  // wscale is the characteristic turbulent velocity in the boundary layer.
827  // Bounds (u*/5 to 16*u*) prevent unrealistic values in very weak or strong convection.
828  // WRF Reference: module_bl_ysu.F L210-215
829  Real wscale = us_eff_arr(i, j, 0) / phiM_safe;
830  wscale = amrex::max(wscale, us_eff_arr(i, j, 0) / Real(5.0)); // Mechanical turbulence floor
831  wscale = amrex::min(wscale, Real(16.0) * us_eff_arr(i, j, 0)); // Free convection ceiling
832 
833  // Compute top-down convective velocity scale wstar3_down (H10 Eq. 12)
834  // This represents turbulence driven by radiative cooling at cloud top
835  amrex::Real wstar3_down = zero;
836  if (enable_ysu_topdown && cloud_top_arr(i, j, 0) >= ksrf) {
837  int k_cloud_top = cloud_top_arr(i, j, 0);
838 
839  // Longwave cooling flux at cloud top (W/m^2 equivalent in K*m/s)
840  // When RRTMGP is active, read from qheating_rates if available.
841  // Otherwise use zero (feature disabled when radiation is off).
842  // Compute LRAD by integrating the LW heating rate (component index 1)
843  // over the PBL column from surface (ksrf) to cloud top (k_cloud_top)
844  amrex::Real LRAD = zero;
845  if (has_qheating_rates) {
846  // Integrate LW heating rate from surface to cloud top
847  // qheating_rates contains heating rates (K/s); negative values represent cooling
848  for (int kk = ksrf; kk <= k_cloud_top; ++kk) {
849  amrex::Real ldz = (use_terrain_fitted_coords)
850  ? (z_nd_arr(i, j, kk+1) - z_nd_arr(i, j, kk))
851  : dz;
852  // Accumulate cooling (negative heating) integrated over height
853  // LW component is at index 1
854  LRAD += -qheat_arr(i, j, kk, 1) * ldz;
855  }
856  }
857 
858  // YSU radiative tendency limiter/smoothing
859  // Apply optional finite guards, bounds checking, and smoothing
860  amrex::Real LRAD_raw = LRAD; // Store raw value for diagnostics
861  amrex::Real LRAD_limited = LRAD;
862 
863  if (enable_ysu_rad_tend_limiter && has_qheating_rates) {
864  // Guard against NaN/Inf in the raw heating rate
865  if (!amrex::Math::isfinite(LRAD_raw)) {
866  LRAD_limited = zero; // Safe fallback: no radiative forcing
867  } else {
868  // Apply the magnitude limiter/bounds
869  // Clamp LRAD to [-limiter_magnitude, +limiter_magnitude]
870  const amrex::Real lim_mag = ysu_rad_tend_limiter_magnitude;
871  LRAD_limited = amrex::min(LRAD_raw, lim_mag);
872  LRAD_limited = amrex::max(LRAD_limited, -lim_mag);
873  }
874  // Use limited value for subsequent wstar computation
875  LRAD = LRAD_limited;
876  }
877 
878  // Top-down convective velocity (H10 Eq. 12):
879  // wstar_down^3 = g/theta * LRAD/(rho*cp) * pblh
880  const amrex::Real t_local = cell_data(i, j, k_cloud_top, RhoTheta_comp)
881  / cell_data(i, j, k_cloud_top, Rho_comp);
882  const amrex::Real rho_ct = cell_data(i, j, k_cloud_top, Rho_comp);
883  wstar3_down = amrex::max(CONST_GRAV_d / t_local * LRAD
884  / (rho_ct * amrex::Real(1004.0))
885  * pblh_corr_arr(i, j, 0), zero_d);
886  }
887  wstar3_down_arr(i, j, 0) = wstar3_down;
888 
889  // Recompute wstar3 and wscale with corrected pblh_corr_arr
890  const Real bfx0_corr = amrex::max(sflux_arr(i, j, 0), zero_d);
891  const Real t_dry = t10_eff_arr(i, j, 0);
892  const Real wstar3_corr = (CONST_GRAV / t_dry) * bfx0_corr * pblh_corr_arr(i, j, 0);
893  wstar3_arr(i, j, 0) = wstar3_corr;
894 
895  // Recompute wscale with corrected pblh:
896  const Real ust3 = us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0);
897  Real wscale_corr = std::cbrt(ust3 + amrex::Real(8.0) * KAPPA * wstar3_corr * amrex::Real(0.5));
898  wscale_corr = amrex::min(wscale_corr, us_eff_arr(i, j, 0) * amrex::Real(16.0));
899  wscale_corr = amrex::max(wscale_corr, us_eff_arr(i, j, 0) / amrex::Real(5.0));
900  wstar_arr(i, j, 0) = wscale_corr;
901 
902  // Compute HGAMT with corrected wscale and WRF convention
903  // WRF bl_ysu.F90 line 687: gamfac = bfac/rhox/wscale
904  // WRF bl_ysu.F90 line 688: hgamt(i) = min(gamfac*hfx(i)/cp, gamcrt)
905  // Use sflux-based sfcflg for consistency with the precompute kernel (Fix 3)
906  bool SFCFLG = (sfcflg_arr(i, j, 0) > zero); // TRUE when unstable/neutral (sflux >= -round-off)
907  const Real rho_sfc = cell_data(i, j, ksrf, Rho_comp);
908  const Real hfx_col = -rho_sfc * amrex::Real(1004.0) * us_eff_arr(i, j, 0) * ts_eff_arr(i, j, 0);
909  const Real gamfac = const_b / (rho_sfc * wscale_corr);
910  const Real HGAMT = (SFCFLG && enable_ysu_countergradient)
911  ? amrex::min(gamfac * hfx_col / amrex::Real(1004.0), GAMCRT)
912  : zero;
913 
914  // Compute HGAMQ with corrected wscale and WRF convention
915  // WRF bl_ysu.F90 line 689: hgamq(i) = min(gamfac*qfx(i), gamcrq)
916  const Real qfx_col = -rho_sfc * us_eff_arr(i, j, 0) * qs_eff_arr(i, j, 0);
917  const Real HGAMQ_raw = (SFCFLG && use_moisture && enable_ysu_countergradient)
918  ? gamfac * qfx_col
919  : zero;
920  Real HGAMQ = amrex::min(amrex::max(HGAMQ_raw, zero_d), GAMCRQ);
921 
922  // Land/water surface discrimination
923  if (lmask_arr && SFCFLG && use_moisture && enable_ysu_countergradient) {
924  bool is_land = (lmask_arr(i,j,0) == 1);
925  if (!is_land) HGAMQ = zero;
926  }
927 
928  // Saturation-Aware HGAMQ limiter
929  if (enable_ysu_sat_limiter && moisture_indices.qv >= 0 && SFCFLG && use_moisture && enable_ysu_countergradient) {
930  Real qv_klo = cell_data(i, j, ksrf, moisture_indices.qv) / cell_data(i, j, ksrf, Rho_comp);
931  Real T_klo = getTgivenRandRTh(cell_data(i, j, ksrf, Rho_comp),
932  cell_data(i, j, ksrf, RhoTheta_comp),
933  qv_klo);
934  Real p_klo = getPgivenRTh(cell_data(i, j, ksrf, RhoTheta_comp), qv_klo) * Real(0.01);
935  Real qsat_klo = zero;
936  erf_qsatw(T_klo, p_klo, qsat_klo);
937  Real rh_klo = (qsat_klo > Real(1.0e-10)) ? (qv_klo / qsat_klo) : zero;
938  if (rh_klo > Real(0.95)) {
939  Real rh_scaling = amrex::max(zero_d, (one - rh_klo) / Real(0.05));
940  HGAMQ *= rh_scaling;
941  }
942  }
943  // Store HGAMT/h and HGAMQ/h for implicit solver (normalized by corrected PBL height)
944  // Also compute VPERT = max(HGAMT + 0.61*θ*HGAMQ, 0) for Pass 3 use
945  // WRF Reference: module_bl_ysu.F lines 230-240 (THERMAL update with VPERT)
946  if (pbli_arr(i, j, 0) <= ksrf + 1) {
947  hgamt_arr(i, j, 0) = zero;
948  hgamq_arr(i, j, 0) = zero;
949  hgamu_arr(i, j, 0) = zero;
950  hgamv_arr(i, j, 0) = zero;
951  vpert_arr(i, j, 0) = zero;
952  } else {
953  const Real pblh = pblh_corr_arr(i, j, 0);
954  hgamt_arr(i, j, 0) = (enable_ysu_countergradient) ? HGAMT / pblh : zero;
955  hgamq_arr(i, j, 0) = (enable_ysu_countergradient && use_moisture) ? HGAMQ / pblh : zero;
956 
957  // Compute YSU momentum countergradient terms (hgamu, hgamv)
958  // WRF bl_ysu.F90 lines 694-696:
959  // brint = -15.9*ust^2/wspd * wstar3/wscale^4
960  // hgamu = brint * ux(1), hgamv = brint * vx(1)
961  //
962  // NOTE: WRF stores the raw (m/s) values here and divides by hpbl at
963  // the point of use (module_bl_ysu.F: -hgamu(i)/hpbl(i)). ERF
964  // instead normalizes at the source, exactly as HGAMT/HGAMQ are
965  // normalized above, so that all four HGAM* components share one
966  // contract: a countergradient *gradient* (units of phi per m)
967  // that the implicit solvers multiply by rho*alpha to form a flux.
968  // See EddyDiff::HGAMU_v in ERF_IndexDefines.H.
969  hgamu_arr(i, j, 0) = zero;
970  hgamv_arr(i, j, 0) = zero;
971  if (SFCFLG && enable_ysu_countergradient) {
972  const Real wspd_sfc = ws10_eff_arr(i, j, 0);
973  const Real ustar = us_eff_arr(i, j, 0);
974  wscale = wstar_arr(i, j, 0); // column-average wscale
975  const Real wstar3 = wstar3_arr(i, j, 0); // convective velocity scale cubed
976 
977  const Real wscale4 = amrex::max(wscale * wscale * wscale * wscale,
978  amrex::Real(1.0e-10));
979  const Real brint = amrex::Real(-15.9) * ustar * ustar
980  / amrex::max(wspd_sfc, amrex::Real(1.0e-4))
981  * wstar3 / wscale4;
982 
983  // ux(i,1) and vx(i,1) in WRF = cell-center velocity at lowest level (ksrf in ERF)
984  const Real u_klo = myhalf * (uvel(i, j, ksrf) + uvel(i+1, j, ksrf));
985  const Real v_klo = myhalf * (vvel(i, j, ksrf) + vvel(i, j+1, ksrf));
986  hgamu_arr(i, j, 0) = brint * u_klo / pblh; // 1/s
987  hgamv_arr(i, j, 0) = brint * v_klo / pblh; // 1/s
988  }
989 
990  // VPERT for Pass 3 diagnostic: unnormalized (not divided by pblh)
991  // This represents the virtual temperature perturbation at surface
992  // When enable_ysu_unbounded_vpert=true, use unbounded VPERT (ERF enhanced)
993  // When enable_ysu_unbounded_vpert=false, cap at GAMCRT (WRF-compatible)
994  // WRF Reference: module_bl_ysu.F lines 230-240
995  // GAP 8: Include WRF height limiter (WRF bl_ysu.F90 line 689-690)
996  if (enable_ysu_countergradient) {
997  // Compute height limiter: min(zl1/(sfcfrac*pblh), 1.0)
998  // This reduces VPERT contribution when the first cell is coarse relative to thin PBLs
999  const Real zl1_col = (use_terrain_fitted_coords)
1000  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
1001  : (ksrf + myhalf) * dz;
1002  constexpr Real sfcfrac_h = amrex::Real(0.1); // WRF SFCFRAC
1003  const Real height_lim = amrex::min(zl1_col / (sfcfrac_h * pblh), one_d);
1004 
1005  const Real VPERT_raw = HGAMT + amrex::Real(0.61) * t_layer * HGAMQ;
1006  const Real VPERT_capped = enable_ysu_unbounded_vpert
1007  ? VPERT_raw
1008  : amrex::min(VPERT_raw, GAMCRT);
1009  vpert_arr(i, j, 0) = amrex::max(VPERT_capped, zero_d) * height_lim;
1010  } else {
1011  vpert_arr(i, j, 0) = zero;
1012  }
1013  }
1014 
1015  });
1016 
1017  // ========================================================================
1018  // RECOMPUTE rib_enhan_arr WITH UPDATED VPERT
1019  // ========================================================================
1020  // BUG FIX: The enhanced Rib array was computed with vpert_arr=0 during the
1021  // initial precompute phase (line 226). Now that VPERT has been computed and
1022  // stored in vpert_arr (lines 709-761), we must RECOMPUTE rib_enhan_arr to
1023  // incorporate the now-nonzero VPERT. This ensures Pass 3 (zero-Ri diagnostic)
1024  // uses the correctly enhanced Richardson numbers, matching WRF methodology
1025  // where thermal excess is computed between predictor and corrector passes.
1026  //
1027  // Reference: Hong et al. (2006) HND06, WRF module_bl_ysu.F lines 150-170
1028  //
1029  BL_PROFILE_VAR("YSU_Rib_Recompute", prof_rib_recomp);
1030  ParallelFor(gbx_work, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
1031  {
1032  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1033  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
1034  const amrex::Real t_layer = t10_eff_arr(i, j, 0);
1035  const amrex::Real q_frac = use_moisture ? q10_eff_arr(i, j, 0) : zero;
1036  const amrex::Real t_layer_v = t_layer * (one + epsv * q_frac);
1037  // Now vpert_arr contains the computed thermal perturbation from the corrector pass
1038  const amrex::Real t_enh = t_layer_v + vpert_arr(i,j,0);
1039  // Rib uses the height above the ground (WRF za). zib is the column's immersed
1040  // surface with erf.pbl_ib_aware and zero otherwise; that option is off on
1041  // terrain-fitted meshes, where Compute_Zrel_AtCellCenter already measures from the ground
1042  const amrex::Real z_sfc = zib;
1043  const amrex::Real zval = (use_terrain_fitted_coords)
1044  ? Compute_Zrel_AtCellCenter(i,j,k,z_sfc_arr,z_nd_arr)
1045  : (k + myhalf) * dz;
1046  const amrex::Real zrel = amrex::max(zval - z_sfc, amrex::Real(1.0e-4));
1047  const amrex::Real theta_v = GetThetav(i,j,k,cell_data,moisture_indices);
1048  const amrex::Real theta_v_klo = GetThetav(i,j,ksrf,cell_data,moisture_indices);
1049  const amrex::Real ws2_raw = fourth * ((uvel(i,j,k)+uvel(i+1,j,k))*(uvel(i,j,k)+uvel(i+1,j,k))
1050  + (vvel(i,j,k)+vvel(i,j+1,k))*(vvel(i,j,k)+vvel(i,j+1,k)));
1051  // Vogelezang & Holtslag (1996): Add shear correction term to denominator instead of ad-hoc floor
1052  const amrex::Real ws2 = (turbChoice.enable_vh96_shear_correction)
1053  ? (ws2_raw + turbChoice.vh96_shear_const_b * us_eff_arr(i,j,0) * us_eff_arr(i,j,0))
1054  : amrex::max(ws2_raw, amrex::Real(1.0));
1055  // Recompute ONLY rib_enhan_arr with updated vpert_arr; leave rib_base_arr unchanged
1056  rib_enhan_arr(i,j,k) = CONST_GRAV * zrel * (theta_v - t_enh) / (ws2 * theta_v_klo);
1057  });
1058  BL_PROFILE_VAR_STOP(prof_rib_recomp);
1059 
1060  // ========================================================================
1061  // RE-RUN CORRECTOR PASS 2 WITH UPDATED rib_enhan_arr
1062  // ========================================================================
1063  // Now that rib_enhan_arr has been recomputed with the nonzero VPERT values,
1064  // we need to re-scan for the PBL height using the corrector Ribcr criterion.
1065  // This corrects the earlier Pass 2 which used zero-VPERT Rib values.
1066  //
1067  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
1068  {
1069  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1070  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
1071  // Determine surface-type-dependent critical Richardson number (same as before)
1072  Real Ribcr;
1073  {
1074  bool over_land = (!lmask_arr) || (lmask_arr(i, j, 0) == 1);
1075  if (over_land) {
1076  Ribcr = turbChoice.pbl_ysu_land_Ribcr;
1077  } else {
1078  const Real z0 = z0_eff_arr(i, j, 0);
1079  const Real ws_layer = ws10_eff_arr(i, j, 0);
1080  const Real Rossby = ws_layer / (turbChoice.pbl_ysu_coriolis_freq * amrex::max(z0, Real(1.0e-4)));
1081  Ribcr = amrex::min(Real(0.16) * std::pow(Real(1.0e-7) * Rossby, -Real(0.18)), Real(0.3));
1082  }
1083  }
1084 
1085  // Compute bounds, as in the first corrector pass: the floor is the top face of
1086  // the column's first fluid cell (see pblh_floor) on every mesh type.
1087  const Real zl1 = (use_terrain_fitted_coords)
1088  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
1089  : zib + myhalf * dz;
1090  const Real dz1 = (use_terrain_fitted_coords)
1091  ? Compute_h_zeta_AtCellCenter(i, j, ksrf, dxInv, z_nd_arr) / dz_inv
1092  : dz;
1093  const Real z_max = (use_terrain_fitted_coords)
1094  ? Compute_Zrel_AtCellCenter(i, j, khi, z_sfc_arr, z_nd_arr)
1095  : (khi + myhalf) * dz;
1096  const Real pblh_max = Real(0.9) * z_max;
1097  const Real pblh_min = pblh_floor(zl1, dz1);
1098  pblh_floor_arr(i, j, 0) = pblh_min;
1099 
1100  // Rescan the updated rib_enhan_arr from the surface cell up, as in the first
1101  // corrector pass (see ERF_PBLRibCrossing.H). A column with no crossing is marked,
1102  // so that no entrainment flux is put at its top cell below.
1103  auto rib_at = [=] (int kk) { return rib_enhan_arr(i,j,kk); };
1104  auto z_at = [=] (int kk) {
1105  return (use_terrain_fitted_coords) ? Compute_Zrel_AtCellCenter(i,j,kk,z_sfc_arr,z_nd_arr)
1106  : (kk + myhalf) * dz;
1107  };
1108  const RibCrossing pbl = find_rib_crossing(ksrf, khi, Ribcr, rib_at, z_at, pblh_min, pblh_max);
1109  pblh_corr_arr(i, j, 0) = pbl.pblh;
1110  pbli_arr(i, j, 0) = pbl.kpbl;
1111  pbl_open_arr(i, j, 0) = pbl.crossed ? 0 : 1;
1112  });
1113 
1114  // Apply PBLH spatial smoothing if enabled (Seibert et al. 2000 methodology)
1115  // Seibert et al. (2000): Review and intercomparison of operational methods
1116  // for the determination of the mixing height. Atmospheric Environment, 34, 1001-1027.
1117  // Spatial smoothing removes unphysical grid-to-grid noise from discrete Rib-crossing detection
1118  if (turbChoice.enable_pblh_smoothing) {
1119  // Smooth the tile's own columns, reading the halo the passes above filled.
1120  // The result is the same however the domain is split.
1121  ApplyPBLHSmoothing(pbl_height_corrector, xybx_tile,
1122  turbChoice.pblh_smoothing_weight,
1123  turbChoice.pblh_smoothing_passes,
1124  geom.Domain(), geom.periodicity());
1125  // The smoothed height stays at or above the column's own floor (the top
1126  // face of its first fluid cell, at least 10 m): beside lower neighbors a
1127  // column over a building (erf.pbl_ib_aware) would otherwise be handed
1128  // a height below its first cell, and the K profile a negative depth.
1129  ParallelFor(xybx_work, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept {
1130  pblh_corr_arr(i, j, 0) = amrex::max(pblh_corr_arr(i, j, 0), pblh_floor_arr(i, j, 0));
1131  });
1132  }
1133 
1134  // Copy corrected PBL height into pblh_mf for SurfaceLayer storage.
1135  // pbl_height_corrector only covers this tile (grown by one), so loop over
1136  // the tile, not the valid box: with tiling in x/y the valid box reaches
1137  // past it. Under TileNoZ the tile spans the full column, and pblh_mf has
1138  // no ghost cells, so the tiles together still fill every cell.
1139  {
1140  auto pblh_out = pblh_mf.array(mfi);
1141  const Box& tbx = mfi.tilebox();
1142  ParallelFor(tbx, [=] AMREX_GPU_DEVICE(int i, int j, int k) noexcept {
1143  pblh_out(i, j, k) = pblh_corr_arr(i, j, 0);
1144  });
1145  }
1146  // ========================================================================
1147  // Extension scan using liquid potential temperature (WRF bl_ysu.F90 lines 733-769)
1148  // ========================================================================
1149  // Scan upward from Pass 2 PBLH using theta_li to extend kpbl for
1150  // cloud-topped boundary layers. Triggered when enable_ysu_topdown and
1151  // use_moisture are both true.
1152  //
1153  if (enable_ysu_topdown && use_moisture) {
1154  ParallelFor(xybx, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
1155  {
1156  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1157  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
1158  const int kpblold = pbli_arr(i,j,0); // Starting PBLH index from Pass 2
1159  bool definebrup = false;
1160 
1161  // Surface liquid-ice potential temperature reference (WRF thermalli = thlix(1))
1162  const Real thermalli = GetThetal(i, j, ksrf, cell_data, moisture_indices);
1163 
1164  // Upward scan using liquid-theta stability criterion
1165  for (int kk = kpblold; kk < khi; ++kk) {
1166  // Velocity shear for Richardson number calculation
1167  const Real ws2_raw = fourth * ((uvel(i,j,kk)+uvel(i+1,j,kk))*(uvel(i,j,kk)+uvel(i+1,j,kk))
1168  + (vvel(i,j,kk)+vvel(i,j+1,kk))*(vvel(i,j,kk)+vvel(i,j+1,kk)));
1169  // Vogelezang & Holtslag (1996): Add shear correction term to denominator instead of ad-hoc floor
1170  const Real ws2 = (turbChoice.enable_vh96_shear_correction)
1171  ? (ws2_raw + turbChoice.vh96_shear_const_b * us_eff_arr(i,j,0) * us_eff_arr(i,j,0))
1172  : amrex::max(ws2_raw, amrex::Real(1.0));
1173 
1174  // Elevation at level kk
1175  // Height above the ground, as in the Rib kernels above
1176  const Real z_sfc = zib;
1177  const Real zval_kk = (use_terrain_fitted_coords)
1178  ? Compute_Zrel_AtCellCenter(i, j, kk, z_sfc_arr, z_nd_arr)
1179  : (kk + myhalf) * dz;
1180  const Real zrel_kk = amrex::max(zval_kk - z_sfc, amrex::Real(1.0e-4));
1181 
1182  // Liquid-ice potential temperature (WRF thlix) at current level and surface
1183  const Real thlix_kk = GetThetal(i, j, kk, cell_data, moisture_indices);
1184  const Real thlix_klo = GetThetal(i, j, ksrf, cell_data, moisture_indices);
1185 
1186  // Bulk Richardson number using liquid-theta potential temperature
1187  const Real bruptmp = CONST_GRAV * zrel_kk * (thlix_kk - thermalli) / (ws2 * thlix_klo);
1188 
1189  // Stability check: threshold is zero for extension scan
1190  const bool stable = (bruptmp >= zero);
1191 
1192  if (definebrup) {
1193  pbli_arr(i,j,0) = kk;
1194  definebrup = false;
1195  }
1196 
1197  if (!stable) {
1198  // Continue scanning while Richardson number indicates mixing
1199  definebrup = true;
1200  }
1201  }
1202 
1203  // Bound result to domain top
1204  pbli_arr(i,j,0) = amrex::min(pbli_arr(i,j,0), izmax);
1205  });
1206  }
1207 
1208  //
1209  // PASS 3 — ZERO-RI DIAGNOSTIC: Compute PBL index with Ribcr=0.0 criterion
1210  //
1211  // Background: WRF employs three distinct PBL height estimates (module_bl_ysu.F lines 150-200):
1212  // Pass 1: Ribcr = surface-type-dependent (predictor, base surface temperature)
1213  // Pass 2: Ribcr = surface-type-dependent (corrector, enhanced surface temperature with VPERT)
1214  // Pass 3: Ribcr = 0.0 diagnostic (uses enhanced surface temperature, neutral criterion)
1215  //
1216  // The third pass with Ribcr=0 produces the PBL height where Richardson number
1217  // first becomes neutral (Rib >= 0). This is the "zero-Richardson" diagnostic
1218  // commonly used in observation-based PBL depth estimates (module_bl_ysu.F lines 190-200).
1219  //
1220  // Use of three passes: The corrector PBL height (Pass 2) is used for
1221  // computing the mixing intensity K = ρ*wstar*κ*z*(1-z/h)², while
1222  // the diagnostic height (Pass 3, Ribcr=0) determines the vertical extent
1223  // of the nonlocal mixing region. This separation provides:
1224  // - Realistic mixed-layer extent in convective conditions
1225  // - Mixing formula consistent with corrector diagnostics
1226  // - Consistency with WRF methodology
1227  //
1228  // Reference: Hong et al. (2006), module_bl_ysu.F
1229  //
1230  constexpr Real Ribcr_zero = zero; // Zero critical Richardson number for diagnostic pass
1231  ParallelFor(xybx, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
1232  {
1233  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1234  // GAP 9: Seed from surface bulk Richardson number (WRF bl_ysu.F90 lines 620-621)
1235  // WRF seeds the loop with br (surface bulk Ri) so ksrf is checked first.
1236  int kpbl_zero = ksrf;
1237  Real Rib = rib_enhan_arr(i,j,ksrf); // Seed from surface level
1238  bool above_critical = (Rib >= Ribcr_zero); // Check if already above critical (Ribcr=0)
1239 
1240  // Scan rib_enhan_arr(i,j,ksrf..khi) for Ribcr=0 crossing (no interpolation needed)
1241  for (int kk = ksrf+1; !above_critical && kk <= khi; ++kk) {
1242  if (rib_enhan_arr(i,j,kk) >= Ribcr_zero) { kpbl_zero = kk; above_critical = true; break; }
1243  kpbl_zero = kk;
1244  }
1245  pbli_zero_arr(i, j, 0) = kpbl_zero;
1246  });
1247  BL_PROFILE_VAR_STOP(prof_pblh);
1248 
1249  // Compute entrainment diffusivity at PBL top cell (WRF bl_ysu.F90 lines 831-925)
1250  // Uses WRF's buoyancy-flux-based entrainment velocity (we), which accounts for
1251  // the actual inversion strength (dthvx) at the PBL top.
1252  {
1253  const bool enable_ysu_entrainment = turbChoice.enable_ysu_entrainment;
1254  const bool enable_ysu_cloud_pblh = turbChoice.enable_ysu_cloud_pblh;
1255 
1256  ParallelFor(xybx, [=, zero_d=zero] AMREX_GPU_DEVICE(int i, int j, int) noexcept
1257  {
1258  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1259  entr_arr(i,j,0) = zero;
1260  if (!enable_ysu_entrainment) return;
1261  // No Ribcr crossing up to khi: kpbl = khi is the top of the domain, not an
1262  // inversion, so no entrainment flux goes there (in WRF bl_ysu.F90 the
1263  // entrainment diffusivity applies at k >= kpbl, above its last face when kpbl = kte)
1264  if (pbl_open_arr(i,j,0) != 0) return;
1265 
1266  const int kpbl = pbli_arr(i,j,0);
1267  const Real rho_kpbl = cell_data(i, j, kpbl, Rho_comp);
1268  const Real pblh = pblh_corr_arr(i,j,0);
1269  const Real wscale = wstar_arr(i,j,0);
1270  const Real ustar = us_eff_arr(i, j, 0);
1271  const Real ustar3 = ustar * ustar * ustar;
1272 
1273  // WRF bl_ysu.F90 lines 831-839: buoyancy-flux-based entrainment velocity
1274  // wm3 = wstar3 + 5*ust3 (combined convective + mechanical velocity scale)
1275  const Real wstar3_col = wstar3_arr(i,j,0);
1276  const Real wm3 = wstar3_col + amrex::Real(5.0) * ustar3;
1277  const Real wm2 = std::pow(wm3, amrex::Real(2.0) / amrex::Real(3.0));
1278 
1279  // bfxpbl = -0.15 * thvx(ksrf)/g * wm3 / hpbl
1280  // thvx keeps the loading of every condensate, as the buoyancy does (WRF's thvx has none)
1281  const Real thvx_klo = GetThetav(i, j, ksrf, cell_data, moisture_indices);
1282  const Real bfxpbl = amrex::Real(-0.15) * thvx_klo / CONST_GRAV * wm3 / pblh;
1283 
1284  // dthvx = max(thvx(kpbl+1) - thvx(kpbl), tmin) [inversion strength at PBL top]
1285  // Guard against kpbl+1 exceeding domain top
1286  const int kpbl_p1 = amrex::min(kpbl + 1, izmax);
1287  const Real thvx_kpbl = GetThetav(i, j, kpbl, cell_data, moisture_indices);
1288  const Real thvx_kpbl_p1 = GetThetav(i, j, kpbl_p1, cell_data, moisture_indices);
1289  const Real dthvx = amrex::max(thvx_kpbl_p1 - thvx_kpbl, amrex::Real(1.0e-2));
1290 
1291  // we = max(bfxpbl / dthvx, -sqrt(wm2))
1292  // we is negative for true (downward) entrainment
1293  const Real we = amrex::max(bfxpbl / dthvx, -std::sqrt(wm2));
1294 
1295  // dz at kpbl level (terrain-adjusted)
1296  const Real met_h = (use_terrain_fitted_coords)
1297  ? Compute_h_zeta_AtCellCenter(i, j, kpbl, dxInv, z_nd_arr) : one;
1298  const Real dz_kpbl = met_h / dz_inv;
1299 
1300  // Apply entrainment only when we < 0 (downward entrainment occurring)
1301  const Real K_cap = Real(5.0) * rho_kpbl * wscale * KAPPA * pblh * Real(0.01);
1302 
1303  // Cloudy entrainment correction (WRF bl_ysu.F90 lines 840-875)
1304  // Applied when qc+qi exceeds threshold at cell kpbl-1 (layer below PBL top)
1305  // Uses cloud liquid water content and buoyancy jump for entrainment efficiency.
1306  // Radiation coupling is not required; wstar3_2 and hgamt2 remain zero.
1307  Real we_final = we;
1308  Real K_entr_final = (we < zero) ? rho_kpbl * (-we) * dz_kpbl : zero;
1309 
1310  if (enable_ysu_topdown && use_moisture) {
1311  const int k_below = amrex::max(kpbl - 1, ksrf);
1312  const Real rho_k = cell_data(i, j, k_below, Rho_comp);
1313  Real qc_below = (moisture_indices.qc >= 0)
1314  ? cell_data(i, j, k_below, moisture_indices.qc) / rho_k : zero;
1315  Real qi_below = (moisture_indices.qi >= 0)
1316  ? cell_data(i, j, k_below, moisture_indices.qi) / rho_k : zero;
1317 
1318  constexpr Real cloud_thresh_entr = amrex::Real(0.01e-3); // 0.01 g/kg
1319 
1320  if ((qc_below + qi_below) > cloud_thresh_entr && kpbl >= ksrf + 2) {
1321  // Cloud correction path: liquid water at cell k_below triggers adjustment
1322 
1323  // Entrainment efficiency computed from liquid water content and
1324  // buoyancy jump between layers. Limited to 0.4 by WRF methodology.
1325  // Uses theta-li jump from k_below to kpbl+1 for inversion strength.
1326 
1327  // Buoyancy jump across two layers, thlix + theta * 0.61 * (qv + qc)
1328  // as in WRF bl_ysu.F90 (dthvx in the cloudy entrainment branch)
1329  const int k_p2 = amrex::min(kpbl + 1, izmax);
1330  auto thlix_v = [=] (int kk) {
1331  const Real rho_kk = cell_data(i, j, kk, Rho_comp);
1332  const Real theta_kk = cell_data(i, j, kk, RhoTheta_comp) / rho_kk;
1333  const Real qv_kk = (moisture_indices.qv >= 0)
1334  ? cell_data(i, j, kk, moisture_indices.qv) / rho_kk : zero;
1335  const Real qc_kk = (moisture_indices.qc >= 0)
1336  ? cell_data(i, j, kk, moisture_indices.qc) / rho_kk : zero;
1337  return GetThetal(i, j, kk, cell_data, moisture_indices)
1338  + theta_kk * epsv * (qv_kk + qc_kk);
1339  };
1340  const Real thlix_kbelow = thlix_v(k_below);
1341  const Real thlix_kp2 = thlix_v(k_p2);
1342 
1343  const Real dthvx_li = amrex::max(thlix_kp2 - thlix_kbelow, amrex::Real(0.1));
1344 
1345  // Entrainment efficiency from cloud liquid water
1346  // ent_eff = min(0.2 * 8 * (xlv/cp) * qc_below / dthvx_li, 0.4)
1347  constexpr Real xlv_over_cp = amrex::Real(2.5e6) / amrex::Real(1004.0);
1348  const Real ent_eff = amrex::min(amrex::Real(0.2) * amrex::Real(8.0)
1349  * xlv_over_cp * qc_below / dthvx_li,
1350  amrex::Real(0.4));
1351 
1352  // Entrainment velocity using cloudy inversion strength
1353  // Replaces clear-sky dthvx with dthvx_li in we calculation
1354  const Real we_cloud = amrex::max(bfxpbl / dthvx_li, -std::sqrt(wm2));
1355 
1356  // Cloud-top entrainment velocity contribution
1357  // bfxpbl_cloud = -ent_eff * max(sflux, 0) (surface buoyancy flux only, no radsum)
1358  const Real bfx0_cloud = amrex::max(sflux_arr(i, j, 0), zero_d);
1359  const Real bfxpbl_cloud = -ent_eff * bfx0_cloud;
1360  const Real we_cloud_top = amrex::max(bfxpbl_cloud / dthvx_li,
1361  -std::sqrt(std::pow(wm3, amrex::Real(2.0)/amrex::Real(3.0))));
1362 
1363  // Summed entrainment velocity
1364  we_final = we_cloud + we_cloud_top;
1365 
1366  // Recompute entrainment coefficient with adjusted entrainment velocity
1367  K_entr_final = (we_final < zero) ? rho_kpbl * (-we_final) * dz_kpbl : zero;
1368 
1369  // Note: WRF zeroes xkzm at k_below when cloud is detected.
1370  // In ERF, entrainment is applied only at kpbl level, making this implicit.
1371  }
1372  }
1373 
1374  entr_arr(i,j,0) = amrex::min(K_entr_final, K_cap);
1375  });
1376 
1377  // Cloud PBLH extension: check for cloud at PBL top cell and extend if present.
1378  // This is a kernel of its own, after the entrainment kernel: the entrainment
1379  // diffusivity above is computed from the index before the extension, and the
1380  // extension applies whether or not erf.enable_ysu_entrainment is set. Inside
1381  // the entrainment kernel it was skipped by that kernel's early returns
1382  // (erf-model/ERF#5191). A column with no Ribcr crossing already has
1383  // kpbl = khi = izmax, so the extension leaves it unchanged.
1384  if (enable_ysu_cloud_pblh && use_moisture) {
1385  ParallelFor(xybx, [=] AMREX_GPU_DEVICE(int i, int j, int) noexcept
1386  {
1387  const int kpbl_current = pbli_arr(i, j, 0);
1388 
1389  // Check for cloud condensate at PBL top cell
1390  amrex::Real qc_kpbl = zero, qi_kpbl = zero;
1391  if (moisture_indices.qc >= 0)
1392  qc_kpbl = cell_data(i, j, kpbl_current, moisture_indices.qc) / cell_data(i, j, kpbl_current, Rho_comp);
1393  if (moisture_indices.qi >= 0)
1394  qi_kpbl = cell_data(i, j, kpbl_current, moisture_indices.qi) / cell_data(i, j, kpbl_current, Rho_comp);
1395 
1396  // Extend PBL top by one cell if cloud present exceeds threshold
1397  if ((qc_kpbl + qi_kpbl) > ysu_qcloud_threshold) {
1398  pbli_arr(i, j, 0) = amrex::min(kpbl_current + 1, izmax);
1399  }
1400  });
1401  }
1402  }
1403 
1404  // Compute K_down for top-down cloud-driven mixing (H10 Eq. 11)
1405  FArrayBox K_down_fab(gbx, 1, The_Async_Arena());
1406  K_down_fab.setVal<RunOn::Device>(zero);
1407  const auto& K_down_arr = K_down_fab.array();
1408 
1409  if (enable_ysu_topdown) {
1410  ParallelFor(gbx, [=, zero_d=zero] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
1411  {
1412  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1413  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
1414  K_down_arr(i,j,k) = zero;
1415  if (k >= pbli_arr(i,j,0) || k < ksrf) return; // only inside PBL, never inside an immersed solid
1416 
1417  const amrex::Real rho = cell_data(i,j,k,Rho_comp);
1418  const amrex::Real pblh = pblh_corr_arr(i,j,0);
1419  const amrex::Real zval = (use_terrain_fitted_coords)
1420  ? Compute_Zrel_AtCellCenter(i,j,k,z_sfc_arr,z_nd_arr)
1421  : (k + myhalf) * dz;
1422  // Heights above the ground: on terrain-fitted meshes zval and pblh already are
1423  const amrex::Real z_sfc = zib;
1424  const amrex::Real zrel = zval - z_sfc;
1425  const amrex::Real pblh_rel = amrex::max(pblh - z_sfc, amrex::Real(1.0e-4));
1426 
1427  // Top-down K-profile (H10 Eq. 11): K_down = rho * wstar_down * kappa * (h-z) * (z/h)^2
1428  // Use stored top-down convective velocity scale (computed from LRAD in the kernel above)
1429  // wstar3_down_arr(i,j,0) = 0 when LRAD=0 (radiation not coupled), so K_down will be zero
1430  const amrex::Real wstar3_down_col = wstar3_down_arr(i,j,0);
1431  const amrex::Real wstar_down_eff = (wstar3_down_col > zero)
1432  ? std::cbrt(wstar3_down_col)
1433  : zero;
1434  const amrex::Real zfac_up = amrex::max(zrel / pblh_rel, zero_d);
1435  K_down_arr(i,j,k) = rho * wstar_down_eff * KAPPA
1436  * amrex::max(pblh_rel - zrel, zero_d)
1437  * zfac_up * zfac_up;
1438  });
1439  }
1440 
1441  // -- Compute diffusion coefficients --
1442 
1443  const Array4<Real>& K_turb = eddyViscosity.array(mfi);
1444 
1445  // Dirichlet flags to switch derivative stencil
1446  bool c_ext_dir_on_zlo = ((bc_ptr[BCVars::cons_bc].lo(2) == ERFBCType::ext_dir));
1447  bool c_ext_dir_on_zhi = ((bc_ptr[BCVars::cons_bc].hi(2) == ERFBCType::ext_dir));
1448  bool u_ext_dir_on_zlo = ((bc_ptr[BCVars::xvel_bc].lo(2) == ERFBCType::ext_dir));
1449  bool u_ext_dir_on_zhi = ((bc_ptr[BCVars::xvel_bc].hi(2) == ERFBCType::ext_dir));
1450  bool v_ext_dir_on_zlo = ((bc_ptr[BCVars::yvel_bc].lo(2) == ERFBCType::ext_dir));
1451  bool v_ext_dir_on_zhi = ((bc_ptr[BCVars::yvel_bc].hi(2) == ERFBCType::ext_dir));
1452 
1453 
1454  BL_PROFILE_VAR("YSU_Kprofile", prof_kprof);
1455  ParallelFor(gbx, [=, wstar3_arr_cap=wstar3_arr, zol1_arr_cap=zol1_arr, sfcflg_arr_cap=sfcflg_arr,
1456  zero_d=zero, one_d=one, two_d=two] AMREX_GPU_DEVICE(int i, int j, int k) noexcept
1457  {
1458  const int ksrf = ksurf_arr(i, j, 0); // local surface: first fluid cell of the column
1459  const Real zib = zib_arr(i, j, 0); // its height above the domain bottom
1460  // Guard: skip lateral ghost cells that may have uninitialized density.
1461  const Real rho_guard = cell_data(i, j, k, Rho_comp);
1462  if (rho_guard <= Real(0)) {
1463  K_turb(i, j, k, EddyDiff::Mom_v) = Real(0);
1464  K_turb(i, j, k, EddyDiff::Theta_v) = Real(0);
1465  K_turb(i, j, k, EddyDiff::Q_v) = Real(0);
1466  K_turb(i, j, k, EddyDiff::HGAMT_v) = Real(0);
1467  K_turb(i, j, k, EddyDiff::HGAMQ_v) = Real(0);
1468  K_turb(i, j, k, EddyDiff::HGAMU_v) = Real(0);
1469  K_turb(i, j, k, EddyDiff::HGAMV_v) = Real(0);
1470  K_turb(i, j, k, EddyDiff::Turb_lengthscale) = Real(0);
1471  return;
1472  }
1473 
1474  Real obuk_val = ol_eff_arr(i, j, 0);
1475  if (std::abs(obuk_val) < amrex::Real(1.0e-10)) {
1476  obuk_val = (obuk_val >= zero) ? amrex::Real(1.0e-10) : amrex::Real(-1.0e-10);
1477  }
1478 
1479  const Real zval = (use_terrain_fitted_coords)
1480  ? Compute_Zrel_AtCellCenter(i, j, k, z_sfc_arr, z_nd_arr)
1481  : (k + myhalf) * dz;
1482  const Real rho = cell_data(i, j, k, Rho_comp);
1483  if (k < ksrf) { // inside an immersed solid: no diffusivity
1484  K_turb(i, j, k, EddyDiff::Mom_v) = zero_d;
1485  K_turb(i, j, k, EddyDiff::Theta_v) = zero_d;
1486  K_turb(i, j, k, EddyDiff::Q_v) = zero_d;
1487  K_turb(i, j, k, EddyDiff::HGAMT_v) = zero_d;
1488  K_turb(i, j, k, EddyDiff::HGAMQ_v) = zero_d;
1489  K_turb(i, j, k, EddyDiff::Turb_lengthscale) = zero_d;
1490  return;
1491  }
1492  const Real met_h_zeta = (use_terrain_fitted_coords)
1493  ? Compute_h_zeta_AtCellCenter(i, j, k, dxInv, z_nd_arr) : one;
1494  const Real dz_terrain = met_h_zeta / dz_inv;
1495 
1496  // Cloud-aware diffusion: compute cloud fraction from qc and qi
1497  // Cloud water threshold for detection (threshold ~ 0.01 g/kg, matching WRF)
1498  //
1499  // CLOUD-AWARE ENHANCEMENTS (ERF Extension):
1500  // This is an optional feature NOT in HND06. It adjusts the
1501  // stability functions in cloudy layers to improve representation of:
1502  // 1. Reduced turbulence near cloud tops (stable layers with clouds)
1503  // 2. Enhanced mixing from latent heat release (unstable layers with clouds)
1504  // 3. Fog/stratus evolution in marine boundary layers
1505  //
1506  // Physical justification:
1507  // - Clouds modify vertical buoyancy structure through radiative effects
1508  // - Latent heat release enhances convective mixing
1509  // - Cloud-top entrainment is distinct from clear-air turbulence
1510  //
1511  // Reference concept: Similar to WRF's IMVDIF cloud-aware parameterization
1512  // (Bretherton & Park 2009, see WRF module_bl_mynn.F).
1513  //
1514  // Disable via enable_ysu_countergradient=false for strict HND06.
1515  constexpr Real qc_threshold = Real(1.0e-5); // 0.01 g/kg in mixing ratio (aligned with WRF)
1516  Real qc_mix = zero;
1517  Real qi_mix = zero;
1518  if (use_moisture) {
1519  // qc (mixing ratio) = qc (density) / rho
1520  if (moisture_indices.qc >= 0) {
1521  qc_mix = cell_data(i, j, k, moisture_indices.qc) / rho;
1522  }
1523  if (moisture_indices.qi >= 0) {
1524  qi_mix = cell_data(i, j, k, moisture_indices.qi) / rho;
1525  }
1526  }
1527  const Real total_qcloud = qc_mix + qi_mix;
1528  const bool has_cloud = (total_qcloud > qc_threshold);
1529 
1530  // Select PBL extent index based on configuration:
1531  // - Default (pbl_mrf_use_zero_ri_extent=false): use pbli_arr (Ri=0.5 corrector)
1532  // This matches WRF behavior for better comparability
1533  // - Alternative (pbl_mrf_use_zero_ri_extent=true): use pbli_zero_arr (Ri=0)
1534  // This provides a ~30-60% taller mixing region for convective ABL cases
1535  const int pbli_extent = turbChoice.pbl_mrf_use_zero_ri_extent ? pbli_zero_arr(i, j, 0) : pbli_arr(i, j, 0);
1536 
1537  if (k < pbli_extent) {
1538  // Within PBL: use nonlocal mixing with diagnostic stability functions
1539  // WRF reference (module_bl_ysu.F lines 190-220):
1540  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F#L190-L220
1541  //
1542  // PBL extent selection:
1543  // - Default (pbl_ysu_use_zero_ri_extent=false): uses pbli_arr (Ri=0.5 corrector)
1544  // Matches WRF behavior for K-profile mixing
1545  // - Alternative (pbl_ysu_use_zero_ri_extent=true): uses pbli_zero_arr (Ri=0)
1546  // Provides physically appropriate mixed-layer depth with extended mixing region
1547  // The mixing intensity is governed by pblh_corr_arr used in the formula K = ρ*wscale*κ*z*(1-z/h)^pfac.
1548  // This two-level approach ensures realistic PBL height behavior across
1549  // different stability regimes while maintaining stable mixing coefficients.
1550  //
1551  // Key physics: YSU nonlocal scheme represents updrafts/downdrafts by
1552  // countergradient fluxes, enabling faster PBL growth than local schemes.
1553  //
1554  // Implement SFCFLG stable-side gating (WRF L808, L872-884)
1555  // When stable (BR > 0, i.e., sflux < 0), skip nonlocal PBL mixing
1556  // and use free-atmosphere Richardson scheme throughout PBL.
1557  // Use sflux-based sfcflg for unified definition (Fix 3)
1558  bool SFCFLG = (sfcflg_arr_cap(i, j, 0) > zero); // TRUE when unstable/neutral (sflux >= -round-off)
1559 
1560  // Stability function phiM for momentum - BUSINGER-DYER form (WRF)
1561  // Unstable (L < 0): phiM = (1 - 16*sf*h/L)^(-1/4) [APHI16=16, exponent -1/4]
1562  // Stable (L > 0): phiM = 1 + 5*sf*h/L
1563  // Bound HOL to [-100, 100] to prevent numerical issues in extreme stability
1564  const Real HOL = sf * pblh_corr_arr(i, j, 0) / obuk_val;
1565  const Real HOL_bounded = amrex::max(amrex::min(HOL, Real(100.0)), Real(-100.0));
1566 
1567  const Real one_quarter = Real(1.0) / Real(4.0);
1568  const Real phiM = (obuk_val > 0)
1569  ? (1 + 5 * HOL_bounded)
1570  : std::pow(
1571  amrex::max(1 - 16 * HOL_bounded, Real(0.01)),
1572  -one_quarter);
1573 
1574  // Stability function phit for heat/temperature - BUSINGER-DYER form
1575  // Unstable (L < 0): phit = (1 - 16*sf*h/L)^(-1/2)
1576  // Stable (L > 0): phit = 1 + 5*sf*h/L (same as phiM for stability)
1577  // Reference: WRF L857-861
1578  const Real phit = (obuk_val > 0)
1579  ? (1 + 5 * HOL_bounded)
1580  : std::pow(
1581  amrex::max(1 - 16 * HOL_bounded, Real(0.01)),
1582  -one / two);
1583 
1584  // Cloud-aware adjustment: In cloudy regions, adjust stability damping
1585  // because clouds modify buoyancy oscillations through latent heating
1586  // and radiation. This improves representation of:
1587  // - Stratus-topped boundary layers (reduced mixing with clouds)
1588  // - Cumulus-capped boundary layers (enhanced mixing with convection)
1589  // This is a physically motivated extension not in original HND06.
1590  Real phit_cloud = phit;
1591  Real phiM_cloud = phiM;
1592  if (has_cloud && obuk_val > zero) {
1593  // Stable layers with clouds: reduce stability enhancement
1594  // Cloud presence reduces oscillations, damping is less effective
1595  // Reduction factor: up to 15-20% where cloud water exceeds threshold
1596  Real reduction_factor = one - Real(0.15) * amrex::min(total_qcloud / qc_threshold, one_d);
1597  // Reduce the phiM enhancement in stable conditions
1598  phiM_cloud = one + Real(5.0) * reduction_factor * sf * pblh_corr_arr(i, j, 0) / obuk_val;
1599  phit_cloud = one + Real(5.0) * reduction_factor * sf * pblh_corr_arr(i, j, 0) / obuk_val;
1600  } else if (has_cloud && obuk_val <= zero) {
1601  // Unstable layers with clouds: slightly enhance instability
1602  // Clouds warm the boundary layer through latent heat release
1603  // Boost factor: up to 5% where cloud water exceeds threshold
1604  Real cloud_boost = Real(1.0) + Real(0.05) * amrex::min(total_qcloud / qc_threshold, one_d);
1605  // Ensure numerically stable exponentiation: base must be in [0.01, 1]
1606  // Businger-Dyer form: phi_m = (1 - 16*HOL)^(-1/4) for unstable conditions
1607  phiM_cloud = std::pow(
1608  amrex::max(one_d - Real(16.0) * HOL_bounded / cloud_boost, Real(0.01)),
1609  -one_quarter);
1610  phit_cloud = std::pow(
1611  amrex::max(one_d - Real(16.0) * HOL_bounded / cloud_boost, Real(0.01)),
1612  -one_d / two_d);
1613  }
1614 
1615  // Use cloud-aware stability functions
1616  const Real phiM_eff = phiM_cloud;
1617  const Real phit_eff = phit_cloud;
1618 
1619  // SECTION A: Full Prandtl Number Calculation (WRF bl_ysu.F90 lines 948-971)
1620  // Three-component formula matching WRF exactly:
1621  // (a) prfac = bfac*karman*sfcfrac = 6.8*0.4*0.1 = 0.272
1622  // (b) prfac2 = free-convection correction that reduces Pr for strong convection
1623  // (c) prnumfac = height-dependent exponential blending
1624  //
1625  // Reference: https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F#L948-L971
1626 
1627  // Step 1: Compute WRF constants (WRF lines 948-950)
1628  constexpr Real bfac = amrex::Real(6.8); // WRF BFAC (not 7.8)
1629  constexpr Real sfcfrac = amrex::Real(0.1); // SFCFRAC
1630  const Real conpr = bfac * KAPPA * sfcfrac; // = 0.272 (not 0.312)
1631 
1632  // Step 2: Compute height-dependent zq_kp1 for prnumfac calculation
1633  const Real zq_kp1_prandtl = zval + myhalf * dz_terrain;
1634 
1635  // Step 3: Compute prfac (surface layer Prandtl correction)
1636  // WRF bl_ysu.F90 line 951: prfac = conpr if SFCFLG, else 0
1637  const Real prfac = SFCFLG ? conpr : zero;
1638 
1639  // Step 4: Compute prfac2 (free-convection Prandtl correction)
1640  // WRF bl_ysu.F90 lines 962-963:
1641  // prfac2 = 15.9*(wstar3+wstar3_2)/ust3 / (1 + 4*karman*(wstar3+wstar3_2)/ust3)
1642  const Real wstar3_col = wstar3_arr_cap(i, j, 0);
1643  const Real ust3 = us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0);
1644  // Top-down wstar3 term (wstar3_2 in WRF bl_ysu.F90 line 949)
1645  // Non-zero only when top-down convection is active (requires radiation coupling for LRAD)
1646  const Real wstar3_2 = wstar3_down_arr(i, j, 0);
1647 
1648  Real prfac2 = zero;
1649  if (SFCFLG && ust3 > amrex::Real(1.0e-10)) {
1650  const Real wstar_tot3 = wstar3_col + wstar3_2;
1651  prfac2 = amrex::Real(15.9) * wstar_tot3 / ust3
1652  / (one + amrex::Real(4.0) * KAPPA * wstar_tot3 / ust3);
1653  }
1654 
1655  // Step 5: Compute prnumfac (height-dependent exponential blend)
1656  // WRF bl_ysu.F90 lines 964-965:
1657  // prnumfac = -3*(max(zq(k+1) - sfcfrac*hpbl, 0))^2 / hpbl^2
1658  const Real pblh = pblh_corr_arr(i, j, 0);
1659  const Real sfclayer = sfcfrac * pblh;
1660  const Real zdiff = amrex::max(zq_kp1_prandtl - sfclayer, zero_d);
1661  const Real prnumfac = amrex::Real(-3.0) * zdiff * zdiff / (pblh * pblh);
1662 
1663  // Step 6: Compute prnum0 base Prandtl (WRF lines 966-970)
1664  // prnum0 = phiH/phiM + prfac
1665  constexpr Real prmin_wrf = amrex::Real(0.25); // WRF minimum (different from ERF)
1666  constexpr Real prmax_wrf = amrex::Real(4.0);
1667  Real prnum0 = (phit_eff / phiM_eff) + prfac;
1668  prnum0 = amrex::min(amrex::max(prnum0, prmin_wrf), prmax_wrf);
1669 
1670  // Step 7: Compute heat Prandtl with free-convection correction and height blend
1671  // WRF uses prnum0_heat = prnum0 / (1 + prfac2*karman*sfcfrac) * exp(prnumfac)
1672  Real prnum0_heat = prnum0 / (one + prfac2 * KAPPA * sfcfrac);
1673  prnum0_heat = amrex::min(amrex::max(prnum0_heat, prmin_wrf), prmax_wrf);
1674  const Real Prt = one + (prnum0_heat - one) * std::exp(prnumfac);
1675 
1676  // Step 8: Compute moisture Prandtl (uses prnum0 WITHOUT the free-convection correction)
1677  // WRF uses prnum_q = prnum0 * exp(prnumfac)
1678  const Real prnum_q = one + (prnum0 - one) * std::exp(prnumfac);
1679 
1680  // Use pre-computed wstar from the dedicated recomputation loop (lines 465-545).
1681  // wstar_arr was computed with pblh_corr_arr to ensure consistency
1682  // between countergradient diagnostics and K-profile calculations.
1683  //const Real wstar = wstar_arr(i, j, 0);
1684 
1685  // SFCFLG gating: WRF skips nonlocal mixing in stable PBL (SFCFLG=.FALSE., BR>0, obuk_val>0)
1686  // In stable conditions, use free-atmosphere Richardson mixing instead.
1687  // WRF Reference: module_bl_ysu.F lines 200, 220-260
1688  if (SFCFLG) {
1689  // PHASE 13 CHANGES: Use layer-top interface height (zq_kp1) and
1690  // level-dependent wscalek for proper K-profile formulation.
1691  // WRF Reference: module_bl_ysu.F lines 943-961
1692 
1693  // Step 1: Compute zq_kp1 (top interface of cell k)
1694  // zq(k+1) in WRF = cell center + dz/2
1695  const Real zq_kp1 = zval + myhalf * dz_terrain;
1696 
1697  // Step 2: Get the first-level height (zl1)
1698  const Real zl1 = (use_terrain_fitted_coords)
1699  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
1700  : (ksrf + myhalf) * dz;
1701 
1702  // Step 3: Compute zfac using zq_kp1 and zl1 (WRF bl_ysu.F90 line 943)
1703  // zfac = min(max((1-(zq(k+1)-zl1)/(hpbl-zl1)), zfmin), 1.)
1704  constexpr Real zfacmin = amrex::Real(1.0e-8);
1705  const Real pblh_rel = amrex::max(pblh_corr_arr(i, j, 0) - zl1, amrex::Real(1.0e-4));
1706  const Real zfac = amrex::min(
1707  amrex::max(one_d - (zq_kp1 - zl1) / pblh_rel, zfacmin), one_d);
1708 
1709  // Step 4: Compute level-dependent wscalek (for K-profile, NOT for HGAMT/HGAMQ)
1710  // WRF stores wstar3 per column; we now have it from Phase 12
1711  const Real ust3_wscale = us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0) * us_eff_arr(i, j, 0);
1712 
1713  Real wscalek_val;
1714  // Unstable/neutral: wscalek = (ust3 + phifac*karman*wstar3*(1-zfac))^(1/3)
1715  wscalek_val = std::cbrt(ust3_wscale + amrex::Real(8.0) * KAPPA * wstar3_col * (one - zfac));
1716 
1717  // Step 5: Compute K_m using zq_kp1 and wscalek_val (WRF line 961)
1718  // WRF: xkzm(i,k) = wscalek(k)*karman*zq(k+1)*zfac(k)**pfac
1719  // The mixing length is the height above the column's own
1720  // surface (zib with erf.pbl_ib_aware, zero otherwise).
1721  constexpr Real ckz_pbl = Real(0.001);
1722  const Real K_base = ckz_pbl * dz_terrain * rho;
1723  constexpr Real pfac = amrex::Real(2.0);
1724  K_turb(i, j, k, EddyDiff::Mom_v) = K_base + rho * wscalek_val * KAPPA * (zq_kp1 - zib) * std::pow(zfac, pfac);
1725 
1726  // Apply Prandtl number to get heat and moisture diffusivity
1727  K_turb(i, j, k, EddyDiff::Theta_v) = K_turb(i, j, k, EddyDiff::Mom_v) / Prt;
1728  if (turbChoice.ysu_moistvars) {
1729  K_turb(i, j, k, EddyDiff::Q_v) = K_turb(i, j, k, EddyDiff::Mom_v) / prnum_q;
1730  } else {
1731  K_turb(i, j, k, EddyDiff::Q_v) = K_turb(i, j, k, EddyDiff::Theta_v);
1732  }
1733 
1734  // Add top-down contribution (H10 Eq. 11)
1735  if (enable_ysu_topdown && k < pbli_arr(i, j, 0)) {
1736  K_turb(i, j, k, EddyDiff::Mom_v) += K_down_arr(i, j, k);
1737  K_turb(i, j, k, EddyDiff::Theta_v) += K_down_arr(i, j, k);
1738  }
1739  } else {
1740  // SECTION B: Stable PBL (sfcflg=false, k < pbli_extent)
1741  // WRF uses wscalek = ust/phi_m(zq(k+1)/L), NOT Richardson mixing inside PBL
1742  // Richardson mixing is ONLY for k >= pbli_extent (free atmosphere)
1743  // WRF Reference: bl_ysu.F90 lines 951-957
1744 
1745  // Step 1: Compute zq_kp1 (top interface of cell k)
1746  const Real zq_kp1_stable = zval + myhalf * dz_terrain;
1747 
1748  // Step 2: Get first-level height (zl1)
1749  const Real zl1_stable = (use_terrain_fitted_coords)
1750  ? Compute_Zrel_AtCellCenter(i, j, ksrf, z_sfc_arr, z_nd_arr)
1751  : (ksrf + myhalf) * dz;
1752 
1753  // Step 3: Compute zfac for stable PBL
1754  constexpr Real zfacmin_stable = amrex::Real(1.0e-8);
1755  const Real pblh_rel_stable = amrex::max(pblh_corr_arr(i, j, 0) - zl1_stable, amrex::Real(1.0e-4));
1756  const Real zfac_stable = amrex::min(
1757  amrex::max(one_d - (zq_kp1_stable - zl1_stable) / pblh_rel_stable, zfacmin_stable), one_d);
1758 
1759  // Step 4: Compute stable wscalek using phi_m
1760  // WRF bl_ysu.F90 lines 951-957: wscalek = ust / phi_m(zq(k+1)/L)
1761  const Real zol1_stable = zol1_arr_cap(i, j, 0); // stored from Phase 12
1762  const Real zol_ratio = (zq_kp1_stable - zib) / (zl1_stable - zib); // zq(k+1) / zl1, above the column's surface
1763  const Real phim_stable_arg = zol1_stable * zol_ratio; // (z/L) for level k+1
1764  // Enable QNSE stable functions if requested, otherwise use default linear form
1765  const Real enable_qnse_d = (turbChoice.enable_qnse_stable_functions) ? Real(1.0) : Real(0.0);
1766  const Real qnse_am_d = turbChoice.qnse_am;
1767  const Real qnse_bm_d = turbChoice.qnse_bm;
1768  const Real phim_stable = (enable_qnse_d > Real(0.5))
1769  ? ((one + qnse_am_d * phim_stable_arg) / (one + qnse_bm_d * phim_stable_arg))
1770  : (one + amrex::Real(5.0) * phim_stable_arg); // stable: phi_m = 1 + 5*(z/L)
1771  const Real wscalek_stable = amrex::max(
1772  us_eff_arr(i, j, 0) / amrex::max(phim_stable, amrex::Real(0.01)),
1773  amrex::Real(0.001));
1774 
1775  // Step 5: Compute K_m for stable PBL using wscalek
1776  constexpr Real ckz_pbl_stable = Real(0.001);
1777  const Real K_base_stable = ckz_pbl_stable * dz_terrain * rho;
1778  constexpr Real pfac_stable = amrex::Real(2.0);
1779  K_turb(i, j, k, EddyDiff::Mom_v) = K_base_stable + rho * wscalek_stable * KAPPA * (zq_kp1_stable - zib) * std::pow(zfac_stable, pfac_stable);
1780 
1781  // Step 6: Apply Prandtl number for stable PBL
1782  // For stable, prfac=0 (from step 3 of SECTION A)
1783  // prnum = phiH/phiM without height blending adjustment
1784  const Real prnum_stable = one + (prnum0 - one) * std::exp(prnumfac);
1785  K_turb(i, j, k, EddyDiff::Theta_v) = K_turb(i, j, k, EddyDiff::Mom_v) / prnum_stable;
1786 
1787  if (turbChoice.ysu_moistvars) {
1788  K_turb(i, j, k, EddyDiff::Q_v) = K_turb(i, j, k, EddyDiff::Mom_v) / prnum_q;
1789  } else {
1790  K_turb(i, j, k, EddyDiff::Q_v) = K_turb(i, j, k, EddyDiff::Theta_v);
1791  }
1792  }
1793  } else if (k >= pbli_extent) {
1794  // Free atmosphere above PBL: use local Richardson number-dependent mixing
1795  // with H10 (Hong 2010) grid-adaptive lengthscale
1796  // WRF Reference: module_bl_ysu.F; H10 Section 3a
1797  // H10 = Hong, S.-Y., 2010: A new stable boundary-layer mixing scheme. QJRMS, 136, 1481-1496.
1798  const Real lambda_min = Real(30.0);
1799  const Real lambda_max = Real(300.0);
1800  const Real lambdadz = amrex::min(amrex::max(Real(0.1) * dz_terrain, lambda_min), lambda_max);
1801  const Real lscale = (lambdadz * KAPPA * zval) / (lambdadz + KAPPA * zval);
1802  Real dthetadz, dudz, dvdz;
1803  ComputeVerticalDerivativesPBL(i, j, k, uvel, vvel, cell_data, izmin, izmax, pbl_derivative_dz_inv(i,j,k),
1804  c_ext_dir_on_zlo, c_ext_dir_on_zhi, u_ext_dir_on_zlo,
1805  u_ext_dir_on_zhi, v_ext_dir_on_zlo, v_ext_dir_on_zhi, dthetadz,
1806  dudz, dvdz, moisture_indices, pbl_strat);
1807 
1808  // This branch is the free atmosphere above the PBL, so it only
1809  // reaches the first fluid cell of the column when the PBL index
1810  // collapses to it. The resolved gradients are unusable there
1811  // (ERF #4037), so fall back on the MOST profile. The effective
1812  // surface scales and the local surface index are used so that an
1813  // immersed surface is handled the same way as the domain bottom.
1814  if (k == ksrf) {
1815  const Real zrel_sl = amrex::max(zval - zib, Real(1.0e-4));
1816  const Real theta = cell_data(i, j, k, RhoTheta_comp) / rho;
1817  const Real qv = (moisture_indices.qv >= 0) ?
1818  cell_data(i, j, k, moisture_indices.qv) / rho : zero;
1820  sl.u_star = us_eff_arr(i, j, 0);
1821  sl.tstar_v = ComputeVirtualTStarPBL(ts_eff_arr(i, j, 0),
1822  use_moisture ? qs_eff_arr(i, j, 0) : zero,
1823  theta, qv, use_moisture);
1824  sl.zval = zrel_sl;
1825  sl.zeta = zrel_sl / obuk_val;
1826  sl.sfuns = l_sfuns;
1827  ApplySurfaceLayerGradientsPBL(sl, dthetadz, dudz, dvdz);
1828  }
1829 
1830  // Apply boundary safeguards to avoid numerical instability in calm conditions above PBL
1831  const Real dudz_safe = (k < izmax) ? dudz : zero;
1832  const Real dvdz_safe = (k < izmax) ? dvdz : zero;
1833 
1834  // Wind shear magnitude with safety threshold (WRF approach, optimized for GPU precision)
1835  // Using separate safety threshold avoids numerical issues with very small wind shear
1836  const Real wind_shear = dudz_safe * dudz_safe + dvdz_safe * dvdz_safe;
1837  const Real wind_shear_safe = std::max(wind_shear, Real(1.0e-8));
1838 
1839  // Use virtual potential temperature (θ_v) for Richardson number stability calculation.
1840  // This correctly accounts for moisture effects on buoyancy.
1841  // WRF Reference: module_bl_ysu.F uses THVX (virtual potential temperature).
1842  // For moist air, θ_v = θ * (1 + 0.61*q_v - q_l - q_i) ≈ θ * (1 + 0.61*q_v)
1843  const Real theta_v = GetThetav(i, j, k, cell_data, moisture_indices);
1844  const Real dtheta_v_dz = dthetadz;
1845 
1846  // Gradient Richardson number: Ri_g = (g/θ_v) * (dθ_v/dz) / (shear²)
1847  // Reference: WRF module_bl_ysu.F line ~450-456, Hong et al. 2006, Eqn. A16a
1848  //
1849  // For STABILITY ANALYSIS:
1850  // Ri_g > 0.5: typically considered strongly stable (turbulence suppressed)
1851  // 0 < Ri_g < 0.5: weakly stable
1852  // Ri_g < 0: unstable (turbulence enhanced)
1853  // Ri_g < -100: very strong instability (apply lower bound for safety)
1854  //
1855  // Bound values from below (-100.0) and above (100.0)
1856  // to prevent extreme floating-point scales from causing numerical instability
1857  Real grad_Ri = CONST_GRAV / theta_v * dtheta_v_dz / wind_shear_safe;
1858  grad_Ri = std::max(std::min(grad_Ri, Real(100.0)), -Real(100.0));
1859 
1860  // GAP 10: In-cloud moist Richardson number modification
1861  // WRF bl_ysu.F90 lines 992-1000 (imvdif == 1, which is hardcoded in WRF)
1862  // Only apply when both the current AND next cell are in-cloud (qc+qi > 0.01e-3 kg/kg)
1863  if (use_moisture && moisture_indices.qc >= 0 && k < izmax) {
1864  const Real rho_k = cell_data(i,j,k, Rho_comp);
1865  const Real rho_kp1 = cell_data(i,j,k+1,Rho_comp);
1866  Real qc_k = (moisture_indices.qc >= 0) ? cell_data(i,j,k, moisture_indices.qc)/rho_k : zero;
1867  Real qc_kp1 = (moisture_indices.qc >= 0) ? cell_data(i,j,k+1,moisture_indices.qc)/rho_kp1 : zero;
1868  Real qi_k = (moisture_indices.qi >= 0) ? cell_data(i,j,k, moisture_indices.qi)/rho_k : zero;
1869  Real qi_kp1 = (moisture_indices.qi >= 0) ? cell_data(i,j,k+1,moisture_indices.qi)/rho_kp1 : zero;
1870 
1871  constexpr Real cloud_thresh = amrex::Real(0.01e-3); // 0.01 g/kg in kg/kg
1872  if ((qc_k + qi_k) > cloud_thresh && (qc_kp1 + qi_kp1) > cloud_thresh) {
1873  // WRF bl_ysu.F90 lines 997-1000:
1874  // qmean = 0.5*(qvx(k)+qvx(k+1))
1875  // tmean = 0.5*(tx(k)+tx(k+1)) [temperature, not theta]
1876  // alpha = xlv*qmean/rd/tmean
1877  // chi = xlv*xlv*qmean / (cp*rv*tmean*tmean)
1878  // ri = (1+alpha)*(ri - g^2/(ss*tmean*cp) * (chi-alpha)/(1+chi))
1879  const Real qv_k_mri = (moisture_indices.qv >= 0)
1880  ? cell_data(i,j,k, moisture_indices.qv) / rho_k : zero;
1881  const Real qv_kp1_mri = (moisture_indices.qv >= 0)
1882  ? cell_data(i,j,k+1,moisture_indices.qv) / rho_kp1 : zero;
1883  // Use proper temperature (not theta) matching WRF's tx(i,k) — Fix 2
1884  const Real T_k = getTgivenRandRTh(rho_k, cell_data(i,j,k, RhoTheta_comp), qv_k_mri);
1885  const Real T_kp1 = getTgivenRandRTh(rho_kp1, cell_data(i,j,k+1,RhoTheta_comp), qv_kp1_mri);
1886  const Real tmean = myhalf * (T_k + T_kp1);
1887  const Real qmean = myhalf * (qv_k_mri + qv_kp1_mri);
1888  constexpr Real xlv = amrex::Real(2.5e6); // latent heat of vaporization (J/kg)
1889  constexpr Real rd = amrex::Real(287.0); // gas constant dry air (J/kg/K)
1890  constexpr Real rv = amrex::Real(461.5); // gas constant water vapor (J/kg/K)
1891  constexpr Real cp = amrex::Real(1004.0); // specific heat dry air (J/kg/K)
1892  const Real alpha = xlv * qmean / (rd * tmean);
1893  const Real chi = xlv * xlv * qmean / (cp * rv * tmean * tmean);
1894  // Moist Ri correction:
1895  grad_Ri = (one + alpha) * (grad_Ri
1896  - CONST_GRAV * CONST_GRAV / wind_shear_safe / tmean / cp
1897  * (chi - alpha) / (one + chi));
1898  grad_Ri = amrex::max(amrex::min(grad_Ri, amrex::Real(100.0)), amrex::Real(-100.0));
1899  }
1900  }
1901 
1902  // YSU stability functions (Hong et al. 2006, MWR, Appendix A)
1903  // Reference: https://doi.org/10.1175/MWR3199.1
1904  // See equations A18-A20
1905  //
1906  // Prandtl number in stable regime:
1907  // Pr = 1 + 2.1 * Ri_g (Eqn. A19)
1908  // Stability functions for momentum and heat:
1909  // For Ri_g > 0 (stable):
1910  // f_t = 1 / ((1 + 5*Ri_g)²) (Eqn. A18)
1911  // f_m = 1 / ((1 + 5*Ri_g)²) (same function as f_t; HND06 gives f_t only)
1912  // For Ri_g < 0 (unstable):
1913  // f_m = 1 - 8*Ri_g / (1 + 1.746*sqrt(-Ri_g)) (Eqn. A20b)
1914  // f_t = 1 - 8*Ri_g / (1 + 1.286*sqrt(-Ri_g)) (Eqn. A20a)
1915  // Protect against numerical errors causing negative grad_Ri
1916  const Real grad_Ri_safe = amrex::max(grad_Ri, -Real(100.0)); // Bound negative values
1917  const Real fm = (grad_Ri_safe > 0)
1918  ? one / ((one + Real(5.0) * grad_Ri_safe) * (one + Real(5.0) * grad_Ri_safe))
1919  : 1 - 8 * grad_Ri_safe / (1 + Real(1.746) * std::sqrt(amrex::max(-grad_Ri_safe, zero_d))); // stable: as Eqn. A18; unstable: Eqn. A20b
1920  const Real ft = (grad_Ri_safe > 0)
1921  ? one / ((one + Real(5.0) * grad_Ri_safe) * (one + Real(5.0) * grad_Ri_safe))
1922  : 1 - 8 * grad_Ri_safe / (1 + Real(1.286) * std::sqrt(amrex::max(-grad_Ri_safe, zero_d))); // stable: Eqn. A18; unstable: Eqn. A20a
1923  const Real rl2wsp = rho * lscale * lscale * std::sqrt(wind_shear);
1924 
1925  K_turb(i, j, k, EddyDiff::Mom_v) = rl2wsp * fm;
1926  // H10 formulation: for stable conditions, K_t = K_m / Pr
1927  if (grad_Ri_safe > 0) {
1928  Real Pr = amrex::min(amrex::max(one + Real(2.1) * grad_Ri, Real(0.25)), Real(4.0));
1929  K_turb(i, j, k, EddyDiff::Theta_v) = K_turb(i, j, k, EddyDiff::Mom_v) / Pr;
1930  } else {
1931  K_turb(i, j, k, EddyDiff::Theta_v) = rl2wsp * ft;
1932  }
1933  // WRF YSU: moisture diffusivity matches heat in free atmosphere
1934  // Physics: Above PBL, Richardson number mixing applies same Ri_g
1935  // dependent mixing to both heat and moisture. The heat scaling (ft or K_m/Pr)
1936  // is used for moisture, which implicitly assumes equal turbulent
1937  // Prandtl and Schmidt numbers in the stable/unstable free atmosphere.
1938  // Q diffusivity matches heat in free atmosphere (same Ri_g-dependent mixing)
1939  K_turb(i, j, k, EddyDiff::Q_v) = K_turb(i, j, k, EddyDiff::Theta_v);
1940  }
1941  // Note: The conditions (k < pbli_extent) and (k >= pbli_extent) are exhaustive,
1942  // so the else clause would be unreachable. All cells reach K-bounds clipping below.
1943 
1944  // Add entrainment diffusivity at PBL top cell (HND06 Eqs. A9-A13, A21)
1945  // Applied only at k == pbli_arr(i,j,0) (the first cell above the PBL)
1946  if (k == pbli_arr(i,j,0)) {
1947  K_turb(i,j,k,EddyDiff::Mom_v) += entr_arr(i,j,0);
1948  K_turb(i,j,k,EddyDiff::Theta_v) += entr_arr(i,j,0);
1949  if (turbChoice.ysu_moistvars) {
1950  K_turb(i,j,k,EddyDiff::Q_v) += entr_arr(i,j,0);
1951  }
1952  }
1953 
1954  // Limit diffusion coefficients to physical bounds
1955  // These bounds ensure numerical stability and prevent unrealistic diffusivity
1956  // that could violate conservation principles or cause solver issues.
1957  //
1958  // Conservative Limits (module_bl_ysu.F lines 300-320):
1959  // https://github.com/wrf-model/WRF/blob/master/phys/module_bl_ysu.F#L300-L320
1960  // Kmin = 0.1 m²/s, Kmax = 300 m²/s
1961  //
1962  // These limits were calibrated for global forecast models and found to be
1963  // robust across a wide range of atmospheric conditions. They prevent:
1964  // - Excessive diffusion in calm conditions (Kmax bound)
1965  // - Numerical instability from too-small diffusion (Kmin bound)
1966  // - CFL violations from over-diffusive mixing
1967  //
1968  // Alternative (Higher Limits) HND06 formulation (MWR, end of Appendix A):
1969  // Kmin = ckz * dz * rho (where ckz = 0.001), Kmax = 1000 m²/s
1970  // These higher limits allow greater mixing in free atmosphere and are
1971  // more appropriate for high-resolution simulations.
1972  Real rhoKmin, rhoKmax;
1973  if (turbChoice.pbl_ysunew_highres_bounds) {
1974  // Hong et al. 2006, MWR, Appendix A: Higher limits for free atmosphere
1975  // These are recommended for high-resolution simulations (Δz < 100 m)
1976  // where the free atmosphere grid can resolve small-scale mixing.
1977  constexpr Real ckz = Real(0.001);
1978  constexpr Real Kmax = Real(1000.0);
1979  rhoKmin = ckz * dz_terrain * rho;
1980  rhoKmax = rho * Kmax;
1981  } else {
1982  // Conservative limits (default; not taken from HND06)
1983  // These provide good results for typical meteorological scales (Δz > 100 m)
1984  // and are the standard in legacy WRF configurations.
1985  constexpr Real Kmin = Real(0.1);
1986  constexpr Real Kmax = Real(300.0);
1987  rhoKmin = rho * Kmin;
1988  rhoKmax = rho * Kmax;
1989  }
1990 
1991  #ifdef ERF_USE_WINDFARM
1992  // Wind farm coupling: if TKE from Fitch/EWP model is available and positive at this cell,
1993  // augment wscale to reflect enhanced turbulence from turbine wakes.
1994  // This requires mf_vars_windfarm to be passed in (added to function signature below).
1995  // For now, add a placeholder comment:
1996  // TODO: Accept optional MultiFab* windfarm_tke argument. When non-null and
1997  // windfarm_tke(i,j,k) > 0, augment K_turb by rho * sqrt(windfarm_tke(i,j,k)) * lscale.
1998  #endif
1999 
2000  // SECTION C: Asymmetric Background Diffusivity Floor (WRF bl_ysu.F90 lines 141-142, 972-974)
2001  // Applied INSIDE the PBL only (k < pbli_extent)
2002  // WRF parameters:
2003  // xkzminm = 0.1 m²/s (background for momentum, added to xkzm)
2004  // xkzminh = 0.01 m²/s (background for heat and moisture, added to xkzh and xkzq)
2005  if (k < pbli_extent) {
2006  constexpr Real xkzminm = amrex::Real(0.1); // background for momentum
2007  constexpr Real xkzminh = amrex::Real(0.01); // background for heat/moisture
2008  K_turb(i, j, k, EddyDiff::Mom_v) += rho * xkzminm;
2009  K_turb(i, j, k, EddyDiff::Theta_v) += rho * xkzminh;
2010  K_turb(i, j, k, EddyDiff::Q_v) += rho * xkzminh;
2011  }
2012  // NOTE: The free-atmosphere branch (k >= pbli_extent) keeps the existing
2013  // ckz*dz*rho floor from the WRF high-res bounds parameterization.
2014 
2015  K_turb(i, j, k, EddyDiff::Mom_v) = std::max(
2016  std::min(K_turb(i, j, k, EddyDiff::Mom_v), rhoKmax), rhoKmin);
2017  K_turb(i, j, k, EddyDiff::Theta_v) = std::max(
2018  std::min(K_turb(i, j, k, EddyDiff::Theta_v), rhoKmax), rhoKmin);
2019  K_turb(i, j, k, EddyDiff::Q_v) = std::max(
2020  std::min(K_turb(i, j, k, EddyDiff::Q_v), rhoKmax), rhoKmin);
2021  K_turb(i, j, k, EddyDiff::Turb_lengthscale) = pblh_corr_arr(i, j, 0);
2022 
2023  // Store countergradient correction terms (HGAMT/h and HGAMQ/h)
2024  // Use the selected PBL extent index (pbli_arr or pbli_zero_arr based on pbl_mrf_use_zero_ri_extent)
2025  // IMPORTANT — units convention for HGAMT_v / HGAMQ_v / HGAMU_v / HGAMV_v:
2026  // HGAMT_v and HGAMQ_v are stored normalized by pblh (i.e. HGAMT/h,
2027  // HGAMQ/h), matching the MRF scheme's convention. HGAMU_v/HGAMV_v
2028  // store the signed brint*u/v momentum countergradient term directly
2029  // (no pblh normalization, since brint already carries the 1/pblh^0
2030  // scaling from the WRF formulation — see hgamu_arr/hgamv_arr above).
2031  //
2032  // None of these four fields require an extra 1/dz (dz_inv) factor
2033  // when consumed by the implicit solver. In ERF_ImplicitDiff_T.cpp
2034  // (ImplicitDiffForStateLU_T and ImplicitDiffForMomLU_T), the RHS
2035  // countergradient contribution is:
2036  // RHS -= Fact * (rhoAlpha_hi * gam_hi - rhoAlpha_lo * gam_lo)
2037  // with no metric factor (the term carries no vertical derivative), and
2038  // where `Fact = implicit_fac * dt * dz_inv` ALREADY contains the
2039  // single grid-spacing factor required. Multiplying by dz_inv a
2040  // second time double-applies the grid spacing and
2041  // produces an incorrect (grid-resolution-dependent) correction.
2042  // This was verified against Exec/CanonicalTests/ABL/MRF_YSUNew_Enhancements/
2043  // canonical/veryunstable_cgcheck_abl — the extra dz_inv breaks the
2044  // countergradient balance check in that case. Do NOT re-add dz_inv
2045  // to the gam_hi/gam_lo terms in ERF_ImplicitDiff_T.cpp.
2046  if (k < pbli_extent) {
2047  // Inside PBL: store the normalized countergradient terms
2048  K_turb(i, j, k, EddyDiff::HGAMT_v) = hgamt_arr(i, j, 0);
2049  K_turb(i, j, k, EddyDiff::HGAMQ_v) = hgamq_arr(i, j, 0);
2050  K_turb(i, j, k, EddyDiff::HGAMU_v) = hgamu_arr(i, j, 0);
2051  K_turb(i, j, k, EddyDiff::HGAMV_v) = hgamv_arr(i, j, 0);
2052  } else {
2053  // Outside PBL: zero countergradient
2054  K_turb(i, j, k, EddyDiff::HGAMT_v) = zero;
2055  K_turb(i, j, k, EddyDiff::HGAMQ_v) = zero;
2056  K_turb(i, j, k, EddyDiff::HGAMU_v) = zero;
2057  K_turb(i, j, k, EddyDiff::HGAMV_v) = zero;
2058  }
2059  });
2060  BL_PROFILE_VAR_STOP(prof_kprof);
2061  // Debug print disabled for production runs.
2062  // amrex::Print()<<" Turbulent Viscosity at cell "<<K_turb(2, 2, 2, EddyDiff::Mom_v)<<" "<<pblh_corr_arr(2, 2, 0)<<std::endl;
2063  // FOEXTRAP top and bottom ghost cells
2064  ParallelFor(xybx, [=] AMREX_GPU_DEVICE(int i, int j, int ) noexcept
2065  {
2066  K_turb(i, j, klo-1, EddyDiff::Mom_v ) = K_turb(i, j, klo, EddyDiff::Mom_v );
2067  K_turb(i, j, klo-1, EddyDiff::Theta_v) = K_turb(i, j, klo, EddyDiff::Theta_v);
2068  K_turb(i, j, klo-1, EddyDiff::Q_v ) = K_turb(i, j, klo, EddyDiff::Q_v );
2069  K_turb(i, j, klo-1, EddyDiff::HGAMT_v) = K_turb(i, j, klo, EddyDiff::HGAMT_v);
2070  K_turb(i, j, klo-1, EddyDiff::HGAMQ_v) = K_turb(i, j, klo, EddyDiff::HGAMQ_v);
2071  K_turb(i, j, klo-1, EddyDiff::HGAMU_v) = K_turb(i, j, klo, EddyDiff::HGAMU_v);
2072  K_turb(i, j, klo-1, EddyDiff::HGAMV_v) = K_turb(i, j, klo, EddyDiff::HGAMV_v);
2073  K_turb(i, j, klo-1, EddyDiff::Turb_lengthscale) = K_turb(i, j, klo, EddyDiff::Turb_lengthscale);
2074  K_turb(i, j, khi+1, EddyDiff::Mom_v ) = K_turb(i, j, khi, EddyDiff::Mom_v );
2075  K_turb(i, j, khi+1, EddyDiff::Theta_v) = K_turb(i, j, khi, EddyDiff::Theta_v);
2076  K_turb(i, j, khi+1, EddyDiff::Q_v ) = K_turb(i, j, khi, EddyDiff::Q_v );
2077  K_turb(i, j, khi+1, EddyDiff::HGAMT_v) = K_turb(i, j, khi, EddyDiff::HGAMT_v);
2078  K_turb(i, j, khi+1, EddyDiff::HGAMQ_v) = K_turb(i, j, khi, EddyDiff::HGAMQ_v);
2079  K_turb(i, j, khi+1, EddyDiff::HGAMU_v) = K_turb(i, j, khi, EddyDiff::HGAMU_v);
2080  K_turb(i, j, khi+1, EddyDiff::HGAMV_v) = K_turb(i, j, khi, EddyDiff::HGAMV_v);
2081  K_turb(i, j, khi+1, EddyDiff::Turb_lengthscale) = K_turb(i, j, khi, EddyDiff::Turb_lengthscale);
2082  });
2083  }// mfi
2084  // Write the YSU-computed PBLH back into SurfaceLayer so Beljaars correction
2085  // and diagnostics can use it, and update_pblh no longer aborts for the YSU type.
2086  // REGRID NOTE: On regrid, SurfaceLayer is reallocated and PBLH returns to sentinel.
2087  // The driver must call ComputeDiffusivityYSU (or an equivalent bootstrap pass)
2088  // before consuming PBLH in update_fluxes() or Beljaars correction after any regrid.
2089  SurfLayer->set_pblh(level, pblh_mf);
2090 }
constexpr amrex::Real epsv
Definition: ERF_Constants.H:56
constexpr amrex::Real KAPPA
Definition: ERF_Constants.H:71
constexpr amrex::Real CONST_GRAV
Definition: ERF_Constants.H:72
constexpr amrex::Real immersed_neutral_obukhov_length
Definition: ERF_Constants.H:31
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real getTgivenRandRTh(const amrex::Real rho, const amrex::Real rhotheta, const amrex::Real qv=amrex::Real(0))
Definition: ERF_EOS.H:46
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real getPgivenRTh(const amrex::Real rhotheta, const amrex::Real qv=amrex::Real(0))
Definition: ERF_EOS.H:81
#define Rho_comp
Definition: ERF_IndexDefines.H:61
#define RhoTheta_comp
Definition: ERF_IndexDefines.H:62
amrex::GpuArray< Real, AMREX_SPACEDIM > dxInv
Definition: ERF_InitCustomPertVels_ParticleTests.H:16
Real z0
Definition: ERF_InitCustomPertVels_ScalarAdvDiff.H:12
const bool use_moisture
Definition: ERF_InitCustomPert_ABL.H:127
AMREX_ALWAYS_ASSERT_WITH_MESSAGE(axis >=0 &&axis< AMREX_SPACEDIM, "prob.axis must be 0, 1 or 2")
const int khi
Definition: ERF_InitCustomPert_Bubble.H:25
AMREX_ALWAYS_ASSERT(bx.length()[2]==khi+1)
const int klo
Definition: ERF_InitCustomPert_KE.H:9
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE void erf_qsatw(amrex::Real t, amrex::Real p, amrex::Real &qsatw)
Definition: ERF_MicrophysicsUtils.H:265
AMREX_GPU_DEVICE AMREX_FORCE_INLINE amrex::Real GetThetav(const int &i, const int &j, const int &k, const amrex::Array4< amrex::Real const > &cell_data, const MoistureComponentIndices &moisture_indices)
Definition: ERF_MoistUtils.H:93
AMREX_GPU_DEVICE AMREX_FORCE_INLINE amrex::Real GetThetal(const int &i, const int &j, const int &k, const amrex::Array4< amrex::Real const > &cell_data, const MoistureComponentIndices &moisture_indices)
Definition: ERF_MoistUtils.H:127
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);})
constexpr amrex::Real real_eps
Definition: ERF_NumericalConstants.H:34
constexpr amrex::Real two
Definition: ERF_NumericalConstants.H:38
constexpr amrex::Real one
Definition: ERF_NumericalConstants.H:37
constexpr amrex::Real fourth
Definition: ERF_NumericalConstants.H:42
constexpr amrex::Real zero
Definition: ERF_NumericalConstants.H:36
constexpr amrex::Real myhalf
Definition: ERF_NumericalConstants.H:41
std::unique_ptr< amrex::MultiFab > WidenForPBLH(const amrex::MultiFab &src, const int ng, const std::function< void(amrex::MultiFab &)> &fill)
Definition: ERF_PBLModels.H:789
AMREX_GPU_DEVICE AMREX_FORCE_INLINE void ComputeVerticalDerivativesPBL(int i, int j, int k, const amrex::Array4< const amrex::Real > &uvel, const amrex::Array4< const amrex::Real > &vvel, const amrex::Array4< const amrex::Real > &cell_data, const int izmin, const int izmax, const PBLDerivativeDzInv &dz_inv, const bool c_ext_dir_on_zlo, const bool c_ext_dir_on_zhi, const bool u_ext_dir_on_zlo, const bool u_ext_dir_on_zhi, const bool v_ext_dir_on_zlo, const bool v_ext_dir_on_zhi, amrex::Real &dthetadz, amrex::Real &dudz, amrex::Real &dvdz, const MoistureComponentIndices &moisture_indices, const StratType strat=StratType::thetav)
Definition: ERF_PBLModels.H:291
void ApplyPBLHSmoothing(amrex::FArrayBox &pblh_fab, const amrex::Box &xybx_valid, const amrex::Real weight, const int passes, const amrex::Box &domain, const amrex::Periodicity &periodicity)
Apply spatial smoothing to PBLH field using 5-point stencil.
Definition: ERF_PBLModels.H:706
AMREX_GPU_DEVICE AMREX_FORCE_INLINE void ApplySurfaceLayerGradientsPBL(const PBLSurfaceLayerGradient &sl, amrex::Real &dthetadz, amrex::Real &dudz, amrex::Real &dvdz)
Definition: ERF_PBLModels.H:411
AMREX_GPU_DEVICE AMREX_FORCE_INLINE amrex::Real ComputeVirtualTStarPBL(amrex::Real t_star, amrex::Real q_star, amrex::Real theta, amrex::Real qv, bool use_moisture)
Definition: ERF_PBLModels.H:374
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE RibCrossing find_rib_crossing(int ksrf, int khi, amrex::Real Ribcr, RibAt const &rib_at, ZAt const &z_at, amrex::Real pblh_min, amrex::Real pblh_max) noexcept
Definition: ERF_PBLRibCrossing.H:74
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real pblh_floor(amrex::Real zl1, amrex::Real dz1) noexcept
Definition: ERF_PBLRibCrossing.H:36
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real Compute_Zrel_AtCellCenter(const int &i, const int &j, const int &k, const amrex::Array4< const amrex::Real > &z_sfc_nd, const amrex::Array4< const amrex::Real > &z_nd)
Definition: ERF_TerrainMetrics.H:764
AMREX_GPU_HOST_DEVICE AMREX_FORCE_INLINE amrex::Real Compute_h_zeta_AtCellCenter(const int &i, const int &j, const int &k, const amrex::GpuArray< amrex::Real, AMREX_SPACEDIM > &cellSizeInv, const amrex::Array4< const amrex::Real > &z_nd)
Definition: ERF_TerrainMetrics.H:202
AMREX_FORCE_INLINE amrex::IntVect TileNoZ()
Definition: ERF_TileNoZ.H:11
@ yvel_bc
Definition: ERF_IndexDefines.H:139
@ cons_bc
Definition: ERF_IndexDefines.H:122
@ xvel_bc
Definition: ERF_IndexDefines.H:138
@ ext_dir
Definition: ERF_IndexDefines.H:317
@ Theta_v
Definition: ERF_IndexDefines.H:267
@ Turb_lengthscale
Definition: ERF_IndexDefines.H:271
@ HGAMU_v
Definition: ERF_IndexDefines.H:279
@ Q_v
Definition: ERF_IndexDefines.H:270
@ Mom_v
Definition: ERF_IndexDefines.H:266
@ HGAMQ_v
Definition: ERF_IndexDefines.H:278
@ HGAMT_v
Definition: ERF_IndexDefines.H:277
@ HGAMV_v
Definition: ERF_IndexDefines.H:280
@ ustar
Definition: ERF_SLM.H:30
@ ks
Definition: ERF_SLM.H:76
@ qstar
Definition: ERF_SLM.H:32
@ tstar
Definition: ERF_SLM.H:31
@ rho
Definition: ERF_Kessler.H:25
@ theta
Definition: ERF_Kessler.H:26
@ qv
Definition: ERF_Kessler.H:31
@ alpha
Definition: ERF_SLM.H:153
@ xvel
Definition: ERF_IndexDefines.H:232
@ yvel
Definition: ERF_IndexDefines.H:233
@ dz
Definition: ERF_AdvanceWDM6.cpp:273
real(c_double), parameter cp
Definition: ERF_module_model_constants.F90:22
real(c_double), parameter xlv
Definition: ERF_module_model_constants.F90:57
int qi
cloud ice
Definition: ERF_DataStruct.H:292
int qv
water vapor
Definition: ERF_DataStruct.H:290
int qc
cloud liquid water
Definition: ERF_DataStruct.H:291
Functor for inverse vertical spacings for terrain-following grids using cell-center heights.
Definition: ERF_PBLModels.H:652
Definition: ERF_PBLModels.H:353
amrex::Real tstar_v
virtual temperature scale
Definition: ERF_PBLModels.H:355
amrex::Real zeta
stability coordinate z/L
Definition: ERF_PBLModels.H:357
similarity_funs sfuns
the surface layer's similarity functions (most.stable_functions)
Definition: ERF_PBLModels.H:358
amrex::Real u_star
friction velocity
Definition: ERF_PBLModels.H:354
amrex::Real zval
height of the cell center above the surface
Definition: ERF_PBLModels.H:356
Definition: ERF_PBLRibCrossing.H:11
amrex::Real pblh
PBL height, kept in [pblh_min, pblh_max].
Definition: ERF_PBLRibCrossing.H:13
int kpbl
level where Rib first reaches Ribcr; khi when it never does
Definition: ERF_PBLRibCrossing.H:12
bool crossed
Rib reached Ribcr at or below khi.
Definition: ERF_PBLRibCrossing.H:14
bool enable_mrf_unbounded_vpert
Whether MRF leaves VPERT unlimited by GAMCRT.
Definition: ERF_TurbStruct.H:1129
bool pbl_mrf_use_zero_ri_extent
Whether MRF uses the Ri=0 K-profile extent.
Definition: ERF_TurbStruct.H:1130
StratType pbl_strat_type
Definition: ERF_TurbStruct.H:951
bool enable_vh96_shear_correction
Whether Vogelezang & Holtslag (1996) shear-correction term is enabled.
Definition: ERF_TurbStruct.H:1106
bool enable_ysu_entrainment
Whether YSU entrainment-layer parameterization is enabled.
Definition: ERF_TurbStruct.H:1093
bool enable_ysu_sat_limiter
Whether YSU applies a saturation limiter to moisture countergradient terms.
Definition: ERF_TurbStruct.H:1089
bool enable_ysu_cloud_pblh
Whether the YSU PBL-top cell index is raised by one where that cell is cloudy.
Definition: ERF_TurbStruct.H:1095
amrex::Real pbl_mrf_const_b
MRF constant used to compute PBL height.
Definition: ERF_TurbStruct.H:1114
amrex::Real pblh_smoothing_weight
Center-cell weight in PBLH smoothing stencil (must be in [0,1]).
Definition: ERF_TurbStruct.H:1110
amrex::Real ysu_qcloud_threshold
Cloud water plus cloud ice threshold for YSU [kg/kg].
Definition: ERF_TurbStruct.H:1098
amrex::Real qnse_bm
Definition: ERF_TurbStruct.H:1141
bool enable_qnse_stable_functions
Definition: ERF_TurbStruct.H:1138
bool enable_ysu_countergradient
Whether YSU countergradient corrections are enabled.
Definition: ERF_TurbStruct.H:1087
bool enable_pblh_smoothing
Whether spatial smoothing of diagnosed PBLH is enabled.
Definition: ERF_TurbStruct.H:1108
int pblh_smoothing_passes
Number of PBLH smoothing iterations to apply.
Definition: ERF_TurbStruct.H:1109
amrex::Real pbl_ib_z0
Definition: ERF_TurbStruct.H:1125
bool enable_ysu_topdown
Whether YSU top-down mixing is enabled.
Definition: ERF_TurbStruct.H:1091
bool pbl_ib_aware
Definition: ERF_TurbStruct.H:1124
amrex::Real ysu_rad_tend_limiter_magnitude
Definition: ERF_TurbStruct.H:1104
amrex::Real pbl_ysu_land_Ribcr
Critical bulk Richardson number over land for stable YSU conditions.
Definition: ERF_TurbStruct.H:1085
amrex::Real vh96_shear_const_b
Vogelezang & Holtslag (1996) shear-correction constant b.
Definition: ERF_TurbStruct.H:1107
amrex::Real qnse_am
Definition: ERF_TurbStruct.H:1140
amrex::Real pbl_mrf_sf
MRF surface flux value used to compute PBL height.
Definition: ERF_TurbStruct.H:1115
bool pbl_ysunew_highres_bounds
Whether YSU applies high-resolution grid-dependent diffusivity bounds.
Definition: ERF_TurbStruct.H:1101
amrex::Real pbl_ysu_coriolis_freq
Coriolis frequency used by YSU-family PBL schemes.
Definition: ERF_TurbStruct.H:1079
bool ysu_moistvars
Whether YSU applies turbulence to moisture variables.
Definition: ERF_TurbStruct.H:1100
bool enable_ysu_rad_tend_limiter
Definition: ERF_TurbStruct.H:1103
Definition: ERF_MOSTUtils.H:84
Here is the call graph for this function: