4#include <tclap/CmdLine.h>
28using namespace netCDF;
43 if (str ==
"x" || str ==
"exit")
48 std::size_t
const max = 0)
52 ERR(
"Input not valid.");
54 else if (error_id == 1)
56 ERR(
"Index not valid. Valid indices are in [0,{:d}].", max);
58 else if (error_id == 2)
60 ERR(
"Input not valid.");
61 std::cout <<
"Type \"info\" to display the available options again. "
62 "\"exit\" will exit the programme.\n";
66static std::size_t
parseInput(std::string
const& request_str,
67 std::size_t
const max_val,
68 bool const has_info =
false)
72 std::cout << request_str;
75 std::getline(std::cin, str);
77 if (has_info && str ==
"info")
79 std::stringstream str_stream(str);
80 if (!(str_stream >> val))
82 std::size_t
const error_val = (has_info) ? 2 : 0;
86 if (val > max_val - 1)
93 return std::numeric_limits<std::size_t>::max();
96static NcVar
getDimVar(NcFile
const& dataset, NcVar
const& var,
97 std::size_t
const dim)
99 NcDim
const& dim_obj = var.getDim(dim);
100 return dataset.getVar(dim_obj.getName());
104 std::size_t
const dim)
106 return std::make_pair(0.0,
static_cast<double>(var.getDim(dim).getSize()));
109static std::vector<std::string>
getArrays(NcFile
const& dataset)
111 auto const& names = dataset.getVars();
112 std::vector<std::string> var_names;
113 for (
auto [name, var] : names)
116 var_names.push_back(name);
123 std::size_t
const n_vars(dataset.getDimCount());
124 std::cout <<
"The NetCDF file contains the following " << n_vars
126 std::cout <<
"\tIndex\tArray Name\t#Dimensions\n";
127 std::cout <<
"-------------------------------------------\n";
128 auto const& names = dataset.getVars();
129 std::size_t count = 0;
130 for (
auto [name, var] : names)
132 std::cout <<
"\t" << count++ <<
"\t" << name <<
"\t("
133 << var.getDimCount() <<
"D array)\n";
140 std::cout <<
"Data array \"" << var.getName()
141 <<
"\" contains the following dimensions:\n";
142 std::size_t
const n_dims(var.getDimCount());
143 for (std::size_t i = 0; i < n_dims; ++i)
144 std::cout <<
"\t" << i <<
"\t" << var.getDim(i).getName() <<
"\t("
145 << var.getDim(i).getSize() <<
" values)\n";
151 if (var.getDimCount() == 1)
154 std::size_t
const size = var.getDim(0).getSize();
155 var.getVar({0}, {1}, &start);
156 var.getVar({size - 1}, {1}, &end);
157 return std::make_pair(start, end);
159 return std::make_pair(0, 0);
163 std::vector<std::size_t>
const& dim_idx_map,
164 std::size_t
const time_offset)
167 std::size_t
const n_dims = var.getDimCount();
168 for (std::size_t i = time_offset; i < n_dims; ++i)
170 NcVar
const& dim =
getDimVar(dataset, var, dim_idx_map[i]);
171 auto const bounds = (dim.isNull()) ?
getDimLength(var, dim_idx_map[i])
173 origin[i - time_offset] =
174 (bounds.first < bounds.second) ? bounds.first : bounds.second;
179static void flipRaster(std::vector<double>& data, std::size_t
const layers,
180 std::size_t
const width, std::size_t
const height)
182 std::size_t
const length(data.size());
183 std::vector<double> tmp_vec;
184 tmp_vec.reserve(length);
185 for (std::size_t k = 0; k < layers; k++)
187 std::size_t
const layer_end = (k + 1) * height * width;
188 for (std::size_t i = 0; i < height; i++)
190 std::size_t
const line_idx(layer_end - (width * (i + 1)));
191 for (std::size_t j = 0; j < width; j++)
193 tmp_vec.push_back(data[line_idx + j]);
197 std::copy(tmp_vec.cbegin(), tmp_vec.cend(), data.begin());
202 bool ret(var.getDimCount() < 2);
204 ERR(
"Only 2+ dimensional variables can be converted into OGS "
211 std::vector<std::string>
const& names =
getArrays(dataset);
213 std::size_t
const idx =
214 parseInput(
"Enter data array index: ", dataset.getVarCount(),
true);
216 if (
static_cast<int>(idx) == dataset.getVarCount() ||
224 std::vector<std::size_t>& dim_idx_map)
227 std::size_t
const n_dims(var.getDimCount());
228 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
229 bool is_time_dep(
true);
234 std::string temp_str(
"");
235 std::cout <<
"Is the parameter time-dependent?\n";
236 while (dim_idx_map[0] == std::numeric_limits<std::size_t>::max() &&
240 <<
"Enter ID for temporal dimension or \"c\" to continue: ";
241 std::getline(std::cin, temp_str);
242 std::stringstream str_stream(temp_str);
243 if (str_stream.str() ==
"c" || str_stream.str() ==
"continue")
247 if (!(str_stream >> dim_idx_map[0]))
250 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
253 if (dim_idx_map[0] > n_dims - 1)
256 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
265 std::size_t
const start_idx = (is_time_dep) ? 1 : 0;
266 std::array<std::string, 4>
const dim_comment{
267 "(x / longitude)",
"(y / latitude)",
"(z / height / depth)",
268 "[Error: 4-dimensional non-temporal arrays are not supported]"};
269 for (std::size_t i = start_idx; i < n_dims; ++i)
271 dim_idx_map[i] = std::numeric_limits<std::size_t>::max();
273 std::string
const request_str(
"Enter ID for dimension " +
274 std::to_string(i) +
" " +
275 dim_comment[i - start_idx] +
": ");
276 std::size_t
const idx =
277 parseInput(request_str, var.getDimCount(),
true);
279 if (
static_cast<int>(idx) == var.getDimCount())
285 dim_idx_map[i] = idx;
292 NcVar
const& var, std::size_t
const dim_idx)
294 std::size_t
const n_time_steps = var.getDim(dim_idx).getSize();
295 std::size_t
const max_val = std::numeric_limits<std::size_t>::max();
296 std::pair<std::size_t, std::size_t> bounds(max_val, max_val);
297 std::cout <<
"\nThe dataset contains " << n_time_steps <<
" time steps.\n";
298 while (bounds.first == max_val)
301 "Specify first time step to export: ", n_time_steps,
false);
303 while (bounds.first > bounds.second || bounds.second > n_time_steps)
306 "Specify last time step to export: ", n_time_steps,
false);
319 std::cout <<
"\nSelect element type for result, choose ";
322 std::cout <<
"(t)riangle or (q)uadliteral: ";
324 std::cout <<
"(p)rism or (h)exahedron: ";
325 std::string type(
"");
326 std::getline(std::cin, type);
330 if (type !=
"t" && type !=
"q" && type !=
"tri" && type !=
"quad" &&
331 type !=
"triangle" && type !=
"quatliteral")
333 if (type ==
"t" || type ==
"tri" || type ==
"triangle")
340 if (type !=
"p" && type !=
"h" && type !=
"prism" &&
341 type !=
"hex" && type !=
"hexahedron")
343 if (type ==
"p" || type ==
"prism")
352 std::pair<std::size_t, std::size_t>
const& time_bounds)
357 std::size_t
const n_time_steps(time_bounds.second - time_bounds.first +
359 std::cout <<
"\nThe selection includes " << n_time_steps
361 std::cout <<
"0. Save data in " << n_time_steps
362 <<
" mesh files with one scalar array each.\n";
363 std::cout <<
"1. Save data in one mesh file with " << n_time_steps
364 <<
" scalar arrays.\n";
365 std::cout <<
"2. Save data as " << n_time_steps <<
" ASC images.\n";
367 std::size_t
const ret =
368 parseInput(
"Select preferred method: ", 3,
false);
382 std::size_t
const max_length(std::to_string(max).length());
383 std::string
const current_str(std::to_string(i));
384 return std::string(max_length - current_str.length(),
'0') + current_str;
389 std::size_t
const dim_idx = var.getDimCount() - 1;
390 NcVar
const dim_var(
getDimVar(dataset, var, dim_idx));
391 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, dim_idx)
393 std::size_t
const dim_size = var.getDim(dim_idx).getSize();
396 OGS_FATAL(
"Dimension '{:s}' has size 0. Aborting...",
397 var.getDim(dim_idx).getName());
399 return std::fabs(bounds.second - bounds.first) /
400 static_cast<double>(dim_size);
404 NcFile
const& dataset, NcVar
const& var,
405 std::vector<std::size_t>
const& dim_idx_map,
406 std::vector<std::size_t>
const& length, std::size_t
const time_offset)
409 getOrigin(dataset, var, dim_idx_map, time_offset);
411 std::size_t n_dims = var.getDimCount();
412 std::size_t z_length =
413 (n_dims - time_offset == 3) ? length[dim_idx_map.back()] : 1;
414 return {length[dim_idx_map[0 + time_offset]],
415 length[dim_idx_map[1 + time_offset]],
422static std::vector<std::size_t>
getLength(NcVar
const& var,
423 std::size_t
const time_offset)
425 std::size_t
const n_dims = (var.getDimCount());
426 std::vector<std::size_t> length(n_dims, 1);
427 for (std::size_t i = time_offset; i < n_dims; ++i)
429 length[i] = var.getDim(i).getSize();
434static std::vector<double>
getData(NcVar
const& var,
435 std::size_t
const total_length,
436 std::size_t
const time_step,
437 std::vector<std::size_t>
const& length)
439 std::size_t
const n_dims(var.getDimCount());
440 std::vector<std::size_t> offset(n_dims, 0);
441 offset[0] = time_step;
442 std::vector<double> data_vec(total_length, 0);
443 var.getVar(offset, length, data_vec.data());
446 data_vec.begin(), data_vec.end(),
447 [](
double const& x) { return x == no_data_input; },
no_data_output);
453 std::vector<std::size_t>& dim_idx_map,
454 TCLAP::ValueArg<std::size_t>& arg_dim_time,
455 TCLAP::ValueArg<std::size_t>& arg_dim1,
456 TCLAP::ValueArg<std::size_t>& arg_dim2,
457 TCLAP::ValueArg<std::size_t>& arg_dim3)
459 std::size_t dim_param_count = 0;
460 if (arg_dim_time.isSet())
462 if (arg_dim1.isSet())
464 if (arg_dim2.isSet())
466 if (arg_dim3.isSet())
469 std::size_t
const n_dims = var.getDimCount();
470 if (dim_param_count != n_dims)
472 ERR(
"Number of parameters set does not fit number of parameters for "
473 "specified variable.");
477 if (arg_dim_time.getValue() >= n_dims || arg_dim1.getValue() >= n_dims ||
478 arg_dim2.getValue() >= n_dims || arg_dim3.getValue() >= n_dims)
480 ERR(
"Maximum allowed dimension for variable \"{:s}\" is {:d}.",
481 var.getName(), n_dims - 1);
485 if (arg_dim_time.isSet())
486 dim_idx_map[0] = arg_dim_time.getValue();
487 std::size_t
const temp_offset = (arg_dim_time.isSet()) ? 1 : 0;
488 dim_idx_map[0 + temp_offset] = arg_dim1.getValue();
489 dim_idx_map[1 + temp_offset] = arg_dim2.getValue();
490 if (n_dims == (3 + temp_offset))
491 dim_idx_map[2 + temp_offset] = arg_dim3.getValue();
498 TCLAP::ValueArg<std::size_t>& arg_time_start,
499 TCLAP::ValueArg<std::size_t>& arg_time_end)
502 if (arg_time_start.getValue() > bounds.second)
504 ERR(
"Start time step larger than total number of time steps. Resetting "
506 arg_time_start.reset();
509 if (!arg_time_end.isSet())
510 return {arg_time_start.getValue(), arg_time_start.getValue()};
512 if (arg_time_end.getValue() > bounds.second)
514 ERR(
"End time step larger than total number of time steps. Resetting "
515 "to starting time step");
516 return {arg_time_start.getValue(), arg_time_start.getValue()};
519 if (arg_time_end.getValue() < arg_time_start.getValue())
521 ERR(
"End time step larger than starting time step. Swapping values");
522 return {arg_time_end.getValue(), arg_time_start.getValue()};
525 return {arg_time_start.getValue(), arg_time_end.getValue()};
529 TCLAP::ValueArg<std::string>& arg_elem_type)
531 if (arg_elem_type.getValue() ==
"tri")
533 if (arg_elem_type.getValue() ==
"quad")
535 if (arg_elem_type.getValue() ==
"prism")
537 if (arg_elem_type.getValue() ==
"hex")
543static bool convert(NcFile
const& dataset, NcVar
const& var,
544 std::string
const& output_name,
545 std::vector<std::size_t>
const& dim_idx_map,
546 std::size_t
const time_offset,
547 std::pair<std::size_t, std::size_t>
const& time_bounds,
551 std::unique_ptr<MeshLib::Mesh> mesh;
552 std::vector<std::size_t>
const length =
getLength(var, time_offset);
553 std::size_t
const array_length = std::accumulate(
554 length.cbegin(), length.cend(), 1, std::multiplies<std::size_t>());
555 for (std::size_t i = time_bounds.first; i <= time_bounds.second; ++i)
557 std::string
const step_str =
558 (time_bounds.first != time_bounds.second)
559 ? std::string(
" time step " + std::to_string(i))
561 std::cout <<
"Converting" << step_str <<
"...\n";
562 std::vector<double> data_vec =
getData(var, array_length, i, length);
566 std::size_t
const n_dims = length.size();
567 NcVar
const dim_var(
getDimVar(dataset, var, n_dims - 2));
568 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, n_dims - 2)
570 if (bounds.first > bounds.second)
572 std::size_t n_layers =
573 (length.size() - time_offset == 3) ? length[n_dims - 3] : 1;
574 flipRaster(data_vec, n_layers, length[n_dims - 1],
585 elem_type, useIntensity,
587 std::string
const output_file_name(
598 std::string array_name(var.getName());
599 if (time_bounds.first != time_bounds.second)
601 if (i == time_bounds.first)
603 data_vec.data(), header, elem_type, useIntensity,
607 std::unique_ptr<MeshLib::Mesh>
const temp(
609 elem_type, useIntensity,
612 temp->getProperties().getPropertyVector<
double>(array_name);
620 if (i == time_bounds.second)
622 std::string
const output_file_name =
625 : output_name +
".vtu";
627 output_file_name) != 0)
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-2026, 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,
"TIME_END");
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,
"TIMESTEP_FIRST");
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,
"",
731 cmd.add(arg_varname);
733 TCLAP::ValueArg<std::string> arg_output(
734 "o",
"output",
"Output (.vtu). The OGS mesh output file",
true,
"",
737 TCLAP::ValueArg<std::string> arg_input(
"i",
"input",
738 "Input (.nc). The netCDF input file",
739 true,
"",
"INPUT_FILE");
742 cmd.add(log_level_arg);
743 cmd.parse(argc, argv);
748 NcFile dataset(arg_input.getValue().c_str(), NcFile::read);
750 if (dataset.isNull())
752 ERR(
"Error opening file.");
756 std::size_t
const mutex =
757 arg_single_file.isSet() + arg_multi_files.isSet() + arg_images.isSet();
760 ERR(
"Only one output format can be specified (single-file, multi-file, "
765 std::cout <<
"OpenGeoSys NetCDF Converter\n";
766 if (!arg_varname.isSet())
768 std::cout <<
"File " << arg_input.getValue()
769 <<
" loaded. Press ENTER to display available data arrays.\n";
773 std::string
const& output_name(arg_output.getValue());
774 std::string
const& var_name = (arg_varname.isSet())
775 ? arg_varname.getValue()
777 NcVar
const& var = dataset.getVar(var_name);
780 ERR(
"Variable \"{:s}\" not found in file.", arg_varname.getValue());
784 std::vector<std::size_t> dim_idx_map(var.getDimCount(), 0);
785 bool is_time_dep(
false);
786 if (arg_dim1.isSet() && arg_dim2.isSet())
788 is_time_dep = arg_dim_time.isSet();
789 if (!
assignDimParams(var, dim_idx_map, arg_dim_time, arg_dim1, arg_dim2,
800 std::pair<std::size_t, std::size_t> time_bounds(0, 0);
803 (arg_time_start.isSet())
805 arg_time_start, arg_time_end)
809 if (arg_images.isSet())
813 else if (arg_multi_files.isSet())
817 else if (arg_single_file.isSet() || !is_time_dep ||
818 time_bounds.first == time_bounds.second)
827 std::size_t
const temp_offset = (is_time_dep) ? 1 : 0;
828 std::size_t
const n_dims = (var.getDimCount());
833 elem_type = (arg_elem_type.isSet())
840 if (arg_nodata.isSet())
845 if (!
convert(dataset, var, output_name, dim_idx_map, is_time_dep,
846 time_bounds, output, elem_type))
851 std::cout <<
"Conversion finished successfully.\n";
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
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)
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.
TCLAP::ValueArg< std::string > makeLogLevelArg()
void initOGSLogger(std::string const &log_level)
std::string getFileExtension(const std::string &path)
std::string dropFileExtension(std::string const &filename)
GITINFOLIB_EXPORT const std::string ogs_version
int writeMeshToFile(const MeshLib::Mesh &mesh, std::filesystem::path const &file_path, std::set< std::string > output_variable_names, bool const use_compression, int const data_mode)
void addPropertyToMesh(Mesh &mesh, std::string_view name, MeshItemType item_type, std::size_t number_of_components, std::span< T const > values)
UseIntensityAs
Selection of possible interpretations for intensities.
MeshElemType
Types of mesh elements supported by OpenGeoSys. Values are from VTKCellType enum.