10#include <tclap/CmdLine.h>
34using namespace netCDF;
49 if (str ==
"x" || str ==
"exit")
54 std::size_t
const max = 0)
58 ERR(
"Input not valid.");
60 else if (error_id == 1)
62 ERR(
"Index not valid. Valid indices are in [0,{:d}].", max);
64 else if (error_id == 2)
66 ERR(
"Input not valid.");
67 std::cout <<
"Type \"info\" to display the available options again. "
68 "\"exit\" will exit the programme.\n";
72static std::size_t
parseInput(std::string
const& request_str,
73 std::size_t
const max_val,
74 bool const has_info =
false)
78 std::cout << request_str;
81 std::getline(std::cin, str);
83 if (has_info && str ==
"info")
85 std::stringstream str_stream(str);
86 if (!(str_stream >> val))
88 std::size_t
const error_val = (has_info) ? 2 : 0;
92 if (val > max_val - 1)
99 return std::numeric_limits<std::size_t>::max();
102static NcVar
getDimVar(NcFile
const& dataset, NcVar
const& var,
103 std::size_t
const dim)
105 NcDim
const& dim_obj = var.getDim(dim);
106 return dataset.getVar(dim_obj.getName());
110 std::size_t
const dim)
112 return std::make_pair(0.0,
static_cast<double>(var.getDim(dim).getSize()));
115static std::vector<std::string>
getArrays(NcFile
const& dataset)
117 auto const& names = dataset.getVars();
118 std::vector<std::string> var_names;
119 for (
auto [name, var] : names)
122 var_names.push_back(name);
129 std::size_t
const n_vars(dataset.getDimCount());
130 std::cout <<
"The NetCDF file contains the following " << n_vars
132 std::cout <<
"\tIndex\tArray Name\t#Dimensions\n";
133 std::cout <<
"-------------------------------------------\n";
134 auto const& names = dataset.getVars();
135 std::size_t count = 0;
136 for (
auto [name, var] : names)
138 std::cout <<
"\t" << count++ <<
"\t" << name <<
"\t("
139 << var.getDimCount() <<
"D array)\n";
146 std::cout <<
"Data array \"" << var.getName()
147 <<
"\" contains the following dimensions:\n";
148 std::size_t
const n_dims(var.getDimCount());
149 for (std::size_t i = 0; i < n_dims; ++i)
150 std::cout <<
"\t" << i <<
"\t" << var.getDim(i).getName() <<
"\t("
151 << var.getDim(i).getSize() <<
" values)\n";
157 if (var.getDimCount() == 1)
160 std::size_t
const size = var.getDim(0).getSize();
161 var.getVar({0}, {1}, &start);
162 var.getVar({size - 1}, {1}, &end);
163 return std::make_pair(start, end);
165 return std::make_pair(0, 0);
169 std::vector<std::size_t>
const& dim_idx_map,
170 std::size_t
const time_offset)
173 std::size_t
const n_dims = var.getDimCount();
174 for (std::size_t i = time_offset; i < n_dims; ++i)
176 NcVar
const& dim =
getDimVar(dataset, var, dim_idx_map[i]);
177 auto const bounds = (dim.isNull()) ?
getDimLength(var, dim_idx_map[i])
179 origin[i - time_offset] =
180 (bounds.first < bounds.second) ? bounds.first : bounds.second;
185static void flipRaster(std::vector<double>& data, std::size_t
const layers,
186 std::size_t
const width, std::size_t
const height)
188 std::size_t
const length(data.size());
189 std::vector<double> tmp_vec;
190 tmp_vec.reserve(length);
191 for (std::size_t k = 0; k < layers; k++)
193 std::size_t
const layer_end = (k + 1) * height * width;
194 for (std::size_t i = 0; i < height; i++)
196 std::size_t
const line_idx(layer_end - (width * (i + 1)));
197 for (std::size_t j = 0; j < width; j++)
199 tmp_vec.push_back(data[line_idx + j]);
203 std::copy(tmp_vec.cbegin(), tmp_vec.cend(), data.begin());
208 bool ret(var.getDimCount() < 2);
210 ERR(
"Only 2+ dimensional variables can be converted into OGS "
217 std::vector<std::string>
const& names =
getArrays(dataset);
219 std::size_t
const idx =
220 parseInput(
"Enter data array index: ", dataset.getVarCount(),
true);
222 if (
static_cast<int>(idx) == dataset.getVarCount() ||
230 std::vector<std::size_t>& dim_idx_map)
233 std::size_t
const n_dims(var.getDimCount());
234 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
235 bool is_time_dep(
true);
240 std::string temp_str(
"");
241 cout <<
"Is the parameter time-dependent?\n";
242 while (dim_idx_map[0] == std::numeric_limits<std::size_t>::max() &&
245 cout <<
"Enter ID for temporal dimension or \"c\" to continue: ";
246 std::getline(std::cin, temp_str);
247 std::stringstream str_stream(temp_str);
248 if (str_stream.str() ==
"c" || str_stream.str() ==
"continue")
252 if (!(str_stream >> dim_idx_map[0]))
255 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
258 if (dim_idx_map[0] > n_dims - 1)
261 dim_idx_map[0] = std::numeric_limits<std::size_t>::max();
270 std::size_t
const start_idx = (is_time_dep) ? 1 : 0;
271 std::array<std::string, 4>
const dim_comment{
272 "(x / longitude)",
"(y / latitude)",
"(z / height / depth)",
273 "[Error: 4-dimensional non-temporal arrays are not supported]"};
274 for (std::size_t i = start_idx; i < n_dims; ++i)
276 dim_idx_map[i] = std::numeric_limits<std::size_t>::max();
278 std::string
const request_str(
"Enter ID for dimension " +
279 std::to_string(i) +
" " +
280 dim_comment[i - start_idx] +
": ");
281 std::size_t
const idx =
282 parseInput(request_str, var.getDimCount(),
true);
284 if (
static_cast<int>(idx) == var.getDimCount())
290 dim_idx_map[i] = idx;
297 NcVar
const& var, std::size_t
const dim_idx)
299 std::size_t
const n_time_steps = var.getDim(dim_idx).getSize();
300 std::size_t
const max_val = std::numeric_limits<std::size_t>::max();
301 std::pair<std::size_t, std::size_t> bounds(max_val, max_val);
302 std::cout <<
"\nThe dataset contains " << n_time_steps <<
" time steps.\n";
303 while (bounds.first == max_val)
306 "Specify first time step to export: ", n_time_steps,
false);
308 while (bounds.first > bounds.second || bounds.second > n_time_steps)
311 "Specify last time step to export: ", n_time_steps,
false);
324 std::cout <<
"\nSelect element type for result, choose ";
327 std::cout <<
"(t)riangle or (q)uadliteral: ";
329 std::cout <<
"(p)rism or (h)exahedron: ";
330 std::string type(
"");
331 std::getline(std::cin, type);
335 if (type !=
"t" && type !=
"q" && type !=
"tri" && type !=
"quad" &&
336 type !=
"triangle" && type !=
"quatliteral")
338 if (type ==
"t" || type ==
"tri" || type ==
"triangle")
345 if (type !=
"p" && type !=
"h" && type !=
"prism" &&
346 type !=
"hex" && type !=
"hexahedron")
348 if (type ==
"p" || type ==
"prism")
357 std::pair<std::size_t, std::size_t>
const& time_bounds)
362 std::size_t
const n_time_steps(time_bounds.second - time_bounds.first +
364 std::cout <<
"\nThe selection includes " << n_time_steps
366 std::cout <<
"0. Save data in " << n_time_steps
367 <<
" mesh files with one scalar array each.\n";
368 std::cout <<
"1. Save data in one mesh file with " << n_time_steps
369 <<
" scalar arrays.\n";
370 std::cout <<
"2. Save data as " << n_time_steps <<
" ASC images.\n";
372 std::size_t
const ret =
373 parseInput(
"Select preferred method: ", 3,
false);
387 std::size_t
const max_length(std::to_string(max).length());
388 std::string
const current_str(std::to_string(i));
389 return std::string(max_length - current_str.length(),
'0') + current_str;
394 std::size_t
const dim_idx = var.getDimCount() - 1;
395 NcVar
const dim_var(
getDimVar(dataset, var, dim_idx));
396 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, dim_idx)
398 std::size_t
const dim_size = var.getDim(dim_idx).getSize();
401 OGS_FATAL(
"Dimension '{:s}' has size 0. Aborting...",
402 var.getDim(dim_idx).getName());
404 return std::fabs(bounds.second - bounds.first) /
405 static_cast<double>(dim_size);
409 NcFile
const& dataset, NcVar
const& var,
410 std::vector<std::size_t>
const& dim_idx_map,
411 std::vector<std::size_t>
const& length, std::size_t
const time_offset)
414 getOrigin(dataset, var, dim_idx_map, time_offset);
416 std::size_t n_dims = var.getDimCount();
417 std::size_t z_length =
418 (n_dims - time_offset == 3) ? length[dim_idx_map.back()] : 1;
419 return {length[dim_idx_map[0 + time_offset]],
420 length[dim_idx_map[1 + time_offset]],
427static std::vector<std::size_t>
getLength(NcVar
const& var,
428 std::size_t
const time_offset)
430 std::size_t
const n_dims = (var.getDimCount());
431 std::vector<std::size_t> length(n_dims, 1);
432 for (std::size_t i = time_offset; i < n_dims; ++i)
434 length[i] = var.getDim(i).getSize();
439static std::vector<double>
getData(NcVar
const& var,
440 std::size_t
const total_length,
441 std::size_t
const time_step,
442 std::vector<std::size_t>
const& length)
444 std::size_t
const n_dims(var.getDimCount());
445 std::vector<std::size_t> offset(n_dims, 0);
446 offset[0] = time_step;
447 std::vector<double> data_vec(total_length, 0);
448 var.getVar(offset, length, data_vec.data());
451 data_vec.begin(), data_vec.end(),
452 [](
double const& x) { return x == no_data_input; },
no_data_output);
458 std::vector<std::size_t>& dim_idx_map,
459 TCLAP::ValueArg<std::size_t>& arg_dim_time,
460 TCLAP::ValueArg<std::size_t>& arg_dim1,
461 TCLAP::ValueArg<std::size_t>& arg_dim2,
462 TCLAP::ValueArg<std::size_t>& arg_dim3)
464 std::size_t dim_param_count = 0;
465 if (arg_dim_time.isSet())
467 if (arg_dim1.isSet())
469 if (arg_dim2.isSet())
471 if (arg_dim3.isSet())
474 std::size_t
const n_dims = var.getDimCount();
475 if (dim_param_count != n_dims)
477 ERR(
"Number of parameters set does not fit number of parameters for "
478 "specified variable.");
482 if (arg_dim_time.getValue() >= n_dims || arg_dim1.getValue() >= n_dims ||
483 arg_dim2.getValue() >= n_dims || arg_dim3.getValue() >= n_dims)
485 ERR(
"Maximum allowed dimension for variable \"{:s}\" is {:d}.",
486 var.getName(), n_dims - 1);
490 if (arg_dim_time.isSet())
491 dim_idx_map[0] = arg_dim_time.getValue();
492 std::size_t
const temp_offset = (arg_dim_time.isSet()) ? 1 : 0;
493 dim_idx_map[0 + temp_offset] = arg_dim1.getValue();
494 dim_idx_map[1 + temp_offset] = arg_dim2.getValue();
495 if (n_dims == (3 + temp_offset))
496 dim_idx_map[2 + temp_offset] = arg_dim3.getValue();
503 TCLAP::ValueArg<std::size_t>& arg_time_start,
504 TCLAP::ValueArg<std::size_t>& arg_time_end)
507 if (arg_time_start.getValue() > bounds.second)
509 ERR(
"Start time step larger than total number of time steps. Resetting "
511 arg_time_start.reset();
514 if (!arg_time_end.isSet())
515 return {arg_time_start.getValue(), arg_time_start.getValue()};
517 if (arg_time_end.getValue() > bounds.second)
519 ERR(
"End time step larger than total number of time steps. Resetting "
520 "to starting time step");
521 return {arg_time_start.getValue(), arg_time_start.getValue()};
524 if (arg_time_end.getValue() < arg_time_start.getValue())
526 ERR(
"End time step larger than starting time step. Swapping values");
527 return {arg_time_end.getValue(), arg_time_start.getValue()};
530 return {arg_time_start.getValue(), arg_time_end.getValue()};
534 TCLAP::ValueArg<std::string>& arg_elem_type)
536 if (arg_elem_type.getValue() ==
"tri")
538 if (arg_elem_type.getValue() ==
"quad")
540 if (arg_elem_type.getValue() ==
"prism")
542 if (arg_elem_type.getValue() ==
"hex")
548static bool convert(NcFile
const& dataset, NcVar
const& var,
549 std::string
const& output_name,
550 std::vector<std::size_t>
const& dim_idx_map,
551 std::size_t
const time_offset,
552 std::pair<std::size_t, std::size_t>
const& time_bounds,
556 std::unique_ptr<MeshLib::Mesh> mesh;
557 std::vector<std::size_t>
const length =
getLength(var, time_offset);
558 std::size_t
const array_length = std::accumulate(
559 length.cbegin(), length.cend(), 1, std::multiplies<std::size_t>());
560 for (std::size_t i = time_bounds.first; i <= time_bounds.second; ++i)
562 std::string
const step_str =
563 (time_bounds.first != time_bounds.second)
564 ? std::string(
" time step " + std::to_string(i))
566 std::cout <<
"Converting" << step_str <<
"...\n";
567 std::vector<double> data_vec =
getData(var, array_length, i, length);
571 std::size_t
const n_dims = length.size();
572 NcVar
const dim_var(
getDimVar(dataset, var, n_dims - 2));
573 auto const bounds = (dim_var.isNull()) ?
getDimLength(var, n_dims - 2)
575 if (bounds.first > bounds.second)
577 std::size_t n_layers =
578 (length.size() - time_offset == 3) ? length[n_dims - 3] : 1;
579 flipRaster(data_vec, n_layers, length[n_dims - 1],
590 elem_type, useIntensity,
592 std::string
const output_file_name(
600 std::string array_name(var.getName());
601 if (time_bounds.first != time_bounds.second)
603 if (i == time_bounds.first)
605 data_vec.data(), header, elem_type, useIntensity,
609 std::unique_ptr<MeshLib::Mesh>
const temp(
611 elem_type, useIntensity,
614 temp->getProperties().getPropertyVector<
double>(array_name);
620 if (i == time_bounds.second)
623 std::string
const output_file_name =
626 : output_name +
".vtu";
633 data_vec.data() + header.
n_cols *
636 std::string
const output_file_name(
646int main(
int argc,
char* argv[])
649 "Converts NetCDF data into mesh file(s).\n\n "
650 "OpenGeoSys-6 software, version " +
653 "Copyright (c) 2012-2024, OpenGeoSys Community "
654 "(http://www.opengeosys.org)",
657 TCLAP::ValueArg<int> arg_nodata(
659 "explicitly specifies the no data value used in the dataset (usually "
660 "it is not necessary to set this)",
664 std::vector<std::string> allowed_elems{
"tri",
"quad",
"prism",
"hex"};
665 TCLAP::ValuesConstraint<std::string> allowed_elem_vals(allowed_elems);
666 TCLAP::ValueArg<std::string> arg_elem_type(
667 "e",
"elem-type",
"the element type used in the resulting OGS mesh",
668 false,
"", &allowed_elem_vals);
669 cmd.add(arg_elem_type);
671 TCLAP::SwitchArg arg_images(
673 "if set, all time steps will be written as ESRI image files (*.asc)");
676 TCLAP::SwitchArg arg_multi_files(
678 "if set, each time step will be written to a separate mesh file");
679 cmd.add(arg_multi_files);
681 TCLAP::SwitchArg arg_single_file(
683 "if set, all time steps will be written to a single mesh file (with "
684 "one scalar array per time step)");
685 cmd.add(arg_single_file);
687 TCLAP::ValueArg<std::size_t> arg_time_end(
689 "last time step to be extracted (only for time-dependent variables!)",
690 false, 0,
"integer specifying index of time step");
691 cmd.add(arg_time_end);
693 TCLAP::ValueArg<std::size_t> arg_time_start(
694 "",
"timestep-first",
695 "first time step to be extracted (only for time-dependent variables!)",
696 false, 0,
"integer specifying index of time step");
697 cmd.add(arg_time_start);
699 std::vector<std::size_t> allowed_dims{0, 1, 2, 3};
700 TCLAP::ValuesConstraint<std::size_t> allowed_dim_vals(allowed_dims);
701 TCLAP::ValueArg<std::size_t> arg_dim3(
703 "index of third dimension (z/height/depth) for the selected variable",
704 false, 0, &allowed_dim_vals);
707 TCLAP::ValueArg<std::size_t> arg_dim2(
709 "index of second dimension (y/latitude) for the selected variable",
710 false, 0, &allowed_dim_vals);
713 TCLAP::ValueArg<std::size_t> arg_dim1(
715 "index of first dimension (x/longitude) for the selected variable",
716 false, 0, &allowed_dim_vals);
719 TCLAP::ValueArg<std::size_t> arg_dim_time(
721 "index of the time-dependent dimension for the selected variable",
722 false, 0, &allowed_dim_vals);
723 cmd.add(arg_dim_time);
725 TCLAP::ValueArg<std::string> arg_varname(
726 "v",
"var",
"variable included in the the netCDF file",
false,
"",
727 "string containing the variable name");
728 cmd.add(arg_varname);
730 TCLAP::ValueArg<std::string> arg_output(
731 "o",
"output",
"the OGS mesh output file",
true,
"",
732 "string containing the path and file name");
734 TCLAP::ValueArg<std::string> arg_input(
735 "i",
"input",
"the netCDF input file",
true,
"",
736 "string containing the path and file name");
738 cmd.parse(argc, argv);
742 NcFile dataset(arg_input.getValue().c_str(), NcFile::read);
744 if (dataset.isNull())
746 ERR(
"Error opening file.");
750 std::size_t
const mutex =
751 arg_single_file.isSet() + arg_multi_files.isSet() + arg_images.isSet();
754 ERR(
"Only one output format can be specified (single-file, multi-file, "
759 std::cout <<
"OpenGeoSys NetCDF Converter\n";
760 if (!arg_varname.isSet())
762 std::cout <<
"File " << arg_input.getValue()
763 <<
" loaded. Press ENTER to display available data arrays.\n";
767 std::string
const& output_name(arg_output.getValue());
768 std::string
const& var_name = (arg_varname.isSet())
769 ? arg_varname.getValue()
771 NcVar
const& var = dataset.getVar(var_name);
774 ERR(
"Variable \"{:s}\" not found in file.", arg_varname.getValue());
778 std::vector<std::size_t> dim_idx_map(var.getDimCount(), 0);
779 bool is_time_dep(
false);
780 if (arg_dim1.isSet() && arg_dim2.isSet())
782 is_time_dep = arg_dim_time.isSet();
783 if (!
assignDimParams(var, dim_idx_map, arg_dim_time, arg_dim1, arg_dim2,
794 std::pair<std::size_t, std::size_t> time_bounds(0, 0);
797 (arg_time_start.isSet())
799 arg_time_start, arg_time_end)
803 if (arg_images.isSet())
807 else if (arg_multi_files.isSet())
811 else if (arg_single_file.isSet() || !is_time_dep ||
812 time_bounds.first == time_bounds.second)
821 std::size_t
const temp_offset = (is_time_dep) ? 1 : 0;
822 std::size_t
const n_dims = (var.getDimCount());
827 elem_type = (arg_elem_type.isSet())
834 if (arg_nodata.isSet())
839 if (!
convert(dataset, var, output_name, dim_idx_map, is_time_dep,
840 time_bounds, output, elem_type))
845 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.
void addPropertyToMesh(Mesh &mesh, std::string_view name, MeshItemType item_type, std::size_t number_of_components, std::vector< T > const &values)