REMORA
Regional Modeling of Oceans Refined Adaptively
Loading...
Searching...
No Matches
REMORA_NCTimeSeries.cpp
Go to the documentation of this file.
1#include "REMORA_Constants.H"
3#include "REMORA_NCFile.H"
4
5#include "AMReX_FillPatchUtil.H"
6#include "AMReX_Interpolater.H"
7#include "AMReX_ParallelDescriptor.H"
8
9#include <string>
10
11#ifdef REMORA_USE_NETCDF
12/**
13 * @param[in ] a_file_names vector of file name(s) to read from
14 * @param[in ] a_field_name name of field to read in
15 * @param[in ] a_time_name name of time variable in NetCDF file
16 * @param[in ] a_domain simulation domain
17 * @param[inout] a_mf_var MultiFab of data to either store into or reference for dimensions
18 * @param[in ] a_is2d Whether the variable we're working with is 2D
19 * @param[in ] a_save_interpolated Whether the interpolated value should be saved internally
20 */
21NCTimeSeries::NCTimeSeries (const amrex::Vector<std::string>& a_file_names, const std::string a_field_name,
22 const std::string a_time_name,
23 const amrex::Box& a_domain,
24 amrex::MultiFab* a_mf_var, bool a_is2d, bool a_save_interpolated) {
25 file_names.assign(a_file_names.begin(), a_file_names.end());
26 time_name = a_time_name;
27 field_name = a_field_name;
28 domain = a_domain;
29 mf_var = a_mf_var;
30 is2d = a_is2d;
31 save_interpolated = a_save_interpolated;
32}
33
35 // open file
36 amrex::Print() << "Loading " << field_name << " from NetCDF file(s)" << std::endl;
37
38 // The time field can have any number of names, depending on the field.
39 // If not specified in input file (time_name.empty()) then set it by default
40 if (time_name.empty())
41 {
42 if (field_name.find("wind") != std::string::npos) {
43 time_name = "wind_time";
44 } else if ((field_name.find("str") != std::string::npos) and (field_name[0] == 's')) {
45 time_name = "sms_time";
46 } else if ((field_name.find("str") != std::string::npos) and (field_name[0] == 'b')) {
47 time_name = "bms_time";
48 } else {
49 time_name = "ocean_time";
50 }
51 }
52
53 for (int ifile = 0; ifile < file_names.size(); ++ifile) {
54 const std::string& file_name = file_names[ifile];
55
56 // Check units of time stamps; should be days
57 std::string unit_str = ReadNetCDFVarAttrStr(file_name, time_name, "units"); // works on proc 0
58 if (amrex::ParallelDescriptor::IOProcessor())
59 {
60 if (unit_str.find("days") == std::string::npos) {
61 amrex::Print() << "Units of ocean_time given as: " << unit_str << std::endl;
62 amrex::Abort("Units must be in days.");
63 }
64 }
65
66 // get times and put in array
67 using RARRAY = NDArray<amrex::Real>;
68 amrex::Vector<RARRAY> array_ts(1);
69 ReadNetCDFFile(file_name, {time_name}, array_ts); // filled only on proc 0
70 if (amrex::ParallelDescriptor::IOProcessor())
71 {
72 int ntimes_io = array_ts[0].get_vshape()[0];
73 for (int nt(0); nt < ntimes_io; nt++)
74 {
75 // Convert ocean time from days to seconds
76 ocean_times.push_back((*(array_ts[0].get_data() + nt)) * amrex::Real(60.0) * amrex::Real(60.0) * amrex::Real(24.0));
77 file_for_time.push_back(ifile);
78 file_itime_offset.push_back(nt);
79 }
80 }
81 }
82 int ntimes = ocean_times.size();
83 // Only do checks on IO processor since ocean_times isn't populated on other ranks yet
84 if (amrex::ParallelDescriptor::IOProcessor()) {
85 AMREX_ASSERT(std::is_sorted(ocean_times.begin(), ocean_times.end()));
86 if (ntimes <= 1) {
87 amrex::Error("Time series data must be given at at least two times");
88 }
89 }
90 int ioproc = amrex::ParallelDescriptor::IOProcessorNumber();
91 amrex::ParallelDescriptor::Bcast(&ntimes,1,ioproc);
92 if (!(amrex::ParallelDescriptor::IOProcessor())) {
93 ocean_times.resize(ntimes);
94 file_for_time.resize(ntimes);
95 file_itime_offset.resize(ntimes);
96 }
97 amrex::ParallelDescriptor::Bcast(ocean_times.data(), ocean_times.size(), ioproc);
98 amrex::ParallelDescriptor::Bcast(file_for_time.data(), file_for_time.size(), ioproc);
99 amrex::ParallelDescriptor::Bcast(file_itime_offset.data(), file_itime_offset.size(), ioproc);
100
101 // Initialize MultiFabs
102 // NetCDF data is always read and temporally interpolated on level 0.
103 mf_before = new amrex::MultiFab(mf_var->boxArray(), mf_var->DistributionMap(), 1, mf_var->nGrowVect());
104 mf_after = new amrex::MultiFab(mf_var->boxArray(), mf_var->DistributionMap(), 1, mf_var->nGrowVect());
105 mf_interp_lev0 = new amrex::MultiFab(mf_var->boxArray(), mf_var->DistributionMap(), 1, mf_var->nGrowVect());
106
107 // dummy initialization
108 i_time_before = -100;
109}
110
111/**
112 * @param time time to interpolate to
113 */
115 amrex::MultiFab* mf_lev,
116 const amrex::Vector<amrex::Geometry>& geom,
117 const amrex::Vector<amrex::IntVect>& ref_ratio) {
118 // Figure out time index:
119 AMREX_ASSERT(time >= ocean_times[0]);
120 AMREX_ASSERT(time <= ocean_times[ocean_times.size()-1]);
121 int i_time_before_old = i_time_before;
122 for (int nt=0; nt < ocean_times.size()-1; nt++) {
123 if ((ocean_times[nt] <= time) and (ocean_times[nt+1] >= time)) {
124 i_time_before = nt;
126 time_after = ocean_times[nt+1];
127 break;
128 }
129 }
130
131 int i_time_after = i_time_before + 1;
132 if (i_time_before_old + 1 == i_time_before) {
133 // swap multifabs so we only have to read in one MultiFab
134 std::swap(mf_before, mf_after);
135 read_in_at_time(mf_after, i_time_after);
136 } else if (i_time_before_old != i_time_before) {
137 read_in_at_time(mf_after, i_time_after);
139 }
140
141 amrex::Real dt = time_after - time_before;
142
143 auto nodality = mf_interp_lev0->ixType();
144
145#ifdef AMREX_USE_OMP
146#pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
147#endif
148 for (amrex::MFIter mfi(*mf_interp_lev0,true); mfi.isValid(); ++mfi) {
149 // Adjust box to match ROMS grid
150 amrex::Box bx = mfi.growntilebox(amrex::IntVect(1-nodality[0],1-nodality[1],0));
151
152 amrex::Real time_before_copy = time_before;
153
154 // Temporal interpolation is done once on level 0.
155 amrex::MultiFab* mf_to_fill = mf_interp_lev0;
156 amrex::Array4<amrex::Real> to_fill = mf_to_fill->array(mfi);
157 amrex::Array4<const amrex::Real> before = mf_before->const_array(mfi);
158 amrex::Array4<const amrex::Real> after = mf_after->const_array(mfi);
159 amrex::ParallelFor(bx, [=] AMREX_GPU_DEVICE (int i, int j, int k)
160 {
161 to_fill(i,j,k) = before(i,j,k) + (time - time_before_copy) * (after(i,j,k) - before(i,j,k)) / dt;
162 });
163 }
164
165 amrex::MultiFab* mf_to_fill_lev = mf_lev;
166 if (save_interpolated) {
167 if (mf_interpolated_lev.size() <= static_cast<amrex::Long>(lev)) {
168 mf_interpolated_lev.resize(lev+1);
169 }
170 if (!mf_interpolated_lev[lev] ||
171 mf_interpolated_lev[lev]->boxArray() != mf_lev->boxArray() ||
172 mf_interpolated_lev[lev]->nGrowVect() != mf_lev->nGrowVect()) {
173 mf_interpolated_lev[lev] = std::make_unique<amrex::MultiFab>(
174 mf_lev->boxArray(), mf_lev->DistributionMap(), 1, mf_lev->nGrowVect());
175 }
176 mf_to_fill_lev = mf_interpolated_lev[lev].get();
177 }
178
179 if (lev == 0) {
180 amrex::MultiFab::Copy(*mf_to_fill_lev, *mf_interp_lev0, 0, 0, 1, mf_to_fill_lev->nGrowVect());
181 return;
182 }
183
184 amrex::PhysBCFunctNoOp null_bc_for_fill;
185 amrex::Vector<amrex::BCRec> null_dom_bcs(1);
186 for (int dir = 0; dir < AMREX_SPACEDIM; ++dir) {
187 null_dom_bcs[0].setLo(dir, amrex::BCType::int_dir);
188 null_dom_bcs[0].setHi(dir, amrex::BCType::int_dir);
189 }
190
191 amrex::Interpolater* mapper = nullptr;
192 const auto& idx_type = mf_to_fill_lev->ixType();
193 if (idx_type == amrex::IndexType(amrex::IntVect(0,0,0))) {
194 mapper = &amrex::cell_cons_interp;
195 } else {
196 mapper = &amrex::face_cons_linear_interp;
197 }
198
199 amrex::InterpFromCoarseLevel(*mf_to_fill_lev, zero, *mf_interp_lev0,
200 0, 0, 1,
201 geom[0], geom[lev],
203 cumulative_ref_ratio(lev, ref_ratio),
204 mapper, null_dom_bcs, 0);
205
206 mf_to_fill_lev->FillBoundary(geom[lev].periodicity());
207}
208
209amrex::IntVect
211 const amrex::Vector<amrex::IntVect>& ref_ratio) const {
212 amrex::IntVect rr(1,1,1);
213 for (int l = 0; l < lev; ++l) {
214 rr[0] *= ref_ratio[l][0];
215 rr[1] *= ref_ratio[l][1];
216 rr[2] *= ref_ratio[l][2];
217 }
218 return rr;
219}
220
221const amrex::MultiFab*
228
229/**
230 * @param[inout] mf multifab to store time step data into
231 * @param[in ] itime index of time step to read from file
232 */
233void NCTimeSeries::read_in_at_time (amrex::MultiFab* mf, int itime) {
234 // This all assumes that we're on level 0 with only one boxes_at_level
235 amrex::FArrayBox NC_fab;
236 amrex::Vector<amrex::FArrayBox*> NC_fabs;
237 amrex::Vector<std::string> NC_names;
238 amrex::Vector<enum NC_Data_Dims_Type> NC_dim_types;
239
240 const std::string& file_name = file_names[file_for_time[itime]];
241 const int itime_offset = file_itime_offset[itime];
242
243 amrex::Print() << "Reading in " << field_name << " at time index " << itime
244 << " from " << file_name << std::endl;
245
246 NC_fabs.push_back(&NC_fab) ; NC_names.push_back(field_name);
247
248 if (is2d) {
249 NC_dim_types.push_back(NC_Data_Dims_Type::Time_SN_WE);
250 } else {
251 NC_dim_types.push_back(NC_Data_Dims_Type::Time_BT_SN_WE);
252 }
253
254 BuildFABsFromNetCDFFile<amrex::FArrayBox,amrex::Real>(domain, file_name, NC_names, NC_dim_types,
255 NC_fabs, true, itime_offset);
256
257#ifdef _OPENMP
258#pragma omp parallel if (amrex::Gpu::notInLaunchRegion())
259#endif
260 {
261 // Don't tile this since we are operating on full FABs in this routine
262 for ( amrex::MFIter mfi(*mf, false); mfi.isValid(); ++mfi )
263 {
264 amrex::FArrayBox &fab = (*mf)[mfi];
265
266 //
267 // FArrayBox to FArrayBox copy does "copy on intersection"
268 // This only works here because we have broadcast the FArrayBox of data from the netcdf file to all ranks
269
270 fab.template copy<amrex::RunOn::Device>(NC_fab);
271 } // mf
272 } // omp
273}
274#endif // REMORA_USE_NETCDF
constexpr amrex::Real zero
AMREX_ALWAYS_ASSERT(!NSPeriodic||!EWPeriodic)
void ReadNetCDFFile(const std::string &fname, amrex::Vector< std::string > names, amrex::Vector< NDArray< DType > > &arrays, bool one_time=false, int fill_time=0)
Read in data from netcdf file and save to data arrays.
std::string ReadNetCDFVarAttrStr(const std::string &fname, const std::string &var_name, const std::string &attr_name)
Helper function for reading a single variable attribute.
static PhysBCFunctNoOp null_bc_for_fill
amrex::Vector< std::unique_ptr< amrex::MultiFab > > mf_interpolated_lev
Interpolated data on each requested AMR level if save_interpolated=true.
bool is2d
Whether the field we're reading in is 2d.
void update_interpolated_to_time(amrex::Real time, int lev, amrex::MultiFab *mf_lev, const amrex::Vector< amrex::Geometry > &geom, const amrex::Vector< amrex::IntVect > &ref_ratio)
Calculate interpolated values at time and fill data for level lev.
void read_in_at_time(amrex::MultiFab *mf, int itime)
Read in data from file at time index itime and fill into mf.
amrex::Vector< int > file_itime_offset
Offset to access a particular time within its file.
amrex::MultiFab * mf_interp_lev0
Multifab storing temporally interpolated data on level 0.
amrex::Real time_after
Time in ocean_times immediately after the last time interpolated to.
amrex::Real time_before
Time in ocean_times immediately before the last time interpolated to.
amrex::Box domain
Domain.
void Initialize()
Read in time array from file and allocate data arrays.
amrex::MultiFab * mf_before
Multifab to store data at time_before.
int i_time_before
Time index immediately before the last time interpolated to.
std::string field_name
Field name in netcdf file.
amrex::IntVect cumulative_ref_ratio(int lev, const amrex::Vector< amrex::IntVect > &ref_ratio) const
Build cumulative refinement ratio from level 0 to lev.
NCTimeSeries(const amrex::Vector< std::string > &a_file_names, const std::string a_field_name, const std::string a_time_name, const amrex::Box &a_domain, amrex::MultiFab *a_mf_var, bool a_is2d, bool a_save_interpolated)
Constructor.
amrex::Vector< std::string > file_names
File names to read from.
amrex::MultiFab * mf_after
Multifab to store data at time_after.
std::string time_name
Field name for time series in netcdf file.
amrex::Vector< int > file_for_time
File index to access a particular time.
const amrex::MultiFab * get_interpolated_mf(int lev) const
Access interpolated data saved for a specific level.
amrex::Vector< amrex::Real > ocean_times
Time points in netcdf file.
amrex::MultiFab * mf_var
NDArray is the datatype designed to hold any data, including scalars, multidimensional arrays,...