ERF
Energy Research and Forecasting: An Atmospheric Modeling Code
ERF_NCWpsFile.H
Go to the documentation of this file.
1 /**
2  * \file ERF_NCWpsFile.H
3  */
4 #ifndef ERF_NCWPSFILE_H_
5 #define ERF_NCWPSFILE_H_
6 
7 #include <sstream>
8 #include <string>
9 #include <atomic>
10 
11 #include "AMReX_FArrayBox.H"
12 #include "AMReX_IArrayBox.H"
13 #include "ERF_EpochTime.H"
14 #include "ERF_NCInterface.H"
15 
16 using PlaneVector = amrex::Vector<amrex::FArrayBox>;
17 
18 /*
19  // Read from metgrid
20  NetCDF variables of dimensions Time_BT_SN_WE: "UU", "VV", "TT", "RH", "PRES", "GHT"
21  NetCDF variables of dimensions Time_SN_WE : "HGT", "MAPFAC_U", "MAPFAC_V", "MAPFAC_M", "PSFC"
22  NetCDF global attributes of type int : "WEST-EAST_GRID_DIMENSION", "SOUTH-NORTH_GRID_DIMENSION"
23  NetCDF global attributes of type string : "SIMULATION_START_DATE"
24  NetCDF global attributes of type real : "DX", "DY"
25 
26  // Read from wrfbdy
27  NetCDF variables of dimensions Time_BdyWidth_BT_SN : "U_BXS", "U_BXE", "V_BXS", "V_BXE" etc.
28  NetCDF variables of dimensions Time_BdyWidth_BT_WE : "U_BYS", "U_BYE", "V_BYS", "V_BYE" etc.
29  NetCDF variables of dimensions Time_BdyWidth_SN : "MU_BXS", "MU_BXE", "PC_BXS", "PC_BXE", etc.
30  NetCDF variables of dimensions Time_BdyWidth_WE : "MU_BYS", "MU_BYE", "PC_BYS", "PC_BYE", etc.
31 */
32 enum class NC_Data_Dims_Type {
33  Time_SL_SN_WE, // Time, Soil Layers, South-North, West-East
35  Time_SN_WE,
36  Time_BT,
37  Time_SL, // Time, Soil layers
38  Time,
43 };
44 
45 //
46 // NDArray is the datatype designed to hold any data, including scalars, multidimensional
47 // arrays, that read from the NetCDF file.
48 //
49 // The data read from NetCDF file are stored in a continuous memory, and the data layout is described
50 // by using a vector (shape). AMReX Box can be constructed using the data shape information, and MultiFab
51 // data array can be setup using the data that stored in the NDArray.
52 //
53 template <typename DataType>
54 struct NDArray
55 {
56  using DType = typename std::remove_const<DataType>::type;
57 
58  // constructor
59  explicit NDArray (const std::string vname, const std::vector<size_t>& vshape)
60  : name{vname}, shape{vshape},
61  data{std::shared_ptr<DType[]>(new DType[this->ndim()],
62  std::default_delete<DType[]>())} {}
63 
64  // default constructor
65  NDArray () : name{"null"}, data{nullptr} {}
66 
67  // get the data pointer
68  decltype(auto) get_data () {
69  return data.get();
70  }
71 
72  // get the variable name
73  std::string get_vname () {
74  return name;
75  }
76 
77  // get the variable data shape
78  std::vector<size_t> get_vshape () {
79  return shape;
80  }
81 
82  // return the total number of data
83  size_t ndim () {
84  size_t num = 1;
85  int isize = static_cast<int>(shape.size());
86  for (auto i=0; i<isize; ++i) num *= shape[i];
87  return num;
88  }
89 
90  // set the data shape information
91  void set_vshape (std::vector<size_t> vshape) {
92  shape = vshape;
93  }
94 
95  private:
96  std::string name;
97  std::vector<size_t> shape;
98  std::shared_ptr<DType[]> data;
99 };
100 
101 int BuildFABsFromWRFBdyFile (const std::string &fname,
102  amrex::Vector<amrex::Vector<amrex::FArrayBox>>& bdy_data_xlo,
103  amrex::Vector<amrex::Vector<amrex::FArrayBox>>& bdy_data_xhi,
104  amrex::Vector<amrex::Vector<amrex::FArrayBox>>& bdy_data_ylo,
105  amrex::Vector<amrex::Vector<amrex::FArrayBox>>& bdy_data_yhi);
106 
107 template<typename DType>
108 void ReadTimeSliceFromNetCDFFile (const std::string& fname,
109  const int tidx,
110  amrex::Vector<std::string> names,
111  amrex::Vector<NDArray<DType> >& arrays,
112  amrex::Vector<int>& success)
113 {
114  amrex::Print() << "Reading time slice " << tidx << " from " << fname << std::endl;
115  AMREX_ASSERT(arrays.size() == names.size());
116 
117  if (amrex::ParallelDescriptor::IOProcessor())
118  {
119  auto ncf = ncutils::NCFile::open(fname, NC_CLOBBER | NC_NETCDF4);
120 
121  int ntimes = ncf.dim("Time").len();
122  AMREX_ALWAYS_ASSERT((tidx >= 0) && (tidx < ntimes));
123 
124  for (auto n=0; n<arrays.size(); ++n)
125  {
126  std::string vname_to_write = names[n];
127  std::string vname_to_read = names[n];
128  if (vname_to_read.substr(0,2) == "R_") {
129  vname_to_read = names[n+4]; // This allows us to read "T" instead -- we will over-write this later
130  }
131 
132  success[n] = ncf.has_var(vname_to_read);
133 
134  if (success[n] == 1)
135  {
136  std::vector<std::string> dimnames = ncf.var(vname_to_read).dimnames();
137  AMREX_ALWAYS_ASSERT(dimnames[0] == "Time");
138 
139  std::vector<size_t> count = ncf.var(vname_to_read).shape();
140  std::vector<size_t> start(count.size(), 0);
141  start[0] = tidx;
142  count[0] = 1;
143 
144  arrays[n] = NDArray<DType>(vname_to_read, count);
145  DType* dataPtr = arrays[n].get_data();
146 
147  ncf.var(vname_to_read).get(dataPtr, start, count);
148  } // has_var
149  }
150  ncf.close();
151  }
152 }
153 
154 template<typename DType>
155 void ReadNetCDFFile (const std::string& fname, amrex::Vector<std::string> names,
156  amrex::Vector<NDArray<DType> >& arrays, amrex::Vector<int>& success)
157 {
158  AMREX_ASSERT(arrays.size() == names.size());
159 
160  if (amrex::ParallelDescriptor::IOProcessor())
161  {
162  auto ncf = ncutils::NCFile::open(fname, NC_CLOBBER | NC_NETCDF4);
163 
164  /*
165  // get the dimension information
166  int Time = static_cast<int>(ncf.dim("Time").len());
167  int DateStrLen = static_cast<int>(ncf.dim("DateStrLen").len());
168  int west_east = static_cast<int>(ncf.dim("west_east").len());
169  int south_north = static_cast<int>(ncf.dim("south_north").len());
170  int bottom_top = static_cast<int>(ncf.dim("bottom_top").len());
171  int bottom_top_stag = static_cast<int>(ncf.dim("bottom_top_stag").len());
172  int west_east_stag = static_cast<int>(ncf.dim("west_east_stag").len());
173  int south_north_stag = static_cast<int>(ncf.dim("south_north_stag").len());
174  int bdy_width = static_cast<int>(ncf.dim("bdy_width").len());
175  */
176 
177  // amrex::Print() << "Reading the dimensions from the netcdf file " << "\n";
178 
179  for (auto n=0; n<arrays.size(); ++n)
180  {
181  std::string vname_to_write = names[n];
182  std::string vname_to_read = names[n];
183 
184  if (vname_to_read.substr(0,2) == "R_") {
185  vname_to_read = names[n+4]; // This allows us to read "T" instead -- we will over-write this later
186  }
187 
188  success[n] = ncf.has_var(vname_to_read);
189  if (success[n] == 0) {
190  amrex::Print() << " Skipping " << vname_to_read << std::endl;
191  } else {
192  amrex::Print() << " Reading " << vname_to_read << std::endl;
193  }
194 
195  if (success[n] == 1) {
196 
197  std::vector<std::string> dimnames = ncf.var(vname_to_read).dimnames();
198  AMREX_ALWAYS_ASSERT(dimnames[0] == "Time" || dimnames[0] == "time");
199 
200  std::vector<size_t> shape = ncf.var(vname_to_read).shape();
201  arrays[n] = NDArray<DType>(vname_to_read,shape);
202  DType* dataPtr = arrays[n].get_data();
203 
204  std::vector<size_t> start(shape.size(), 0);
205 
206 #if 0
207  auto numPts = arrays[n].ndim();
208  amrex::Print() << "NetCDF Variable name = " << vname_to_read << std::endl;
209  amrex::Print() << "numPts read from NetCDF file/var = " << numPts << std::endl;
210  amrex::Print() << "Dims in var = " << ncf.var(vname_to_read).ndim() << std::endl;
211  amrex::Print() << "Dim names = (";
212  for (auto &dim:dimnames)
213  amrex::Print() << dim << ", " ;
214  amrex::Print() << ")" << std::endl;
215  amrex::Print() << "Dims of the variable = (";
216  for (auto &dim:shape)
217  amrex::Print() << dim << ", " ;
218  amrex::Print() << ")" << std::endl;
219 #endif
220 
221  ncf.var(vname_to_read).get(dataPtr, start, shape);
222 
223  } // has_var
224  }
225  ncf.close();
226  }
227 }
228 
229 /**
230  * Helper function for reading data from NetCDF file into a
231  * provided FAB.
232  *
233  * @param iv Index for which variable we are going to fill
234  * @param domain Box specifying the horizontal and vertical extent to read
235  * @param nc_arrays Arrays of data from NetCDF file
236  * @param var_name Variable name
237  * @param NC_dim_type Dimension type for the variable as stored in the NetCDF file
238  * @param temp FAB where we store the variable data from the NetCDF Arrays
239  */
240 template<class FAB,typename DType>
241 void
243  const amrex::Box& domain,
244  amrex::Vector<NDArray<float>>& nc_arrays,
245  const std::string& var_name,
246  NC_Data_Dims_Type& NC_dim_type,
247  FAB& temp)
248 {
249  int ns1, ns2, ns3; // bottom_top, south_north, west_east (these can be staggered or unstaggered)
250  if (NC_dim_type == NC_Data_Dims_Type::Time_BT) {
251  ns1 = nc_arrays[iv].get_vshape()[1];
252  ns2 = 1;
253  ns3 = 1;
254  // amrex::Print() << "TYPE BT " << ns1 << std::endl;
255  } else if (NC_dim_type == NC_Data_Dims_Type::Time_SN_WE) {
256  ns1 = 1;
257  ns2 = nc_arrays[iv].get_vshape()[1];
258  ns3 = nc_arrays[iv].get_vshape()[2];
259  // amrex::Print() << "TYPE SN WE " << ns2 << " " << ns3 << std::endl;
260  } else if (NC_dim_type == NC_Data_Dims_Type::Time_BT_SN_WE) {
261  ns1 = nc_arrays[iv].get_vshape()[1];
262  ns2 = nc_arrays[iv].get_vshape()[2];
263  ns3 = nc_arrays[iv].get_vshape()[3];
264  // amrex::Print() << "TYPE BT SN WE " << ns1 << " " << ns2 << " " << ns3 << std::endl;
265  } else if (NC_dim_type == NC_Data_Dims_Type::Time_SL_SN_WE) {
266  ns1 = nc_arrays[iv].get_vshape()[1];
267  ns2 = nc_arrays[iv].get_vshape()[2];
268  ns3 = nc_arrays[iv].get_vshape()[3];
269  // amrex::Print() << "TYPE SL SN WE " << ns1 << " " << ns2 << " " << ns3 << std::endl;
270  } else if (NC_dim_type == NC_Data_Dims_Type::Time_SL) {
271  ns1 = nc_arrays[iv].get_vshape()[1];
272  ns2 = 1;
273  ns3 = 1;
274  // amrex::Print() << "TYPE SL " << ns1 << std::endl;
275  }
276  else {
277  amrex::Abort("Dont know this NC_Data_Dims_Type");
278  }
279 
280  // allow fewer z levels to be read in
281  // - ns1 may be the bottom_top or bottom_top_stag dim
282  // - domain.bigEnd(2) is the input number of cells in z
283  // - khi may be nz==bottom_top, nz < bottom_top, or 0 for 2D fields
284  int khi = std::min(domain.bigEnd(2), ns1-1);
285 
286  // TODO: The box will only start at (0,0,0) at level 0 -- we need to generalize this
287  amrex::Box in_box(amrex::IntVect(0,0,0), amrex::IntVect(ns3-1,ns2-1,ns1-1)); // ns1 may or may not be staggered
288  amrex::Box my_box(amrex::IntVect(0,0,0), amrex::IntVect(ns3-1,ns2-1,khi));
289 
290  if (var_name == "PH" || var_name == "PHB") {
291  my_box.setType(amrex::IndexType(amrex::IntVect(0,0,1)));
292  my_box.setBig(2, khi+1);
293  }
294  else if (var_name == "U" || var_name == "UU" || var_name == "MAPFAC_U") {
295  my_box.setType(amrex::IndexType(amrex::IntVect(1,0,0)));
296  }
297  else if (var_name == "V" || var_name == "VV" || var_name == "MAPFAC_V") {
298  my_box.setType(amrex::IndexType(amrex::IntVect(0,1,0)));
299  }
300  else if (var_name == "W" || var_name == "WW") {
301  my_box.setType(amrex::IndexType(amrex::IntVect(0,0,1)));
302  my_box.setBig(2, khi+1);
303  }
304  else if (var_name == "TSLB" || var_name == "SMOIS" || var_name == "SH2O" || var_name == "ZS" || var_name == "DZS") {
305  // soil variables are staggered in z
306  my_box.setType(amrex::IndexType(amrex::IntVect(0,0,1)));
307  }
308 
309  amrex::Arena* Arena_Used = amrex::The_Arena();
310 #ifdef AMREX_USE_GPU
311  // Make sure temp lives on CPU since nc_arrays lives on CPU only
312  Arena_Used = amrex::The_Pinned_Arena();
313 #endif
314  temp.resize(my_box,1, Arena_Used);
315  amrex::Array4<DType> fab_arr = temp.array();
316 
317  int ioff = temp.box().smallEnd()[0];
318  int joff = temp.box().smallEnd()[1];
319  int kmax = temp.box().bigEnd()[2]; // highest z level to be read in
320  //amrex::Print() << var_name << " domain khi, kmax, ns1 = " << khi << " " << kmax << " " << ns1 << std::endl;
321 
322  auto num_pts = in_box.numPts();
323 
324  for (int n(0); n < num_pts; ++n) {
325  int k = n / (ns2*ns3);
326  if (k > kmax) continue;
327  int j = (n - k*(ns2*ns3)) / ns3 + joff;
328  int i = n - k*(ns2*ns3) - (j-joff) * ns3 + ioff;
329  fab_arr(i,j,k,0) = static_cast<DType>(*(nc_arrays[iv].get_data()+n));
330  }
331 }
332 
333 /**
334  * Function to read NetCDF variables and fill the corresponding Array4's
335  *
336  * @param domain Box specifying the domain covered by the NetCDF fields
337  * @param fname Name of the NetCDF file to be read
338  * @param nc_var_names Variable names in the NetCDF file
339  * @param NC_dim_types NetCDF data dimension types
340  * @param fab_vars Fab data we are to fill
341  * @param success Success flags for each requested variable
342  */
343 template<class FAB,typename DType>
344 void
345 BuildFABsFromNetCDFFile (const amrex::Box& domain,
346  const std::string &fname,
347  amrex::Vector<std::string> nc_var_names,
348  amrex::Vector<enum NC_Data_Dims_Type> NC_dim_types,
349  amrex::Vector<FAB*> fab_vars,
350  amrex::Vector<int>& success)
351 {
352  int ioproc = amrex::ParallelDescriptor::IOProcessorNumber(); // I/O rank
353 
354  amrex::Vector<NDArray<float>> nc_arrays(nc_var_names.size());
355 
356  if (amrex::ParallelDescriptor::IOProcessor())
357  {
358  ReadNetCDFFile(fname, nc_var_names, nc_arrays, success);
359  }
360 
361  amrex::ParallelDescriptor::Bcast(success.dataPtr(), success.size(), ioproc);
362 
363  for (int iv = 0; iv < nc_var_names.size(); iv++)
364  {
365  if (success[iv] == 1) {
366  FAB tmp;
367  if (amrex::ParallelDescriptor::IOProcessor()) {
368  fill_fab_from_arrays<FAB,DType>(iv, domain, nc_arrays, nc_var_names[iv], NC_dim_types[iv], tmp);
369  }
370 
371  int ncomp = tmp.nComp();
372  amrex::Box box = tmp.box();
373 
374  amrex::ParallelDescriptor::Bcast(&box, 1, ioproc);
375  amrex::ParallelDescriptor::Bcast(&ncomp, 1, ioproc);
376 
377  if (!amrex::ParallelDescriptor::IOProcessor()) {
378 #ifdef AMREX_USE_GPU
379  tmp.resize(box,ncomp,amrex::The_Pinned_Arena());
380 #else
381  tmp.resize(box,ncomp);
382 #endif
383  }
384 
385  amrex::ParallelDescriptor::Bcast(tmp.dataPtr(), tmp.size(), ioproc);
386 
387  // Shift box by the domain lower corner
388  amrex::Box fab_bx = tmp.box();
389  amrex::Dim3 dom_lb = lbound(domain);
390  fab_bx += amrex::IntVect(dom_lb.x,dom_lb.y,dom_lb.z);
391  // fab_vars points to data on device
392  fab_vars[iv]->resize(fab_bx,1);
393 #ifdef AMREX_USE_GPU
394  amrex::Gpu::copy(amrex::Gpu::hostToDevice,
395  tmp.dataPtr(), tmp.dataPtr() + tmp.size(),
396  fab_vars[iv]->dataPtr());
397 #else
398  // Provided by BaseFab inheritance through FArrayBox
399  fab_vars[iv]->copy(tmp,tmp.box(),0,fab_bx,0,1);
400 #endif
401  } // success
402  } // iv
403 }
404 #endif
@ num
Definition: ERF_DataStruct.H:27
const int khi
Definition: ERF_InitCustomPert_Bubble.H:21
AMREX_ALWAYS_ASSERT(bx.length()[2]==khi+1)
Arena * Arena_Used
Definition: ERF_Morrison_Advance_F.H:23
void ReadNetCDFFile(const std::string &fname, amrex::Vector< std::string > names, amrex::Vector< NDArray< DType > > &arrays, amrex::Vector< int > &success)
Definition: ERF_NCWpsFile.H:155
NC_Data_Dims_Type
Definition: ERF_NCWpsFile.H:32
void fill_fab_from_arrays(int iv, const amrex::Box &domain, amrex::Vector< NDArray< float >> &nc_arrays, const std::string &var_name, NC_Data_Dims_Type &NC_dim_type, FAB &temp)
Definition: ERF_NCWpsFile.H:242
void BuildFABsFromNetCDFFile(const amrex::Box &domain, const std::string &fname, amrex::Vector< std::string > nc_var_names, amrex::Vector< enum NC_Data_Dims_Type > NC_dim_types, amrex::Vector< FAB * > fab_vars, amrex::Vector< int > &success)
Definition: ERF_NCWpsFile.H:345
amrex::Vector< amrex::FArrayBox > PlaneVector
Definition: ERF_NCWpsFile.H:16
int BuildFABsFromWRFBdyFile(const std::string &fname, amrex::Vector< amrex::Vector< amrex::FArrayBox >> &bdy_data_xlo, amrex::Vector< amrex::Vector< amrex::FArrayBox >> &bdy_data_xhi, amrex::Vector< amrex::Vector< amrex::FArrayBox >> &bdy_data_ylo, amrex::Vector< amrex::Vector< amrex::FArrayBox >> &bdy_data_yhi)
void ReadTimeSliceFromNetCDFFile(const std::string &fname, const int tidx, amrex::Vector< std::string > names, amrex::Vector< NDArray< DType > > &arrays, amrex::Vector< int > &success)
Definition: ERF_NCWpsFile.H:108
@ tmp
Definition: ERF_AdvanceWSM6.cpp:114
Definition: ERF_NCWpsFile.H:55
std::string name
Definition: ERF_NCWpsFile.H:96
std::shared_ptr< DType[]> data
Definition: ERF_NCWpsFile.H:98
size_t ndim()
Definition: ERF_NCWpsFile.H:83
NDArray()
Definition: ERF_NCWpsFile.H:65
std::string get_vname()
Definition: ERF_NCWpsFile.H:73
void set_vshape(std::vector< size_t > vshape)
Definition: ERF_NCWpsFile.H:91
NDArray(const std::string vname, const std::vector< size_t > &vshape)
Definition: ERF_NCWpsFile.H:59
typename std::remove_const< DataType >::type DType
Definition: ERF_NCWpsFile.H:56
std::vector< size_t > shape
Definition: ERF_NCWpsFile.H:97
decltype(auto) get_data()
Definition: ERF_NCWpsFile.H:68
std::vector< size_t > get_vshape()
Definition: ERF_NCWpsFile.H:78