ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_SuperDropletPC.H
Go to the documentation of this file.
1 #ifndef SUPERDROPLET_PC_H_
2 #define SUPERDROPLET_PC_H_
3 
4 #ifdef ERF_USE_PARTICLES
5 
6 #include <random>
11 #include <AMReX_StructOfArrays.H>
12 
13 /*! \brief Ice category for density calculations */
14 enum class IceCategory { Ice, Snow, Graupel, Total };
15 
16 /**
17  * Particle container for the super-droplet method.
18  */
19 class SuperDropletPC : public ERFPC
20 {
21  using MFPtr = std::unique_ptr<amrex::MultiFab>;
22  using BCTypeArr = amrex::GpuArray<ERF_BC, AMREX_SPACEDIM*2>;
23 
24  public:
25 
26  /*! \brief Constructor */
27  SuperDropletPC ( amrex::ParGDBBase* a_gdb,
28  const std::vector<Species::Name>& a_species_mat,
29  const std::vector<Species::Name>& a_aerosol_mat,
30  const double a_dt,
31  const std::string& a_name = "super_droplets" )
32  : ERFPC (a_gdb, a_name, ERFPCOptions{ /*read_particle_init=*/false, /*advect_with_gravity=*/true })
33  {
34  define( a_species_mat,
35  a_aerosol_mat,
36  a_gdb->ParticleBoxArray(0),
37  a_gdb->ParticleDistributionMap(0),
38  a_dt );
39  }
40 
41  /*! \brief Constructor */
42  SuperDropletPC ( const amrex::Geometry& a_geom,
43  const amrex::DistributionMapping& a_dmap,
44  const amrex::BoxArray& a_ba,
45  const std::vector<Species::Name>& a_species_mat,
46  const std::vector<Species::Name>& a_aerosol_mat,
47  const double a_dt,
48  const std::string& a_name = "super_droplets" )
49  : ERFPC (a_geom, a_dmap, a_ba, a_name, ERFPCOptions{ /*read_particle_init=*/false, /*advect_with_gravity=*/true })
50  {
51  define(a_species_mat, a_aerosol_mat, a_ba, a_dmap, a_dt);
52  }
53 
54  /*! \brief Destructor */
55  ~SuperDropletPC ()
56  {
57  if (m_mass_change_logging) {
58  fclose(m_mass_change_log);
59  }
60  }
61 
62  /*! \brief Set vapor species material */
63  AMREX_FORCE_INLINE
64  virtual void setSpeciesMaterial ( const Species::Name& a_name )
65  {
66  if (a_name == Species::Name::H2O) { m_idx_w = m_species_mat.size(); }
67  if (a_name == Species::Name::ice) { m_idx_i = m_species_mat.size(); }
68  m_species_mat.push_back(std::make_unique<MaterialProperties>(a_name));
69  m_device_props_initialized = false; // Properties have changed, need to reinitialize
70  }
71 
72  /*! \brief Set species material */
73  AMREX_FORCE_INLINE
74  virtual void setSpeciesMaterial ( const std::vector<Species::Name>& a_names )
75  {
76  for (auto& name : a_names) { setSpeciesMaterial(name); }
77  }
78 
79  /*! \brief Get vapor material */
80  AMREX_FORCE_INLINE
81  virtual const MaterialProperties& getSpeciesMaterial (const Species::Name& a_name) const
82  {
83  for (auto& species : m_species_mat) {
84  if (species->m_name == a_name) { return *species; }
85  }
86  amrex::Abort("SuperDropletPC::getSpeciesMaterial() - species not found");
87  return *m_species_mat[0];
88  }
89 
90 
91  /*! \brief Set aerosol material */
92  AMREX_FORCE_INLINE
93  virtual void setAerosolMaterial ( const Species::Name& a_name )
94  {
95  m_aerosol_mat.push_back(std::make_unique<MaterialProperties>(a_name));
96  m_device_props_initialized = false; // Properties have changed, need to reinitialize
97  }
98 
99  /*! \brief Set aerosol material */
100  AMREX_FORCE_INLINE
101  virtual void setAerosolMaterial ( const std::vector<Species::Name>& a_names )
102  {
103  for (auto& name : a_names) { setAerosolMaterial(name); }
104  }
105 
106  /*! \brief Update device properties if material properties change */
107  void updateDeviceProperties ();
108 
109  /*! \brief Setup species and aerosol mass pointers from SOA */
110  template<typename SOAType>
111  void setupMassPointers (SOAType& soa, SDPCDefn::SDSpeciesMassArr& sp_mass_ptrs,
112  SDPCDefn::SDAerosolMassArr& ae_mass_ptrs) const
113  {
114  for (int i = 0; i < m_num_species; i++) {
115  sp_mass_ptrs[i] = soa.GetRealData(idx_s(i, m_num_aerosols, m_num_species)).data();
116  }
117  for (int i = 0; i < m_num_aerosols; i++) {
118  ae_mass_ptrs[i] = soa.GetRealData(idx_a(i, m_num_aerosols, m_num_species)).data();
119  }
120  }
121 
122  /*! \brief Update particle radius and total mass from species/aerosol masses */
123  AMREX_GPU_DEVICE AMREX_FORCE_INLINE
124  static void updateParticleAttributes (
125  int particle_idx,
126  amrex::ParticleReal* radius_ptr,
127  amrex::ParticleReal* mass_ptr,
128  int idx_w,
129  amrex::ParticleReal rho_w,
130  int num_sp, int num_ae,
131  const int* sp_sol_arr,
132  const int* ae_sol_arr,
133  const SDPCDefn::SDSpeciesMassArr sp_mass_ptrs,
134  const SDPCDefn::SDAerosolMassArr ae_mass_ptrs,
135  const amrex::ParticleReal* sp_rho_arr,
136  const amrex::ParticleReal* ae_rho_arr)
137  {
138  // Update effective radius
139  radius_ptr[particle_idx] = SD_effective_radius(
140  particle_idx, idx_w, rho_w,
141  num_sp, num_ae,
142  sp_sol_arr, ae_sol_arr,
143  sp_mass_ptrs, ae_mass_ptrs,
144  sp_rho_arr, ae_rho_arr);
145 
146  // Update total mass
147  mass_ptr[particle_idx] = SD_total_mass(
148  particle_idx, num_sp, num_ae,
149  sp_mass_ptrs, ae_mass_ptrs);
150  }
151 
152  /*! \brief Get real-type particle attribute names */
153  [[nodiscard]] virtual amrex::Vector<std::string> varNames () const override;
154 
155  /*! \brief Get Eulerian plot variable names */
156  [[nodiscard]] virtual amrex::Vector<std::string> meshPlotVarNames () const override;
157 
158  /*! \brief Compute mesh variable from particles */
159  virtual void computeMeshVar ( const std::string&,
160  amrex::MultiFab&,
161  const amrex::MultiFab&,
162  const int ) const override;
163 
164  /*! \brief Initialize super-droplets in domain at AMR level a_lev */
165  void InitializeParticles (const int a_lev, const double a_t, const MFPtr& a_ptr);
166 
167  using ERFPC::InitializeParticles;
168 
169  /*! \brief Inject super-droplets in domain */
170  virtual void InjectParticles (const double, const MFPtr& a_ptr, const double);
171 
172  /*! \brief add particles for a given set of initialization parameters */
173  void addParticles ( int a_lev, const MFPtr&, const SDInitProperties&,
174  bool composite_init = false );
175 
176  /*! \brief Set initial number of superdroplets per cell as a box with uniform density */
177  void setNumSDBoxDistribution ( int a_lev,
178  amrex::iMultiFab&,
179  const int,
180  const MFPtr&,
181  const amrex::RealBox&,
182  const bool );
183 
184  /*! \brief Scatter a box-level count of super-droplets over the injection box */
185  void setNumSDPerBox ( int a_lev,
186  amrex::iMultiFab&,
187  const int,
188  const amrex::RealBox&,
189  const unsigned int,
190  const MFPtr& );
191 
192  /*! \brief Set initial number of superdroplets per cell as a bubble with uniform density */
193  void setNumSDBubbleDistribution ( int a_lev,
194  amrex::iMultiFab&,
195  const int,
196  const MFPtr&,
197  const amrex::RealBox&,
198  const bool );
199 
200  /*! \brief Scale the SDM number density with air density
201  * \param[in] a_mf Multifab containing the air density field
202  */
203  virtual void DensityScaling ( const amrex::MultiFab& a_mf, int a_lev = 0 );
204 
205  /*! \brief Evolve particles for one time step */
206  virtual void EvolveParticles ( int,
207  double,
208  amrex::Vector<amrex::Vector<amrex::MultiFab>>&,
209  const amrex::Vector<MFPtr>& ) override
210  {
211  amrex::Abort("SuperDropletPC::EvolveParticles() is intentionally disabled.");
212  }
213 
214  /*! \brief Advect particles for one time step
215  * \param[in] a_lev AMR level
216  * \param[in] a_time Current simulation time
217  * \param[in] a_dt Timestep for advection
218  * \param[in] a_flow_vel Array of face-based velocities
219  * \param[in] a_density Density field
220  * \param[in] a_pressure Pressure field
221  * \param[in] a_temperature Temperature field
222  * \param[in] a_z_phys_nd Array of terrain heights
223  * \param[in] a_bctypes Array of boundary condition types
224  * \param[in] a_recycle Flag to enable particle recycling
225  */
226  virtual void AdvectParticles ( int a_lev,
227  double a_time,
228  double a_dt,
229  const amrex::MultiFab* const a_flow_vel,
230  const amrex::MultiFab& a_density,
231  const amrex::MultiFab& a_pressure,
232  const amrex::MultiFab& a_temperature,
233  const amrex::Vector<MFPtr>& a_z_phys_nd,
234  const BCTypeArr& a_bctypes,
235  const bool a_recycle);
236 
237  /*! \brief Condensation and evaporation growth/shrinking for one time step */
238  virtual void MassChange_LV (int,
239  double,
240  const Species::Name&,
241  const amrex::MultiFab&,
242  const amrex::MultiFab&,
243  const amrex::MultiFab&,
244  const amrex::MultiFab&,
245  const amrex::Vector<MFPtr>&,
246  const bool );
247 
248  /*! \brief Freezing/melting for one time step */
249  virtual void MassChange_SL (int,
250  double,
251  const amrex::MultiFab&,
252  const amrex::MultiFab&,
253  const amrex::MultiFab&,
254  const amrex::Vector<MFPtr>& );
255 
256  /*! \brief Deposition and sublimation growth/shrinking for one time step */
257  virtual void MassChange_SV (int,
258  double,
259  const amrex::MultiFab&,
260  const amrex::MultiFab&,
261  const amrex::MultiFab&,
262  const amrex::MultiFab&,
263  const amrex::MultiFab&,
264  const amrex::MultiFab&,
265  const amrex::MultiFab&,
266  const amrex::Vector<MFPtr>& );
267 
268  /*! \brief Coalescence of super-droplets */
269  virtual void Coalescence ( int,
270  double,
271  const amrex::MultiFab&,
272  const amrex::MultiFab&,
273  const amrex::MultiFab&,
274  const amrex::MultiFab&,
275  const amrex::Vector<MFPtr>& );
276 
277  /*! \brief Recycle super-droplets
278  * \param[in] a_lev AMR level
279  * \param[in] a_z_phys_nd Array of terrain heights
280  * \param[in] a_iter Current iteration number
281  * \param[in] a_dt Timestep size
282  * \param[in] a_recycle Flag to enable recycling
283  */
284  virtual void Recycle ( const int a_lev,
285  const amrex::Vector<MFPtr>& a_z_phys_nd,
286  const int a_iter,
287  const double a_dt,
288  const bool a_recycle);
289 
290  /*! \brief Set the vertical coordinate of recycled super-droplets on their owning grids
291  * \param[in] a_z_phys_nd Array of terrain heights
292  */
293  void placeRecycledParticles ( const amrex::Vector<MFPtr>& a_z_phys_nd );
294 
295  /*! \brief Set the multiplicity of super-droplets that entered through an open lateral
296  * boundary from the cell they entered, once they are on their owning grids
297  * \param[in] a_z_phys_nd Array of terrain heights
298  */
299  void setInflowMultiplicity ( const amrex::Vector<MFPtr>& a_z_phys_nd );
300 
301  /*! \brief Deactivate, reflect or wrap the super-droplets that crossed a domain boundary;
302  * returns the number that entered through an open boundary and still need their
303  * multiplicity (stretched or terrain-fitted mesh); public for CUDA extended lambdas */
304  amrex::Long treatBoundaryCrossings ( int, const BCTypeArr&, const bool );
305 
306  /*! \brief Cells differ in physical thickness (stretched or terrain-fitted mesh) */
307  void setVariableDz ( const bool a_variable_dz )
308  {
309  m_variable_dz = a_variable_dz;
310  for (auto& inj : m_injections) { inj->m_variable_dz = a_variable_dz; }
311  }
312 
313  /*! \brief Return the number of super-droplets
314  This returns the number of AMReX particles being used in the simulation. */
315  [[nodiscard]] inline virtual amrex::Long NumSuperDroplets ()
316  {
317  return ERFPC::TotalNumberOfParticles();
318  }
319 
320  /*! \brief Return the total number of physical particles */
321  [[nodiscard]] virtual amrex::Real TotalNumberOfParticles ();
322 
323  /*! \brief Return the number of deactivated super-droplets */
324  [[nodiscard]] virtual amrex::Long NumSDDeactivated ();
325 
326  /*! \brief Compute and print diagnostics of the state at a step and time (step, level, time, write files, node heights, file name digits) */
327  virtual void Diagnostics (int, int, double, bool, const amrex::MultiFab& a_z_phys_nd, int);
328  /*! \brief Compute mass density distribution */
329  virtual void ComputeDistributions ( int, int,
330  amrex::ParticleReal,
331  amrex::ParticleReal,
332  const amrex::MultiFab& a_z_phys_nd, int );
333 #ifdef ERF_USE_ML_UPHYS_DIAGNOSTICS
334  /*! \brief Compute binned size distributions */
335  virtual void ComputeBinnedDistributions ( int, int, const amrex::MultiFab& a_z_phys_nd, int );
336  /*! \brief Compute cell-wise binned size distributions */
337  virtual void ComputeBinnedDistributionsCell ( int, int, amrex::Real, const amrex::MultiFab& a_z_phys_nd, int );
338 #endif
339 
340  /*! \brief Mean physical volume of the cells of level a_lev */
341  [[nodiscard]] amrex::Real meanCellVolume ( int a_lev, const amrex::MultiFab& a_z_phys_nd ) const;
342 
343  /*! \brief Per-cell counts of every initialization, on the host */
344  [[nodiscard]] amrex::Vector<SDCellCounts> initCellCountsHost () const
345  {
346  amrex::Vector<SDCellCounts> counts_h(m_initializations.size());
347  for (size_t i = 0; i < m_initializations.size(); i++) {
348  counts_h[i] = m_initializations[i]->cellCounts();
349  }
350  return counts_h;
351  }
352 
353  /*! \brief Per-cell counts of every initialization, on the device */
354  [[nodiscard]] amrex::Gpu::DeviceVector<SDCellCounts> initCellCounts () const
355  {
356  const auto counts_h = initCellCountsHost();
357  amrex::Gpu::DeviceVector<SDCellCounts> counts_d(counts_h.size());
358  amrex::Gpu::copy(amrex::Gpu::hostToDevice, counts_h.begin(), counts_h.end(), counts_d.begin());
359  return counts_d;
360  }
361 
362  /*! \brief Compute the SD number density on a mesh */
363  virtual void SDNumberDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int a_comp=0 ) const;
364  /*! \brief Compute the particle number density on a mesh */
365  virtual void numberDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int a_comp=0 ) const;
366  /*! \brief Compute the particle mass density on a mesh */
367  virtual void massDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, const int& a_lev, const int& a_comp=0 ) const override;
368  /*! \brief Compute the mass flux component on a mesh */
369  virtual void massFlux ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int, const int a_comp=0 ) const;
370 
371  /*! \brief Compute the species mass density on a mesh */
372  virtual void speciesMassDensity ( amrex::MultiFab&,
373  const amrex::MultiFab& a_z_phys_nd,
374  int a_lev,
375  int,
376  const int a_comp = 0) const;
377 
378  /*! \brief Compute the cloud/rain mass density on a mesh */
379  virtual void cloudRainDensity ( amrex::MultiFab&,
380  const amrex::MultiFab& a_z_phys_nd,
381  int a_lev,
382  amrex::Real,
383  amrex::Real,
384  const int a_comp = 0) const;
385 
386  /*! \brief Compute ice category mass density on a mesh (ice, snow, graupel, or total) */
387  virtual void iceCategoryDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd,
388  int a_lev, IceCategory, amrex::Real,
389  const int a_comp = 0) const;
390 
391  /*! \brief Compute the ice mass density on a mesh */
392  virtual void iceDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd,
393  int a_lev, amrex::Real, const int a_comp = 0) const;
394 
395  /*! \brief Compute the snow mass density on a mesh */
396  virtual void snowDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd,
397  int a_lev, amrex::Real, const int a_comp = 0) const;
398 
399  /*! \brief Compute the graupel mass density on a mesh */
400  virtual void graupelDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd,
401  int a_lev, amrex::Real, const int a_comp = 0) const;
402 
403  /*! \brief Compute the frozen water mass density on a mesh */
404  virtual void totalIceDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd,
405  int a_lev, const int a_comp = 0) const;
406 
407  /*! \brief Compute the species mass flux component on a mesh */
408  virtual void speciesMassFlux ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int, const int, const int a_comp=0 ) const;
409 
410  /*! \brief Compute the aerosol mass density on a mesh */
411  virtual void aerosolMassDensity ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int, const int a_comp=0 ) const;
412  /*! \brief Compute the aerosol mass flux component on a mesh */
413  virtual void aerosolMassFlux ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int, const int, const int a_comp=0 ) const;
414 
415  /*! \brief Compute the particle effective radius on a mesh */
416  virtual void effectiveRadius ( amrex::MultiFab&, const amrex::MultiFab& a_z_phys_nd, int a_lev, const int a_comp=0 ) const;
417 
418  /*! \brief Applies boundary treatment to the particle container and redistributes it */
419  virtual void applyBoundaryTreatment ( int, const amrex::Vector<MFPtr>&, const BCTypeArr&, const bool );
420 
421  /*! \brief Split coarse-level particles in newly-refined cells after AMR
422  * regrid to restore per-cell SD count. Cascades correctly across
423  * multiple new levels: a coarse particle under L2 is split by the
424  * cumulative refRatio(0)*refRatio(1) and tagged for L2. Skips
425  * particles whose multiplicity is below the relevant split factor. */
426  void SplitParticlesForRefinement ( int a_finest_level ) override;
427 
428  /*! \brief Continuously split new entrants on fine levels and merge
429  * excess-tag super-droplets back into native hosts (tag = level + 1).
430  * Per-step departees and regrid-time leftovers from disappeared finer
431  * levels are folded into the same per-level tag-normalizing sweep. */
432  void SplitMergeAtLevelBoundary () override;
433 
434  /*! \brief Regrid-time merge in cells that lost fine-level coverage.
435  * Reduces super-droplet count to `np_bin / merge_factor` so the
436  * coarse-level density is restored after de-refinement. */
437  void MergeParticlesAtDerefinement ( int a_lev,
438  const amrex::BoxArray& a_old_fine_ba,
439  const amrex::IntVect& a_ref_ratio ) override;
440 
441  /*! \brief Whether split/merge across AMR levels is enabled. */
442  bool splitMergeAMR () const { return m_split_merge_amr; }
443 
444  protected:
445 
446  SDCoalescenceKernelType m_coalescence_kernel; /*!< Coalescence kernel */
447  amrex::Real m_ice_agg_eff; /*!< Ice-ice aggregation (collection) efficiency */
448  bool m_include_brownian_coalescence; /*!< Include Brownian coalescence? */
449  SDKernelRelativeVelocityType m_kernel_relative_velocity; /*!< Kernel relative velocity type */
450 
451  SDTerminalVelocityType m_term_vel_type_w; /*!< Terminal velocity model for water droplets */
452  SDTerminalVelocityType m_term_vel_type_i; /*!< Terminal velocity model for ice particles */
453 
454  int m_num_sd_per_cell; /*!< Number of super-droplets per cell */
455  bool m_density_scaling; /*!< Scale initial number density with air density */
456  bool m_nucleate_particles; /*!< nucleate new superdroplets from vapor */
457  bool m_prescribed_advection; /*!< move particles with prescribed vertical velocity */
458  amrex::Real m_prescribed_w = 0.0; /*!< constant prescribed updraft [m/s]; 0 -> sinusoidal pulse */
459  bool m_split_merge_amr = false; /*!< split/merge particles across AMR level boundaries */
460  bool m_variable_dz = false; /*!< cells differ in physical thickness (stretched or terrain-fitted mesh) */
461 
462  int m_num_species; /*!< Number of vapor/condensate species */
463  std::vector<std::unique_ptr<MaterialProperties>> m_species_mat; /*!< Vapor/condensate material */
464  int m_num_aerosols; /*!< Number of aerosols */
465  std::vector<std::unique_ptr<MaterialProperties>> m_aerosol_mat; /*!< Aerosol materials */
466 
467  /* Mass change equation Newton solver parameters */
468  amrex::Real m_newton_rtol; /*!< Newton solver - relative tolerance */
469  amrex::Real m_newton_atol; /*!< Newton solver - absolute tolerance */
470  amrex::Real m_newton_stol; /*!< Newton solver - step tolerance */
471  int m_newton_maxits; /*!< Newton solver - maximum iterations */
472 
473  /* Mass change equation (un)convergence logs */
474  bool m_mass_change_logging; /*!< Whether to log unconverged particles */
475  FILE* m_mass_change_log; /*!< File handle for log with unconverged info */
476  std::string m_mass_change_log_fname; /*!< Name of unconverged info log file */
477 
478  amrex::Real m_mass_change_cfl; /*!< CFL for phase change equation */
479  SDMassChangeTIMethod m_mass_change_ti; /*!< time integrator for mass change ODE */
480  long m_num_unconverged_particles; /*!< total number of unconverged particles */
481 
482  /* Ventilation factor for phase change (water species) */
483  bool m_mass_change_ventilation; /*!< include ventilation factor in phase change */
484  amrex::Real m_vent_alpha1; /*!< ventilation factor fit coefficient alpha_1 */
485  amrex::Real m_vent_beta1; /*!< ventilation factor fit exponent beta_1 */
486  amrex::Real m_vent_alpha2; /*!< ventilation factor fit coefficient alpha_2 */
487  amrex::Real m_vent_beta2; /*!< ventilation factor fit exponent beta_2 */
488  amrex::Real m_vent_fcap; /*!< maximum ventilation factor */
489 
490  amrex::IntVect m_coalescence_bin_size; /*!< bin size for coalescence */
491 
492  int m_distribution_grid_size; /*!< Size of 1D grid to compute distributions on */
493 
494  amrex::MultiFab m_mf_buf;
495 
496 #ifdef ERF_USE_ML_UPHYS_DIAGNOSTICS
497  amrex::Real m_bindist_rmin; /*!< min radius for binned distribution */
498  amrex::Real m_bindist_rmax; /*!< max radius for binned distribution */
499 
500  /*! Cell-wise mass distribution */
501  amrex::MultiFab m_mass_ln_R_mf;
502  /*! Cell-wise number distribution */
503  amrex::MultiFab m_num_ln_R_mf;
504 #endif
505 
506  /*! maximum coalescence time scale */
507  amrex::Real m_t_coalescence;
508 
509  /*! Initialization parameters objects */
510  int m_num_initializations = 1;
511  /*! vector of initializations */
512  std::vector< std::unique_ptr<SDInitialization> > m_initializations;
513 
514  /*! Injection parameters objects */
515  int m_num_injections = 0;
516  /*! vector of injections */
517  std::vector< std::unique_ptr<SDInjection> > m_injections;
518 
519  /*! sigma_0 parameter for mass distribution calculation */
520  amrex::Real m_sigma0;
521 
522  /*! place the initial SDs randomly within cells */
523  bool m_place_randomly_in_cells;
524 
525  /*! random engine */
526  std::mt19937 m_rndeng;
527 
528  /*! species index of water */
529  int m_idx_w = -1;
530 
531  /*! species index of ice */
532  int m_idx_i = -1;
533 
534  /*! inactive particles threshold */
535  amrex::Real m_deac_threshold;
536 
537  /*! save inactive particles to file */
538  bool m_save_inactive;
539 
540  /*! Persistent device vectors for material properties */
541  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_sp_density; // Species densities
542  amrex::Gpu::DeviceVector<int> m_sp_solubility; // Species solubilities
543  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_sp_ionization; // Species ionization
544  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_sp_mol_weight; // Species molecular weight
545  amrex::Gpu::DeviceVector<int> m_sp_is_INP; // Species ice nucleating particle flags
546 
547  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_ae_density; // Aerosol densities
548  amrex::Gpu::DeviceVector<int> m_ae_solubility; // Aerosol solubilities
549  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_ae_ionization; // Aerosol ionization
550  amrex::Gpu::DeviceVector<amrex::ParticleReal> m_ae_mol_weight; // Aerosol molecular weight
551  amrex::Gpu::DeviceVector<int> m_ae_is_INP; // Aerosol ice nucleating particle flags
552 
553  /*! Flag to track if device properties are initialized */
554  bool m_device_props_initialized = false;
555 
556  /* recycled particle position bounds */
557  amrex::Real m_recyc_xmin;
558  amrex::Real m_recyc_xmax;
559  amrex::Real m_recyc_ymin;
560  amrex::Real m_recyc_ymax;
561  amrex::Real m_recyc_zmin;
562  amrex::Real m_recyc_zmax;
563 
564  /*! Method to initialize device properties */
565  void initializeDeviceProperties ();
566 
567  /*! \brief Build ProcessContext with geometry and species info */
568  SDProcess::ProcessContext buildProcessContext (int a_lev) const
569  {
570  SDProcess::ProcessContext ctx;
571  const amrex::Geometry& geom = m_gdb->Geom(a_lev);
572  ctx.plo = geom.ProbLoArray();
573  ctx.phi = geom.ProbHiArray();
574  ctx.dxi = geom.InvCellSizeArray();
575  ctx.dx = geom.CellSizeArray();
576  ctx.domain = geom.Domain();
577  for (int d = 0; d < AMREX_SPACEDIM; d++) {
578  ctx.is_periodic[d] = geom.isPeriodic(d) ? 1 : 0;
579  }
580  const auto cell_size = geom.CellSize();
581  ctx.cell_volume = AMREX_D_TERM(cell_size[0], *cell_size[1], *cell_size[2]);
582  ctx.num_species = m_num_species;
583  ctx.num_aerosols = m_num_aerosols;
584  ctx.idx_water = m_idx_w;
585  ctx.idx_ice = m_idx_i;
586  ctx.rho_water = m_species_mat[m_idx_w]->m_density;
587  if (m_idx_i >= 0) {
588  ctx.rho_ice = m_species_mat[m_idx_i]->m_density;
589  }
590  return ctx;
591  }
592 
593  /*! \brief Setup particle attribute pointers for a tile */
594  template<typename SOAType, typename AOSType>
595  void setupParticlePointers (
596  SOAType& soa,
597  AOSType& aos,
598  SDProcess::ParticlePointers& ptrs) const
599  {
600  using namespace SDPCDefn;
601 
602  constexpr int rtoff_i = SuperDropletsIntIdx::ncomps;
603  constexpr int rtoff_r = SuperDropletsRealIdx::ncomps;
604 
605  ptrs.num_particles = aos.numParticles();
606  ptrs.mass_ptr = soa.GetRealData(SuperDropletsRealIdx::mass).data();
607  ptrs.radius_ptr = soa.GetRealData(rtoff_r + SuperDropletsRealIdxSoA_RT::radius).data();
608  ptrs.active_ptr = soa.GetIntData(rtoff_i + SuperDropletsIntIdxSoA_RT::active).data();
609  ptrs.v_ptr[0] = soa.GetRealData(SuperDropletsRealIdx::vx).data();
610  ptrs.v_ptr[1] = soa.GetRealData(SuperDropletsRealIdx::vy).data();
611  ptrs.v_ptr[2] = soa.GetRealData(SuperDropletsRealIdx::vz).data();
612  ptrs.vterm_ptr = soa.GetRealData(rtoff_r + SuperDropletsRealIdxSoA_RT::term_vel).data();
613  ptrs.mult_ptr = soa.GetRealData(rtoff_r + SuperDropletsRealIdxSoA_RT::multiplicity).data();
614  // Always set ice-related pointers: SoA always has these comps; water-only coalescence uses Tfz_ptr
615  ptrs.Tfz_ptr = soa.GetRealData(idx_ice_Tfz(m_num_aerosols, m_num_species)).data();
616  ptrs.a_ptr = soa.GetRealData(idx_ice_a(m_num_aerosols, m_num_species)).data();
617  ptrs.c_ptr = soa.GetRealData(idx_ice_c(m_num_aerosols, m_num_species)).data();
618  ptrs.mrime_ptr = soa.GetRealData(idx_ice_mrime(m_num_aerosols, m_num_species)).data();
619  ptrs.nmono_ptr = soa.GetRealData(idx_ice_nmono(m_num_aerosols, m_num_species)).data();
620  setupMassPointers(soa, ptrs.sp_mass_ptrs, ptrs.ae_mass_ptrs);
621  if (!m_device_props_initialized) {
622  const_cast<SuperDropletPC*>(this)->initializeDeviceProperties();
623  }
624  ptrs.sp_rho_arr = m_sp_density.data();
625  ptrs.sp_sol_arr = m_sp_solubility.data();
626  ptrs.sp_ion_arr = m_sp_ionization.data();
627  ptrs.sp_mw_arr = m_sp_mol_weight.data();
628  ptrs.sp_INP_arr = m_sp_is_INP.data();
629  ptrs.ae_rho_arr = m_ae_density.data();
630  ptrs.ae_sol_arr = m_ae_solubility.data();
631  ptrs.ae_ion_arr = m_ae_ionization.data();
632  ptrs.ae_mw_arr = m_ae_mol_weight.data();
633  ptrs.ae_INP_arr = m_ae_is_INP.data();
634  }
635 
636  /*! \brief Common body for forEachParticleTile iterations */
637  template<typename TileFunc>
638  void forEachParticleTileBody (
639  ParIterType& pti, int a_lev,
640  const SDProcess::ProcessContext& ctx,
641  TileFunc&& func)
642  {
643  int grid = pti.index();
644  auto& ptile = ParticlesAt(a_lev, pti);
645  auto& aos = ptile.GetArrayOfStructs();
646  auto& soa = ptile.GetStructOfArrays();
647  if (aos.numParticles() == 0) { return; }
648  auto* p_pbox = aos().data();
649  SDProcess::ParticlePointers ptrs;
650  setupParticlePointers(soa, aos, ptrs);
651  func(pti, grid, p_pbox, ptrs, ctx);
652  }
653 
654  /*! \brief Iterate over particle tiles with common setup (parallel) */
655  template<typename TileFunc>
656  AMREX_FORCE_INLINE
657  void forEachParticleTile (
658  int a_lev,
659  const SDProcess::ProcessContext& ctx,
660  TileFunc&& func)
661  {
662 #ifdef AMREX_USE_OMP
663 #pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
664 #endif
665  for (ParIterType pti(*this, a_lev); pti.isValid(); ++pti) {
666  forEachParticleTileBody(pti, a_lev, ctx, std::forward<TileFunc>(func));
667  }
668  }
669 
670  /*! \brief Iterate over particle tiles WITHOUT OpenMP (serial)
671  * Use when per-tile operations are not thread-safe (e.g., DenseBins).
672  */
673  template<typename TileFunc>
674  AMREX_FORCE_INLINE
675  void forEachParticleTileSerial (int a_lev, const SDProcess::ProcessContext& ctx, TileFunc&& func)
676  {
677  for (ParIterType pti(*this, a_lev); pti.isValid(); ++pti) {
678  forEachParticleTileBody(pti, a_lev, ctx, std::forward<TileFunc>(func));
679  }
680  }
681 
682  /*! \brief Lightweight iteration (no ProcessContext) */
683  template<typename TileFunc>
684  void forEachParticleTile (int a_lev, TileFunc&& func)
685  {
686 #ifdef AMREX_USE_OMP
687 #pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
688 #endif
689  for (ParIterType pti(*this, a_lev); pti.isValid(); ++pti) {
690  int grid = pti.index();
691  auto& ptile = ParticlesAt(a_lev, pti);
692  auto& aos = ptile.GetArrayOfStructs();
693  auto& soa = ptile.GetStructOfArrays();
694  const int num_particles = aos.numParticles();
695  if (num_particles == 0) { continue; }
696  auto* p_pbox = aos().data();
697  SDProcess::ParticlePointers ptrs;
698  setupParticlePointers(soa, aos, ptrs);
699  func(pti, grid, p_pbox, ptrs, num_particles);
700  }
701  }
702 
703  /*! \brief read inputs from file */
704  virtual void readInputs () override
705  {
706  amrex::Abort("SuperDropletPC::readInputs(): Do not use this interface.");
707  }
708 
709  /*! \brief read inputs from file */
710  virtual void readInputs (const double);
711 
712  /*! \brief Particle initialization - null (no particles are initialized) */
713  void initializeParticlesNull (const MFPtr&) { }
714 
715  private:
716 
717  /*! \brief define super-droplets */
718  void define ( const std::vector<Species::Name>&,
719  const std::vector<Species::Name>&,
720  const amrex::BoxArray&,
721  const amrex::DistributionMapping&,
722  const double );
723 
724  /*! \brief add super-droplet method-specific particle attributes */
725  void add_superdroplet_attributes ();
726 
727 };
728 
729 #endif
730 #endif
int m_num_species
Definition: ERF_InitCustomPert_MultiSpeciesBubble.H:32
Dimensionless numeric literals and pure mathematical constants.
std::string name
Definition: ERF_Plotfile2DCatalog.cpp:139
Common data structures for SuperDroplet physical processes.
Super-droplets initial properties.
Definition: ERF_SDInitialization.H:333
Definition: ERF_MaterialProperties.H:179