10#include <tclap/CmdLine.h>
37using namespace netCDF;
52 if (str ==
"x" || str ==
"exit")
57 std::size_t
const max = 0)
61 ERR(
"Input not valid.");
63 else if (error_id == 1)
65 ERR(
"Index not valid. Valid indices are in [0,{:d}].", max);
67 else if (error_id == 2)
69 ERR(
"Input not valid.");
70 std::cout <<
"Type \"info\" to display the available options again. "
71 "\"exit\" will exit the programme.\n";
75static std::size_t
parseInput(std::string
const& request_str,
76 std::size_t
const max_val,
77 bool const has_info =
false)
81 std::cout << request_str;
84 std::getline(std::cin, str);
86 if (has_info && str ==
"info")
88 std::stringstream str_stream(str);
89 if (!(str_stream >> val))
91 std::size_t
const error_val = (has_info) ? 2 : 0;
95 if (val > max_val - 1)
102 return std::numeric_limits<std::size_t>::max();
105static NcVar
getDimVar(NcFile
const& dataset, NcVar
const& var,
106 std::size_t
const dim)
108 NcDim
const& dim_obj = var.getDim(dim);
109 return dataset.getVar(dim_obj.getName());
113 std::size_t
const dim)
115 return std::make_pair(0.0,
static_cast<double>(var.getDim(dim).getSize()));
118static std::vector<std::string>
getArrays(NcFile
const& dataset)
120 auto const& names = dataset.getVars();
121 std::vector<std::string> var_names;
122 for (
auto [name, var] : names)
125 var_names.push_back(name);
132 std::size_t
const n_vars(dataset.getDimCount());
133 std::cout <<
"The NetCDF file contains the following " << n_vars
135 std::cout <<
"\tIndex\tArray Name\t#Dimensions\n";
136 std::cout <<
"-------------------------------------------\n";
137 auto const& names = dataset.getVars();
138 std::size_t count = 0;
139 for (
auto [name, var] : names)
141 std::cout <<
"\t" << count++ <<
"\t" << name <<
"\t("
142 << var.getDimCount() <<
"D array)\n";
149 std::cout <<
"Data array \"" << var.getName()
150 <<
"\" contains the following dimensions:\n";
151 std::size_t
const n_dims(var.getDimCount());
152 for (std::size_t i = 0; i < n_dims; ++i)
153 std::cout <<
"\t" << i <<
"\t" << var.getDim(i).getName() <<
"\t("
154 << var.getDim(i).getSize() <<
" values)\n";
160 if (var.getDimCount() == 1)
163 std::size_t
const size = var.getDim(0).getSize();
164 var.getVar({0}, {1}, &start);
165 var.getVar({size - 1}, {1}, &end);
166 return std::make_pair(start, end);
168 return std::make_pair(0, 0);
172 std::vector<std::size_t>
const& dim_idx_map,
173 std::size_t
const time_offset)
176 std::size_t
const n_dims = var.getDimCount();
177 for (std::size_t i = time_offset; i < n_dims; ++i)
179 NcVar
const& dim =
getDimVar(dataset, var, dim_idx_map[i]);
180 auto const bounds = (dim.isNull()) ?
getDimLength(var, dim_idx_map[i])
182 origin[i - time_offset] =
183 (bounds.first < bounds.second) ? bounds.first : bounds.second;
188static void flipRaster(std::vector<double>& data, std::size_t
const layers,
189 std::size_t
const width, std::size_t
const height)
191 std::size_t
const length(data.size());
192 std::vector<double> tmp_vec;
193 tmp_vec.reserve(length);
194 for (std::size_t k = 0; k < layers; k++)
196 std::size_t
const layer_end = (k + 1) * height * width;
197 for (std::size_t i = 0; i < height; i++)
199 std::size_t
const line_idx(layer_end - (width * (i + 1)));
200 for (std::size_t j = 0; j < width; j++)
202 tmp_vec.push_back(data[line_idx + j]);
206 std::copy(tmp_vec.cbegin(), tmp_vec.cend(), data.begin());
211 bool ret(var.getDimCount() < 2);
213 ERR(
"Only 2+ dimensional variables can be converted into OGS "
220 std::vector<std::string>
const& names =
getArrays(dataset);
222 std::size_t
const idx =
223 parseInput(
"Enter data array index: ", dataset.getVarCount(),
true);
225 if (
static_cast<int>(idx) == dataset.getVarCount() ||
233 std::vector<std::size_t>& dim_idx_map)
236 std::size_t
const n_dims(var.getDimCount());
237 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
238 bool is_time_dep(
true);
243 std::string temp_str(
"");
244 cout <<
"Is the parameter time-dependent?\n";
245 while (dim_idx_map[0] == std::numeric_limits<std::size_t>::max() &&
248 cout <<
"Enter ID for temporal dimension or \"c\" to continue: ";
249 std::getline(std::cin, temp_str);
250 std::stringstream str_stream(temp_str);
251 if (str_stream.str() ==
"c" || str_stream.str() ==
"continue")
255 if (!(str_stream >> dim_idx_map[0]))
258 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
261 if (dim_idx_map[0] > n_dims - 1)
264 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
273 std::size_t
const start_idx = (is_time_dep) ? 1 : 0;
274 std::array<std::string, 4>
const dim_comment{
275 "(x / longitude)",
"(y / latitude)",
"(z / height / depth)",
276 "[Error: 4-dimensional non-temporal arrays are not supported]"};
277 for (std::size_t i = start_idx; i < n_dims; ++i)
279 dim_idx_map[i] = std::numeric_limits<std::size_t>::max();
281 std::string
const request_str(
"Enter ID for dimension " +
282 std::to_string(i) +
" " +
283 dim_comment[i - start_idx] +
": ");
284 std::size_t
const idx =
285 parseInput(request_str, var.getDimCount(),
true);
287 if (
static_cast<int>(idx) == var.getDimCount())
293 dim_idx_map[i] = idx;
300 NcVar
const& var, std::size_t
const dim_idx)
302 std::size_t
const n_time_steps = var.getDim(dim_idx).getSize();
303 std::size_t
const max_val = std::numeric_limits<std::size_t>::max();
304 std::pair<std::size_t, std::size_t> bounds(max_val, max_val);
305 std::cout <<
"\nThe dataset contains " << n_time_steps <<
" time steps.\n";
306 while (bounds.first == max_val)
309 "Specify first time step to export: ", n_time_steps,
false);
311 while (bounds.first > bounds.second || bounds.second > n_time_steps)
314 "Specify last time step to export: ", n_time_steps,
false);
327 std::cout <<
"\nSelect element type for result, choose ";
330 std::cout <<
"(t)riangle or (q)uadliteral: ";
332 std::cout <<
"(p)rism or (h)exahedron: ";
333 std::string type(
"");
334 std::getline(std::cin, type);
338 if (type !=
"t" && type !=
"q" && type !=
"tri" && type !=
"quad" &&
339 type !=
"triangle" && type !=
"quatliteral")
341 if (type ==
"t" || type ==
"tri" || type ==
"triangle")
348 if (type !=
"p" && type !=
"h" && type !=
"prism" &&
349 type !=
"hex" && type !=
"hexahedron")
351 if (type ==
"p" || type ==
"prism")
360 std::pair<std::size_t, std::size_t>
const& time_bounds)
365 std::size_t
const n_time_steps(time_bounds.second - time_bounds.first +
367 std::cout <<
"\nThe selection includes " << n_time_steps
369 std::cout <<
"0. Save data in " << n_time_steps
370 <<
" mesh files with one scalar array each.\n";
371 std::cout <<
"1. Save data in one mesh file with " << n_time_steps
372 <<
" scalar arrays.\n";
373 std::cout <<
"2. Save data as " << n_time_steps <<
" ASC images.\n";
375 std::size_t
const ret =
376 parseInput(
"Select preferred method: ", 3,
false);
390 std::size_t
const max_length(std::to_string(max).length());
391 std::string
const current_str(std::to_string(i));
392 return std::string(max_length - current_str.length(),
'0') + current_str;
397 std::size_t
const dim_idx = var.getDimCount() - 1;
398 NcVar
const dim_var(
getDimVar(dataset, var, dim_idx));
399 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, dim_idx)
401 std::size_t
const dim_size = var.getDim(dim_idx).getSize();
404 OGS_FATAL(
"Dimension '{:s}' has size 0. Aborting...",
405 var.getDim(dim_idx).getName());
407 return std::fabs(bounds.second - bounds.first) /
408 static_cast<double>(dim_size);
412 NcFile
const& dataset, NcVar
const& var,
413 std::vector<std::size_t>
const& dim_idx_map,
414 std::vector<std::size_t>
const& length, std::size_t
const time_offset)
417 getOrigin(dataset, var, dim_idx_map, time_offset);
419 std::size_t n_dims = var.getDimCount();
420 std::size_t z_length =
421 (n_dims - time_offset == 3) ? length[dim_idx_map.back()] : 1;
422 return {length[dim_idx_map[0 + time_offset]],
423 length[dim_idx_map[1 + time_offset]],
430static std::vector<std::size_t>
getLength(NcVar
const& var,
431 std::size_t
const time_offset)
433 std::size_t
const n_dims = (var.getDimCount());
434 std::vector<std::size_t> length(n_dims, 1);
435 for (std::size_t i = time_offset; i < n_dims; ++i)
437 length[i] = var.getDim(i).getSize();
442static std::vector<double>
getData(NcVar
const& var,
443 std::size_t
const total_length,
444 std::size_t
const time_step,
445 std::vector<std::size_t>
const& length)
447 std::size_t
const n_dims(var.getDimCount());
448 std::vector<std::size_t> offset(n_dims, 0);
449 offset[0] = time_step;
450 std::vector<double> data_vec(total_length, 0);
451 var.getVar(offset, length, data_vec.data());
454 data_vec.begin(), data_vec.end(),
455 [](
double const& x) { return x == no_data_input; },
no_data_output);
461 std::vector<std::size_t>& dim_idx_map,
462 TCLAP::ValueArg<std::size_t>& arg_dim_time,
463 TCLAP::ValueArg<std::size_t>& arg_dim1,
464 TCLAP::ValueArg<std::size_t>& arg_dim2,
465 TCLAP::ValueArg<std::size_t>& arg_dim3)
467 std::size_t dim_param_count = 0;
468 if (arg_dim_time.isSet())
470 if (arg_dim1.isSet())
472 if (arg_dim2.isSet())
474 if (arg_dim3.isSet())
477 std::size_t
const n_dims = var.getDimCount();
478 if (dim_param_count != n_dims)
480 ERR(
"Number of parameters set does not fit number of parameters for "
481 "specified variable.");
485 if (arg_dim_time.getValue() >= n_dims || arg_dim1.getValue() >= n_dims ||
486 arg_dim2.getValue() >= n_dims || arg_dim3.getValue() >= n_dims)
488 ERR(
"Maximum allowed dimension for variable \"{:s}\" is {:d}.",
489 var.getName(), n_dims - 1);
493 if (arg_dim_time.isSet())
494 dim_idx_map[0] = arg_dim_time.getValue();
495 std::size_t
const temp_offset = (arg_dim_time.isSet()) ? 1 : 0;
496 dim_idx_map[0 + temp_offset] = arg_dim1.getValue();
497 dim_idx_map[1 + temp_offset] = arg_dim2.getValue();
498 if (n_dims == (3 + temp_offset))
499 dim_idx_map[2 + temp_offset] = arg_dim3.getValue();
506 TCLAP::ValueArg<std::size_t>& arg_time_start,
507 TCLAP::ValueArg<std::size_t>& arg_time_end)
510 if (arg_time_start.getValue() > bounds.second)
512 ERR(
"Start time step larger than total number of time steps. Resetting "
514 arg_time_start.reset();
517 if (!arg_time_end.isSet())
518 return {arg_time_start.getValue(), arg_time_start.getValue()};
520 if (arg_time_end.getValue() > bounds.second)
522 ERR(
"End time step larger than total number of time steps. Resetting "
523 "to starting time step");
524 return {arg_time_start.getValue(), arg_time_start.getValue()};
527 if (arg_time_end.getValue() < arg_time_start.getValue())
529 ERR(
"End time step larger than starting time step. Swapping values");
530 return {arg_time_end.getValue(), arg_time_start.getValue()};
533 return {arg_time_start.getValue(), arg_time_end.getValue()};
537 TCLAP::ValueArg<std::string>& arg_elem_type)
539 if (arg_elem_type.getValue() ==
"tri")
541 if (arg_elem_type.getValue() ==
"quad")
543 if (arg_elem_type.getValue() ==
"prism")
545 if (arg_elem_type.getValue() ==
"hex")
551static bool convert(NcFile
const& dataset, NcVar
const& var,
552 std::string
const& output_name,
553 std::vector<std::size_t>
const& dim_idx_map,
554 std::size_t
const time_offset,
555 std::pair<std::size_t, std::size_t>
const& time_bounds,
559 std::unique_ptr<MeshLib::Mesh> mesh;
560 std::vector<std::size_t>
const length =
getLength(var, time_offset);
561 std::size_t
const array_length = std::accumulate(
562 length.cbegin(), length.cend(), 1, std::multiplies<std::size_t>());
563 for (std::size_t i = time_bounds.first; i <= time_bounds.second; ++i)
565 std::string
const step_str =
566 (time_bounds.first != time_bounds.second)
567 ? std::string(
" time step " + std::to_string(i))
569 std::cout <<
"Converting" << step_str <<
"...\n";
570 std::vector<double> data_vec =
getData(var, array_length, i, length);
574 std::size_t
const n_dims = length.size();
575 NcVar
const dim_var(
getDimVar(dataset, var, n_dims - 2));
576 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, n_dims - 2)
578 if (bounds.first > bounds.second)
580 std::size_t n_layers =
581 (length.size() - time_offset == 3) ? length[n_dims - 3] : 1;
582 flipRaster(data_vec, n_layers, length[n_dims - 1],
593 elem_type, useIntensity,
595 std::string
const output_file_name(
603 std::string array_name(var.getName());
604 if (time_bounds.first != time_bounds.second)
606 if (i == time_bounds.first)
608 data_vec.data(), header, elem_type, useIntensity,
612 std::unique_ptr<MeshLib::Mesh>
const temp(
614 elem_type, useIntensity,
617 temp->getProperties().getPropertyVector<
double>(array_name);
620 MeshLib::addPropertyToMesh<double>(
623 if (i == time_bounds.second)
626 std::string
const output_file_name =
629 : output_name +
".vtu";
636 data_vec.data() + header.
n_cols *
639 std::string
const output_file_name(
649int main(
int argc,
char* argv[])
652 "Converts NetCDF data into mesh file(s).\n\n "
653 "OpenGeoSys-6 software, version " +
656 "Copyright (c) 2012-2024, OpenGeoSys Community "
657 "(http://www.opengeosys.org)",
660 TCLAP::ValueArg<int> arg_nodata(
662 "explicitly specifies the no data value used in the dataset (usually "
663 "it is not necessary to set this)",
667 std::vector<std::string> allowed_elems{
"tri",
"quad",
"prism",
"hex"};
668 TCLAP::ValuesConstraint<std::string> allowed_elem_vals(allowed_elems);
669 TCLAP::ValueArg<std::string> arg_elem_type(
670 "e",
"elem-type",
"the element type used in the resulting OGS mesh",
671 false,
"", &allowed_elem_vals);
672 cmd.add(arg_elem_type);
674 TCLAP::SwitchArg arg_images(
676 "if set, all time steps will be written as ESRI image files (*.asc)");
679 TCLAP::SwitchArg arg_multi_files(
681 "if set, each time step will be written to a separate mesh file");
682 cmd.add(arg_multi_files);
684 TCLAP::SwitchArg arg_single_file(
686 "if set, all time steps will be written to a single mesh file (with "
687 "one scalar array per time step)");
688 cmd.add(arg_single_file);
690 TCLAP::ValueArg<std::size_t> arg_time_end(
692 "last time step to be extracted (only for time-dependent variables!)",
693 false, 0,
"integer specifying index of time step");
694 cmd.add(arg_time_end);
696 TCLAP::ValueArg<std::size_t> arg_time_start(
697 "",
"timestep-first",
698 "first time step to be extracted (only for time-dependent variables!)",
699 false, 0,
"integer specifying index of time step");
700 cmd.add(arg_time_start);
702 std::vector<std::size_t> allowed_dims{0, 1, 2, 3};
703 TCLAP::ValuesConstraint<std::size_t> allowed_dim_vals(allowed_dims);
704 TCLAP::ValueArg<std::size_t> arg_dim3(
706 "index of third dimension (z/height/depth) for the selected variable",
707 false, 0, &allowed_dim_vals);
710 TCLAP::ValueArg<std::size_t> arg_dim2(
712 "index of second dimension (y/latitude) for the selected variable",
713 false, 0, &allowed_dim_vals);
716 TCLAP::ValueArg<std::size_t> arg_dim1(
718 "index of first dimension (x/longitude) for the selected variable",
719 false, 0, &allowed_dim_vals);
722 TCLAP::ValueArg<std::size_t> arg_dim_time(
724 "index of the time-dependent dimension for the selected variable",
725 false, 0, &allowed_dim_vals);
726 cmd.add(arg_dim_time);
728 TCLAP::ValueArg<std::string> arg_varname(
729 "v",
"var",
"variable included in the the netCDF file",
false,
"",
730 "string containing the variable name");
731 cmd.add(arg_varname);
733 TCLAP::ValueArg<std::string> arg_output(
734 "o",
"output",
"the OGS mesh output file",
true,
"",
735 "string containing the path and file name");
737 TCLAP::ValueArg<std::string> arg_input(
738 "i",
"input",
"the netCDF input file",
true,
"",
739 "string containing the path and file name");
741 cmd.parse(argc, argv);
744 MPI_Init(&argc, &argv);
747 NcFile dataset(arg_input.getValue().c_str(), NcFile::read);
749 if (dataset.isNull())
751 ERR(
"Error opening file.");
758 std::size_t
const mutex =
759 arg_single_file.isSet() + arg_multi_files.isSet() + arg_images.isSet();
762 ERR(
"Only one output format can be specified (single-file, multi-file, "
770 std::cout <<
"OpenGeoSys NetCDF Converter\n";
771 if (!arg_varname.isSet())
773 std::cout <<
"File " << arg_input.getValue()
774 <<
" loaded. Press ENTER to display available data arrays.\n";
778 std::string
const& output_name(arg_output.getValue());
779 std::string
const& var_name = (arg_varname.isSet())
780 ? arg_varname.getValue()
782 NcVar
const& var = dataset.getVar(var_name);
785 ERR(
"Variable \"{:s}\" not found in file.", arg_varname.getValue());
792 std::vector<std::size_t> dim_idx_map(var.getDimCount(), 0);
793 bool is_time_dep(
false);
794 if (arg_dim1.isSet() && arg_dim2.isSet())
796 is_time_dep = arg_dim_time.isSet();
797 if (!
assignDimParams(var, dim_idx_map, arg_dim_time, arg_dim1, arg_dim2,
811 std::pair<std::size_t, std::size_t> time_bounds(0, 0);
814 (arg_time_start.isSet())
816 arg_time_start, arg_time_end)
820 if (arg_images.isSet())
824 else if (arg_multi_files.isSet())
828 else if (arg_single_file.isSet() || !is_time_dep ||
829 time_bounds.first == time_bounds.second)
838 std::size_t
const temp_offset = (is_time_dep) ? 1 : 0;
839 std::size_t
const n_dims = (var.getDimCount());
844 elem_type = (arg_elem_type.isSet())
851 if (arg_nodata.isSet())
856 if (!
convert(dataset, var, output_name, dim_idx_map, is_time_dep,
857 time_bounds, output, elem_type))
865 std::cout <<
"Conversion finished successfully.\n";
Definition of the AsciiRasterInterface class.
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition of the Mesh class.
static void showArrays(NcFile const &dataset)
static double no_data_input
static OutputType multFilesSelectionLoop(std::pair< std::size_t, std::size_t > const &time_bounds)
int main(int argc, char *argv[])
static std::string arraySelectionLoop(NcFile const &dataset)
static MathLib::Point3d getOrigin(NcFile const &dataset, NcVar const &var, std::vector< std::size_t > const &dim_idx_map, std::size_t const time_offset)
static GeoLib::RasterHeader createRasterHeader(NcFile const &dataset, NcVar const &var, std::vector< std::size_t > const &dim_idx_map, std::vector< std::size_t > const &length, std::size_t const time_offset)
static void showErrorMessage(std::size_t const error_id, std::size_t const max=0)
static std::pair< double, double > getDimLength(NcVar const &var, std::size_t const dim)
static std::pair< std::size_t, std::size_t > assignTimeBounds(NcVar const &var, TCLAP::ValueArg< std::size_t > &arg_time_start, TCLAP::ValueArg< std::size_t > &arg_time_end)
static std::pair< double, double > getBoundaries(NcVar const &var)
static std::size_t parseInput(std::string const &request_str, std::size_t const max_val, bool const has_info=false)
static std::string getIterationString(std::size_t i, std::size_t max)
static MeshLib::MeshElemType assignElemType(TCLAP::ValueArg< std::string > &arg_elem_type)
static MeshLib::MeshElemType elemSelectionLoop(std::size_t const dim)
static bool assignDimParams(NcVar const &var, std::vector< std::size_t > &dim_idx_map, TCLAP::ValueArg< std::size_t > &arg_dim_time, TCLAP::ValueArg< std::size_t > &arg_dim1, TCLAP::ValueArg< std::size_t > &arg_dim2, TCLAP::ValueArg< std::size_t > &arg_dim3)
static std::pair< std::size_t, std::size_t > timestepSelectionLoop(NcVar const &var, std::size_t const dim_idx)
static const double no_data_output
static void checkExit(std::string const &str)
static void flipRaster(std::vector< double > &data, std::size_t const layers, std::size_t const width, std::size_t const height)
static std::vector< std::size_t > getLength(NcVar const &var, std::size_t const time_offset)
static std::vector< std::string > getArrays(NcFile const &dataset)
static NcVar getDimVar(NcFile const &dataset, NcVar const &var, std::size_t const dim)
static bool dimensionSelectionLoop(NcVar const &var, std::vector< std::size_t > &dim_idx_map)
static double getResolution(NcFile const &dataset, NcVar const &var)
static std::vector< double > getData(NcVar const &var, std::size_t const total_length, std::size_t const time_step, std::vector< std::size_t > const &length)
static bool convert(NcFile const &dataset, NcVar const &var, std::string const &output_name, std::vector< std::size_t > const &dim_idx_map, std::size_t const time_offset, std::pair< std::size_t, std::size_t > const &time_bounds, OutputType const output, MeshLib::MeshElemType const elem_type)
static bool canConvert(NcVar const &var)
static void showArraysDims(NcVar const &var)
Definition of the GeoLib::Raster class.
Implementation of the VtuInterface class.
static void writeRasterAsASC(GeoLib::Raster const &raster, std::string const &file_name)
Writes an Esri asc-file.
Class Raster is used for managing raster data.
Reads and writes VtkXMLUnstructuredGrid-files (vtu) to and from OGS data structures....
bool writeToFile(std::filesystem::path const &file_path)
std::string getFileExtension(const std::string &path)
std::string dropFileExtension(std::string const &filename)
GITINFOLIB_EXPORT const std::string ogs_version
UseIntensityAs
Selection of possible interpretations for intensities.
MeshElemType
Types of mesh elements supported by OpenGeoSys. Values are from VTKCellType enum.