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
352 MeshLib::IO::writeMeshToFile(*mesh, path + mesh->getName() + ".vtu");
353
354 // write entry in project file
355 QDomElement mesh_tag = doc.createElement("mesh");
356 root.appendChild(mesh_tag);
357 QDomText filename_text =
358 doc.createTextNode(QString::fromStdString(mesh->getName()));
359 mesh_tag.appendChild(filename_text);
360 }
361
362 // geometries
363 for (std::string const& name : geo_objects.getGeometryNames())
364 {
365 // write gml file
366 GeoLib::IO::XmlGmlInterface gml(geo_objects);
367 gml.export_name = name;
369 std::string(path + name + ".gml")))
370 {
371 // write entry in project file
372 QDomElement geo_tag = doc.createElement("geometry");
373 root.appendChild(geo_tag);
374 QDomText filename_text =
375 doc.createTextNode(QString::fromStdString(name + ".gml"));
376 geo_tag.appendChild(filename_text);
377 }
378 else
379 ERR("XmlGmlInterface::writeFile(): Error writing gml-file '{:s}'.",
380 name);
381 }
382
383 // stations
384 std::vector<std::string> stn_names;
385 geo_objects.getStationVectorNames(stn_names);
386 for (std::string const& name : stn_names)
387 {
388 // write station file
389 GeoLib::IO::XmlStnInterface stn(geo_objects);
390 stn.export_name = name;
391
393 path + name + ".stn"))
394 {
395 // write entry in project file
396 QDomElement stn_tag = doc.createElement("stations");
397 root.appendChild(stn_tag);
398 QDomText filename_text =
399 doc.createTextNode(QString::fromStdString(name + ".stn"));
400 stn_tag.appendChild(filename_text);
401 }
402 else
403 ERR("XmlStnInterface::writeFile(): Error writing stn-file '{:s}'.",
404 name);
405 }
406
407 if (!_project.getBoundaryConditions().empty() ||
408 !_project.getSourceTerms().empty())
409 {
410 // parameters
411 writeProcessVariables(doc, root);
412 }
413
414 std::string xml = doc.toString().toStdString();
415 out << xml;
416 return true;
417}
418
419void addTextNode(QDomDocument& doc,
420 QDomElement& parent,
421 QString const& node_name,
422 QString const& content)
423{
424 QDomElement tag = doc.createElement(node_name);
425 parent.appendChild(tag);
426 QDomText order_text = doc.createTextNode(content);
427 tag.appendChild(order_text);
428}
429
430bool PVarExists(std::string const& name,
431 std::vector<DataHolderLib::ProcessVariable> const& p_vars)
432{
433 return std::any_of(p_vars.begin(), p_vars.end(),
434 [&](auto const& p_var) { return p_var.name == name; });
435}
436
437std::vector<DataHolderLib::ProcessVariable>
439{
440 std::vector<std::unique_ptr<DataHolderLib::BoundaryCondition>> const&
441 boundary_conditions = _project.getBoundaryConditions();
442 std::vector<std::unique_ptr<DataHolderLib::SourceTerm>> const&
443 source_terms = _project.getSourceTerms();
444
445 std::vector<DataHolderLib::ProcessVariable> p_vars;
446 for (auto& bc : boundary_conditions)
447 {
448 DataHolderLib::ProcessVariable const& pvar(bc->getProcessVar());
449 if (!PVarExists(pvar.name, p_vars))
450 {
451 p_vars.push_back(pvar);
452 }
453 }
454
455 for (auto& st : source_terms)
456 {
457 DataHolderLib::ProcessVariable const& pvar(st->getProcessVar());
458 if (!PVarExists(pvar.name, p_vars))
459 {
460 p_vars.push_back(pvar);
461 }
462 }
463 return p_vars;
464}
465
466template <typename T>
468 QDomDocument& doc,
469 QDomElement& tag,
470 DataHolderLib::FemCondition const& cond) const
471{
473 {
474 addTextNode(doc,
475 tag,
476 "geometrical_set",
477 QString::fromStdString(cond.getBaseObjName()));
478 addTextNode(doc, tag, "geometry",
479 QString::fromStdString(cond.getObjName()));
480 addTextNode(doc,
481 tag,
482 "type",
483 QString::fromStdString(T::convertTypeToString(
484 static_cast<T const&>(cond).getType())));
485 addTextNode(doc, tag, "parameter",
486 QString::fromStdString(cond.getParamName()));
487 }
489 {
490 addTextNode(doc,
491 tag,
492 "type",
493 QString::fromStdString(T::convertTypeToString(
494 static_cast<T const&>(cond).getType())));
495 addTextNode(doc, tag, "mesh",
496 QString::fromStdString(cond.getBaseObjName()));
497 addTextNode(doc,
498 tag,
499 "field_name",
500 QString::fromStdString(cond.getParamName()));
501 }
502}
503
505 QDomElement& bc_list_tag,
506 std::string const& name) const
507{
508 std::vector<std::unique_ptr<DataHolderLib::BoundaryCondition>> const&
509 boundary_conditions = _project.getBoundaryConditions();
510 for (auto& bc : boundary_conditions)
511 {
512 if (bc->getProcessVarName() != name)
513 {
514 continue;
515 }
516 QDomElement bc_tag = doc.createElement("boundary_condition");
517 bc_list_tag.appendChild(bc_tag);
519 }
520}
521
523 QDomElement& st_list_tag,
524 std::string const& name) const
525{
526 std::vector<std::unique_ptr<DataHolderLib::SourceTerm>> const&
527 source_terms = _project.getSourceTerms();
528 for (auto& st : source_terms)
529 {
530 if (st->getProcessVarName() != name)
531 {
532 continue;
533 }
534 QDomElement st_tag = doc.createElement("source_term");
535 st_list_tag.appendChild(st_tag);
537 }
538}
539
541 QDomElement& root) const
542{
543 std::vector<DataHolderLib::ProcessVariable> const p_vars(
545
546 QDomElement param_list_tag = doc.createElement("parameters");
547 root.appendChild(param_list_tag);
548
549 QDomElement pvar_list_tag = doc.createElement("process_variables");
550 root.appendChild(pvar_list_tag);
551
552 for (DataHolderLib::ProcessVariable const& p_var : p_vars)
553 {
554 QDomElement pvar_tag = doc.createElement("process_variable");
555 pvar_list_tag.appendChild(pvar_tag);
556 addTextNode(doc, pvar_tag, "name", QString::fromStdString(p_var.name));
557 addTextNode(doc, pvar_tag, "order", QString::number(p_var.order));
558 addTextNode(doc, pvar_tag, "components",
559 QString::number(p_var.components));
560 QDomElement bc_list_tag = doc.createElement("boundary_conditions");
561 pvar_tag.appendChild(bc_list_tag);
562 writeBoundaryConditions(doc, bc_list_tag, p_var.name);
563 QDomElement st_list_tag = doc.createElement("source_terms");
564 pvar_tag.appendChild(st_list_tag);
565 writeSourceTerms(doc, st_list_tag, p_var.name);
566 }
567}
568} // 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 > variable_output_names)