OGS
XmlPrjInterface.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: Copyright (c) OpenGeoSys Community (opengeosys.org)
2// SPDX-License-Identifier: BSD-3-Clause
3
4#include "XmlPrjInterface.h"
5
6#include <QFile>
7#include <QFileInfo>
8#include <QtXml/QDomDocument>
9#include <iostream>
10#include <vector>
11
14#include "BaseLib/FileTools.h"
15#include "BaseLib/IO/Writer.h"
16#include "BaseLib/Logging.h"
17#include "GeoLib/GEOObjects.h"
22#include "MeshLib/Mesh.h"
23
24namespace FileIO
25{
27 : XMLQtInterface("OpenGeoSysProject.xsd"), _filename(""), _project(project)
28{
29}
30
31int XmlPrjInterface::readFile(const QString& fileName)
32{
33 if (XMLQtInterface::readFile(fileName) == 0)
34 {
35 return 0;
36 }
37
38 QFileInfo fi(fileName);
39 QString path =
40 (fi.path().length() > 3) ? QString(fi.path() + "/") : fi.path();
41
42 QDomNode param_root = QDomNode();
43 QDomNode pvar_root = QDomNode();
44 QDomDocument doc("OGS-PROJECT-DOM");
45 doc.setContent(getContent());
46 QDomElement docElement = doc.documentElement(); // OpenGeoSysProject
47 if (docElement.nodeName().compare("OpenGeoSysProject"))
48 {
49 ERR("XmlPrjInterface::readFile(): Unexpected XML root.");
50 return 0;
51 }
52
53 auto read_single_mesh = [&](QString const& mesh_str)
54 {
55 std::unique_ptr<MeshLib::Mesh> mesh{
56 MeshLib::IO::readMeshFromFile(mesh_str.toStdString())};
57 if (mesh != nullptr)
58 {
59 _project.addMesh(std::move(mesh));
60 }
61 };
62
63 QDomNodeList fileList = docElement.childNodes();
64
65 for (int i = 0; i < fileList.count(); i++)
66 {
67 QDomNode const node(fileList.at(i));
68 QString const node_name(node.nodeName());
69 QString const file_name(node.toElement().text().trimmed());
70 if (file_name.isEmpty())
71 {
72 continue;
73 }
74
75 if (node_name == "geometry")
76 {
77 GeoLib::IO::XmlGmlInterface gml(_project.getGEOObjects());
78 try
79 {
80 gml.readFile(QString(path + file_name));
81 }
82 catch (std::runtime_error const& err)
83 {
84 OGSError::box(err.what(),
85 "Failed to read file `" + fileName + "'");
86 }
87 }
88 else if (node_name == "stations")
89 {
90 GeoLib::IO::XmlStnInterface stn(_project.getGEOObjects());
91 stn.readFile(QString(path + file_name));
92 }
93 else if (node_name == "mesh")
94 {
95 read_single_mesh(path + file_name);
96 }
97 else if (node_name == "meshes")
98 {
99 for (QDomNode meshes_node = node.firstChild();
100 meshes_node != QDomNode();
101 meshes_node = meshes_node.nextSibling())
102 {
103 if (!meshes_node.isElement())
104 {
105 ERR("Expected an XML element node.");
106 return 0;
107 }
108 if (meshes_node.nodeName() != "mesh")
109 {
110 ERR("Expected an XML element node named 'mesh' got '{:s}'.",
111 meshes_node.nodeName().toStdString());
112 return 0;
113 }
114 if (meshes_node.childNodes().count() != 1)
115 {
116 ERR("Expected an XML element node named 'mesh' to contain "
117 "exactly one child node but it has {:d} children.",
118 meshes_node.childNodes().count());
119 return 0;
120 }
121 QDomNode node_text = meshes_node.firstChild();
122 if (!node_text.isText())
123 {
124 ERR("Expected an XML element node named 'mesh' to contain "
125 "text.");
126 return 0;
127 }
128 read_single_mesh(path + node_text.toText().data().trimmed());
129 }
130 }
131
132 else if (node_name == "parameters")
133 {
134 param_root = node;
135 }
136 else if (node_name == "process_variables")
137 {
138 pvar_root = node;
139 }
140 }
141
142 if (param_root != QDomNode() && pvar_root != QDomNode())
143 {
144 readConditions(pvar_root, param_root);
145 }
146 else
147 INFO("Skipping process variables");
148
149 return 1;
150}
151
152QDomNode XmlPrjInterface::findParam(QDomNode const& param_root,
153 QString const& param_name) const
154{
155 QDomNode param = param_root.firstChild();
156
157 while (param != QDomNode())
158 {
159 QDomNodeList nodeList = param.childNodes();
160 for (int i = 0; i < nodeList.count(); i++)
161 {
162 QDomNode node = nodeList.at(i);
163 // std::cout << node.nodeName().toStdString() <<
164 // node.toElement().text().toStdString() << std::endl;
165 if (node.nodeName() == "name" &&
166 node.toElement().text() == param_name)
167 {
168 return node;
169 }
170 }
171 param = param.nextSibling();
172 }
173 return QDomNode();
174}
175
176void XmlPrjInterface::readConditions(QDomNode const& pvar_root,
177 QDomNode const& param_root)
178{
179 QDomNode pvar = pvar_root.firstChild();
180 while (pvar != QDomNode())
181 {
183 QDomNodeList nodeList = pvar.childNodes();
184 for (int i = 0; i < nodeList.count(); i++)
185 {
186 QDomNode const node = nodeList.at(i);
187 QString const node_name = node.nodeName();
188 if (node_name == "name")
189 {
190 process_var.name = node.toElement().text().toStdString();
191 }
192 else if (node_name == "components")
193 {
194 process_var.components = node.toElement().text().toInt();
195 }
196 else if (node_name == "order")
197 {
198 process_var.order = node.toElement().text().toInt();
199 }
200 else if (node_name == "boundary_conditions")
201 {
202 readBoundaryConditions(node, param_root, process_var);
203 }
204 else if (node_name == "source_terms")
205 {
206 readSourceTerms(node, param_root, process_var);
207 }
208 }
209 pvar = pvar.nextSibling();
210 }
211}
212
214 QDomNode const& bc_root,
215 QDomNode const& param_root,
217{
218 QDomNode bc = bc_root.firstChild();
219 while (bc != QDomNode())
220 {
221 std::unique_ptr<DataHolderLib::BoundaryCondition> cond(
223 pvar));
224 if (cond->getType() !=
226 {
227 _project.addBoundaryCondition(std::move(cond));
228 }
229
230 bc = bc.nextSibling();
231 }
232}
233
235 QDomNode const& st_root,
236 QDomNode const& param_root,
238{
239 QDomNode st = st_root.firstChild();
240 while (st != QDomNode())
241 {
242 std::unique_ptr<DataHolderLib::SourceTerm> cond(
243 parseCondition<DataHolderLib::SourceTerm>(st, param_root, pvar));
245 {
246 _project.addSourceTerm(std::move(cond));
247 }
248 st = st.nextSibling();
249 }
250}
251
252template <typename T>
254 QDomNode const& node,
255 QDomNode const& param_root,
256 DataHolderLib::ProcessVariable const& pvar) const
257{
258 DataHolderLib::BaseObjType base_obj_type =
260 typename T::ConditionType type = T::ConditionType::NONE;
261 std::string base_obj_name;
262 std::string obj_name;
263 std::string param_name;
264 QDomNode param_node = QDomNode();
265 QDomNodeList nodeList = node.childNodes();
266 for (int i = 0; i < nodeList.count(); i++)
267 {
268 QString const node_name = nodeList.at(i).nodeName();
269 QString const content = nodeList.at(i).toElement().text().trimmed();
270 if (node_name == "geometrical_set" &&
271 base_obj_type != DataHolderLib::BaseObjType::MESH)
272 {
273 base_obj_name = content.toStdString();
274 }
275 else if (node_name == "geometry" &&
276 base_obj_type != DataHolderLib::BaseObjType::MESH)
277 {
278 obj_name = content.toStdString();
279 }
280 else if (node_name == "type")
281 {
282 type = T::convertStringToType(content.toStdString());
283 }
284 else if (node_name == "mesh")
285 {
286 base_obj_type = DataHolderLib::BaseObjType::MESH;
287 base_obj_name = content.toStdString();
288 obj_name.clear();
289 }
290 else if (node_name == "field_name")
291 {
292 param_name = content.toStdString();
293 }
294 else if (node_name == "parameter")
295 {
296 QDomNode val = findParam(param_root, content);
297 if (val == QDomNode())
298 {
299 continue;
300 }
301 param_name = content.toStdString();
302 param_node = nodeList.at(i);
303 }
304 }
305
306 if (!param_name.empty())
307 {
308 T* cond = new T(pvar, param_name, type);
309 if (base_obj_type == DataHolderLib::BaseObjType::MESH)
310 {
311 cond->setMesh(base_obj_name);
312 }
313 else
314 {
315 cond->setGeoObject(base_obj_name, obj_name);
316 }
317
318 return cond;
319 }
320 return new T({"", 0, 0}, "", T::ConditionType::NONE);
321}
322
323int XmlPrjInterface::writeToFile(const std::string& filename)
324{
325 _filename = filename;
327}
328
330{
331 GeoLib::GEOObjects& geo_objects = _project.getGEOObjects();
332 QFileInfo fi(QString::fromStdString(_filename));
333 std::string path((fi.absolutePath()).toStdString() + "/");
334
335 out << "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"; // xml
336 // definition
337 out << "<?xml-stylesheet type=\"text/xsl\" "
338 "href=\"OpenGeoSysProject.xsl\"?>\n\n"; // stylefile definition
339
340 QDomDocument doc("OGS-PROJECT-DOM");
341 QDomElement root = doc.createElement("OpenGeoSysProject");
342 root.setAttribute("xmlns:ogs", "http://www.opengeosys.org");
343 root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
344
345 doc.appendChild(root);
346
347 // meshes
348 auto const& mesh_vector = _project.getMeshObjects();
349 for (auto const& mesh : mesh_vector)
350 {
351 // write mesh file
353 path + mesh->getName() + ".vtu") != 0)
354 {
355 return false;
356 }
357
358 // write entry in project file
359 QDomElement mesh_tag = doc.createElement("mesh");
360 root.appendChild(mesh_tag);
361 QDomText filename_text =
362 doc.createTextNode(QString::fromStdString(mesh->getName()));
363 mesh_tag.appendChild(filename_text);
364 }
365
366 // geometries
367 for (std::string const& name : geo_objects.getGeometryNames())
368 {
369 // write gml file
370 GeoLib::IO::XmlGmlInterface gml(geo_objects);
371 gml.export_name = name;
373 std::string(path + name + ".gml")))
374 {
375 // write entry in project file
376 QDomElement geo_tag = doc.createElement("geometry");
377 root.appendChild(geo_tag);
378 QDomText filename_text =
379 doc.createTextNode(QString::fromStdString(name + ".gml"));
380 geo_tag.appendChild(filename_text);
381 }
382 else
383 ERR("XmlGmlInterface::writeFile(): Error writing gml-file '{:s}'.",
384 name);
385 }
386
387 // stations
388 std::vector<std::string> stn_names;
389 geo_objects.getStationVectorNames(stn_names);
390 for (std::string const& name : stn_names)
391 {
392 // write station file
393 GeoLib::IO::XmlStnInterface stn(geo_objects);
394 stn.export_name = name;
395
397 path + name + ".stn"))
398 {
399 // write entry in project file
400 QDomElement stn_tag = doc.createElement("stations");
401 root.appendChild(stn_tag);
402 QDomText filename_text =
403 doc.createTextNode(QString::fromStdString(name + ".stn"));
404 stn_tag.appendChild(filename_text);
405 }
406 else
407 ERR("XmlStnInterface::writeFile(): Error writing stn-file '{:s}'.",
408 name);
409 }
410
411 if (!_project.getBoundaryConditions().empty() ||
412 !_project.getSourceTerms().empty())
413 {
414 // parameters
415 writeProcessVariables(doc, root);
416 }
417
418 std::string xml = doc.toString().toStdString();
419 out << xml;
420 return true;
421}
422
423void addTextNode(QDomDocument& doc,
424 QDomElement& parent,
425 QString const& node_name,
426 QString const& content)
427{
428 QDomElement tag = doc.createElement(node_name);
429 parent.appendChild(tag);
430 QDomText order_text = doc.createTextNode(content);
431 tag.appendChild(order_text);
432}
433
434bool PVarExists(std::string const& name,
435 std::vector<DataHolderLib::ProcessVariable> const& p_vars)
436{
437 return std::any_of(p_vars.begin(), p_vars.end(),
438 [&](auto const& p_var) { return p_var.name == name; });
439}
440
441std::vector<DataHolderLib::ProcessVariable>
443{
444 std::vector<std::unique_ptr<DataHolderLib::BoundaryCondition>> const&
445 boundary_conditions = _project.getBoundaryConditions();
446 std::vector<std::unique_ptr<DataHolderLib::SourceTerm>> const&
447 source_terms = _project.getSourceTerms();
448
449 std::vector<DataHolderLib::ProcessVariable> p_vars;
450 for (auto& bc : boundary_conditions)
451 {
452 DataHolderLib::ProcessVariable const& pvar(bc->getProcessVar());
453 if (!PVarExists(pvar.name, p_vars))
454 {
455 p_vars.push_back(pvar);
456 }
457 }
458
459 for (auto& st : source_terms)
460 {
461 DataHolderLib::ProcessVariable const& pvar(st->getProcessVar());
462 if (!PVarExists(pvar.name, p_vars))
463 {
464 p_vars.push_back(pvar);
465 }
466 }
467 return p_vars;
468}
469
470template <typename T>
472 QDomDocument& doc,
473 QDomElement& tag,
474 DataHolderLib::FemCondition const& cond) const
475{
477 {
478 addTextNode(doc,
479 tag,
480 "geometrical_set",
481 QString::fromStdString(cond.getBaseObjName()));
482 addTextNode(doc, tag, "geometry",
483 QString::fromStdString(cond.getObjName()));
484 addTextNode(doc,
485 tag,
486 "type",
487 QString::fromStdString(T::convertTypeToString(
488 static_cast<T const&>(cond).getType())));
489 addTextNode(doc, tag, "parameter",
490 QString::fromStdString(cond.getParamName()));
491 }
493 {
494 addTextNode(doc,
495 tag,
496 "type",
497 QString::fromStdString(T::convertTypeToString(
498 static_cast<T const&>(cond).getType())));
499 addTextNode(doc, tag, "mesh",
500 QString::fromStdString(cond.getBaseObjName()));
501 addTextNode(doc,
502 tag,
503 "field_name",
504 QString::fromStdString(cond.getParamName()));
505 }
506}
507
509 QDomElement& bc_list_tag,
510 std::string const& name) const
511{
512 std::vector<std::unique_ptr<DataHolderLib::BoundaryCondition>> const&
513 boundary_conditions = _project.getBoundaryConditions();
514 for (auto& bc : boundary_conditions)
515 {
516 if (bc->getProcessVarName() != name)
517 {
518 continue;
519 }
520 QDomElement bc_tag = doc.createElement("boundary_condition");
521 bc_list_tag.appendChild(bc_tag);
523 }
524}
525
527 QDomElement& st_list_tag,
528 std::string const& name) const
529{
530 std::vector<std::unique_ptr<DataHolderLib::SourceTerm>> const&
531 source_terms = _project.getSourceTerms();
532 for (auto& st : source_terms)
533 {
534 if (st->getProcessVarName() != name)
535 {
536 continue;
537 }
538 QDomElement st_tag = doc.createElement("source_term");
539 st_list_tag.appendChild(st_tag);
541 }
542}
543
545 QDomElement& root) const
546{
547 std::vector<DataHolderLib::ProcessVariable> const p_vars(
549
550 QDomElement param_list_tag = doc.createElement("parameters");
551 root.appendChild(param_list_tag);
552
553 QDomElement pvar_list_tag = doc.createElement("process_variables");
554 root.appendChild(pvar_list_tag);
555
556 for (DataHolderLib::ProcessVariable const& p_var : p_vars)
557 {
558 QDomElement pvar_tag = doc.createElement("process_variable");
559 pvar_list_tag.appendChild(pvar_tag);
560 addTextNode(doc, pvar_tag, "name", QString::fromStdString(p_var.name));
561 addTextNode(doc, pvar_tag, "order", QString::number(p_var.order));
562 addTextNode(doc, pvar_tag, "components",
563 QString::number(p_var.components));
564 QDomElement bc_list_tag = doc.createElement("boundary_conditions");
565 pvar_tag.appendChild(bc_list_tag);
566 writeBoundaryConditions(doc, bc_list_tag, p_var.name);
567 QDomElement st_list_tag = doc.createElement("source_terms");
568 pvar_tag.appendChild(st_list_tag);
569 writeSourceTerms(doc, st_list_tag, p_var.name);
570 }
571}
572} // namespace FileIO
void INFO(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:28
void ERR(fmt::format_string< Args... > fmt, Args &&... args)
Definition Logging.h:40
std::ostringstream out
The stream to write to.
Definition Writer.h:36
std::string writeToString()
Writes the object to a string.
Definition Writer.cpp:20
QByteArray const & getContent() const
XMLQtInterface(QString schemaFile="")
Base class for boundary conditions, initial conditions and source terms.
std::string getBaseObjName() const
Returns the name of the base object (i.e. geometry or mesh)
BaseObjType getBaseObjType() const
Specifies if the condition is set a geometry or on a mesh.
std::string const getObjName() const
Returns the name of the geometric object.
std::string const getParamName() const
Returns the name of the parameter associated with the condition.
void readBoundaryConditions(QDomNode const &bc_root, QDomNode const &param_root, DataHolderLib::ProcessVariable const &pvar)
Reading all boundary conditions.
T * parseCondition(QDomNode const &node, QDomNode const &param_root, DataHolderLib::ProcessVariable const &pvar) const
Parsing one specific condition.
int writeToFile(const std::string &filename)
Writes a project to the specified file.
std::vector< DataHolderLib::ProcessVariable > getPrimaryVariableVec() const
Compiles a vector of all existing primary variables for writing purposes.
bool write() override
Writes the object to the internal stream. This method must be implemented by a subclass....
void writeSourceTerms(QDomDocument &doc, QDomElement &st_list_tag, std::string const &name) const
Writes a list of source terms.
void readSourceTerms(QDomNode const &st_root, QDomNode const &param_root, DataHolderLib::ProcessVariable const &pvar)
Reading all source terms.
int readFile(const QString &fileName) override
Reads an xml-file containing a project.
void writeProcessVariables(QDomDocument &doc, QDomElement &root) const
Writes information on process variables.
DataHolderLib::Project & _project
void writeCondition(QDomDocument &doc, QDomElement &tag, DataHolderLib::FemCondition const &cond) const
Writes one specific condition.
void writeBoundaryConditions(QDomDocument &doc, QDomElement &bc_list_tag, std::string const &name) const
Writes a list of boundary conditions.
XmlPrjInterface(DataHolderLib::Project &project)
void readConditions(QDomNode const &pvar_root, QDomNode const &param_root)
Manages reading all kinds of conditions.
QDomNode findParam(QDomNode const &param_root, QString const &param_name) const
Tests if a given parameter exists within the file.
Container class for geometric objects.
Definition GEOObjects.h:46
std::vector< std::string > getGeometryNames() const
Returns the names of all geometry vectors.
void getStationVectorNames(std::vector< std::string > &names) const
Returns the names of all station vectors.
Reads and writes GeoObjects to and from XML files.
int readFile(const QString &fileName) override
Reads an xml-file containing geometric object definitions into the GEOObjects used in the constructor...
Reads and writes Observation Sites to and from XML files.
int readFile(const QString &fileName) override
Reads an xml-file containing station object definitions into the GEOObjects used in the constructor (...
static void box(const QString &e)
Definition OGSError.cpp:13
int writeStringToFile(std::string_view content, std::filesystem::path const &file_path)
Definition Writer.cpp:34
void addTextNode(QDomDocument &doc, QDomElement &parent, QString const &node_name, QString const &content)
bool PVarExists(std::string const &name, std::vector< DataHolderLib::ProcessVariable > const &p_vars)
MeshLib::Mesh * readMeshFromFile(const std::string &file_name, bool const compute_element_neighbors)
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)